1 <!-- doc/src/sgml/func.sgml -->
3 <chapter id="functions">
4 <title>Functions and Operators</title>
6 <indexterm zone="functions">
7 <primary>function</primary>
10 <indexterm zone="functions">
11 <primary>operator</primary>
15 <productname>PostgreSQL</productname> provides a large number of
16 functions and operators for the built-in data types. Users can also
17 define their own functions and operators, as described in
18 <xref linkend="server-programming">. The
19 <application>psql</application> commands <command>\df</command> and
20 <command>\do</command> can be used to list all
21 available functions and operators, respectively.
25 If you are concerned about portability then note that most of
26 the functions and operators described in this chapter, with the
27 exception of the most trivial arithmetic and comparison operators
28 and some explicitly marked functions, are not specified by the
29 <acronym>SQL</acronym> standard. Some of this extended functionality
30 is present in other <acronym>SQL</acronym> database management
31 systems, and in many cases this functionality is compatible and
32 consistent between the various implementations. This chapter is also
33 not exhaustive; additional functions appear in relevant sections of
38 <sect1 id="functions-logical">
39 <title>Logical Operators</title>
41 <indexterm zone="functions-logical">
42 <primary>operator</primary>
43 <secondary>logical</secondary>
47 <primary>Boolean</primary>
48 <secondary>operators</secondary>
49 <see>operators, logical</see>
53 The usual logical operators are available:
56 <primary>AND (operator)</primary>
60 <primary>OR (operator)</primary>
64 <primary>NOT (operator)</primary>
68 <primary>conjunction</primary>
72 <primary>disjunction</primary>
76 <primary>negation</primary>
80 <member><literal>AND</></member>
81 <member><literal>OR</></member>
82 <member><literal>NOT</></member>
85 <acronym>SQL</acronym> uses a three-valued logic system with true,
86 false, and <literal>null</>, which represents <quote>unknown</quote>.
87 Observe the following truth tables:
93 <entry><replaceable>a</replaceable></entry>
94 <entry><replaceable>b</replaceable></entry>
95 <entry><replaceable>a</replaceable> AND <replaceable>b</replaceable></entry>
96 <entry><replaceable>a</replaceable> OR <replaceable>b</replaceable></entry>
150 <entry><replaceable>a</replaceable></entry>
151 <entry>NOT <replaceable>a</replaceable></entry>
176 The operators <literal>AND</literal> and <literal>OR</literal> are
177 commutative, that is, you can switch the left and right operand
178 without affecting the result. But see <xref
179 linkend="syntax-express-eval"> for more information about the
180 order of evaluation of subexpressions.
184 <sect1 id="functions-comparison">
185 <title>Comparison Functions and Operators</title>
187 <indexterm zone="functions-comparison">
188 <primary>comparison</primary>
189 <secondary>operators</secondary>
193 The usual comparison operators are available, as shown in <xref
194 linkend="functions-comparison-op-table">.
197 <table id="functions-comparison-op-table">
198 <title>Comparison Operators</title>
202 <entry>Operator</entry>
203 <entry>Description</entry>
209 <entry> <literal><</literal> </entry>
210 <entry>less than</entry>
214 <entry> <literal>></literal> </entry>
215 <entry>greater than</entry>
219 <entry> <literal><=</literal> </entry>
220 <entry>less than or equal to</entry>
224 <entry> <literal>>=</literal> </entry>
225 <entry>greater than or equal to</entry>
229 <entry> <literal>=</literal> </entry>
234 <entry> <literal><></literal> or <literal>!=</literal> </entry>
235 <entry>not equal</entry>
243 The <literal>!=</literal> operator is converted to
244 <literal><></literal> in the parser stage. It is not
245 possible to implement <literal>!=</literal> and
246 <literal><></literal> operators that do different things.
251 Comparison operators are available for all relevant data types.
252 All comparison operators are binary operators that
253 return values of type <type>boolean</type>; expressions like
254 <literal>1 < 2 < 3</literal> are not valid (because there is
255 no <literal><</literal> operator to compare a Boolean value with
256 <literal>3</literal>).
261 <primary>BETWEEN</primary>
263 In addition to the comparison operators, the special
264 <token>BETWEEN</token> construct is available:
266 <replaceable>a</replaceable> BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
270 <replaceable>a</replaceable> >= <replaceable>x</replaceable> AND <replaceable>a</replaceable> <= <replaceable>y</replaceable>
272 Notice that <token>BETWEEN</token> treats the endpoint values as included
274 <literal>NOT BETWEEN</literal> does the opposite comparison:
276 <replaceable>a</replaceable> NOT BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
280 <replaceable>a</replaceable> < <replaceable>x</replaceable> OR <replaceable>a</replaceable> > <replaceable>y</replaceable>
283 <primary>BETWEEN SYMMETRIC</primary>
285 <literal>BETWEEN SYMMETRIC</> is the same as <literal>BETWEEN</>
286 except there is no requirement that the argument to the left of
287 <literal>AND</> be less than or equal to the argument on the right.
288 If it is not, those two arguments are automatically swapped, so that
289 a nonempty range is always implied.
294 <primary>IS NULL</primary>
297 <primary>IS NOT NULL</primary>
300 <primary>ISNULL</primary>
303 <primary>NOTNULL</primary>
305 To check whether a value is or is not null, use the constructs:
307 <replaceable>expression</replaceable> IS NULL
308 <replaceable>expression</replaceable> IS NOT NULL
310 or the equivalent, but nonstandard, constructs:
312 <replaceable>expression</replaceable> ISNULL
313 <replaceable>expression</replaceable> NOTNULL
315 <indexterm><primary>null value</primary><secondary>comparing</secondary></indexterm>
319 Do <emphasis>not</emphasis> write
320 <literal><replaceable>expression</replaceable> = NULL</literal>
321 because <literal>NULL</> is not <quote>equal to</quote>
322 <literal>NULL</>. (The null value represents an unknown value,
323 and it is not known whether two unknown values are equal.) This
324 behavior conforms to the SQL standard.
329 Some applications might expect that
330 <literal><replaceable>expression</replaceable> = NULL</literal>
331 returns true if <replaceable>expression</replaceable> evaluates to
332 the null value. It is highly recommended that these applications
333 be modified to comply with the SQL standard. However, if that
334 cannot be done the <xref linkend="guc-transform-null-equals">
335 configuration variable is available. If it is enabled,
336 <productname>PostgreSQL</productname> will convert <literal>x =
337 NULL</literal> clauses to <literal>x IS NULL</literal>.
343 If the <replaceable>expression</replaceable> is row-valued, then
344 <literal>IS NULL</> is true when the row expression itself is null
345 or when all the row's fields are null, while
346 <literal>IS NOT NULL</> is true when the row expression itself is non-null
347 and all the row's fields are non-null. Because of this behavior,
348 <literal>IS NULL</> and <literal>IS NOT NULL</> do not always return
349 inverse results for row-valued expressions, i.e., a row-valued
350 expression that contains both NULL and non-null values will return false
352 This definition conforms to the SQL standard, and is a change from the
353 inconsistent behavior exhibited by <productname>PostgreSQL</productname>
354 versions prior to 8.2.
360 <primary>IS DISTINCT FROM</primary>
363 <primary>IS NOT DISTINCT FROM</primary>
365 Ordinary comparison operators yield null (signifying <quote>unknown</>),
366 not true or false, when either input is null. For example,
367 <literal>7 = NULL</> yields null, as does <literal>7 <> NULL</>. When
368 this behavior is not suitable, use the
369 <literal>IS <optional> NOT </> DISTINCT FROM</literal> constructs:
371 <replaceable>expression</replaceable> IS DISTINCT FROM <replaceable>expression</replaceable>
372 <replaceable>expression</replaceable> IS NOT DISTINCT FROM <replaceable>expression</replaceable>
374 For non-null inputs, <literal>IS DISTINCT FROM</literal> is
375 the same as the <literal><></> operator. However, if both
376 inputs are null it returns false, and if only one input is
377 null it returns true. Similarly, <literal>IS NOT DISTINCT
378 FROM</literal> is identical to <literal>=</literal> for non-null
379 inputs, but it returns true when both inputs are null, and false when only
380 one input is null. Thus, these constructs effectively act as though null
381 were a normal data value, rather than <quote>unknown</>.
386 <primary>IS TRUE</primary>
389 <primary>IS NOT TRUE</primary>
392 <primary>IS FALSE</primary>
395 <primary>IS NOT FALSE</primary>
398 <primary>IS UNKNOWN</primary>
401 <primary>IS NOT UNKNOWN</primary>
403 Boolean values can also be tested using the constructs
405 <replaceable>expression</replaceable> IS TRUE
406 <replaceable>expression</replaceable> IS NOT TRUE
407 <replaceable>expression</replaceable> IS FALSE
408 <replaceable>expression</replaceable> IS NOT FALSE
409 <replaceable>expression</replaceable> IS UNKNOWN
410 <replaceable>expression</replaceable> IS NOT UNKNOWN
412 These will always return true or false, never a null value, even when the
414 A null input is treated as the logical value <quote>unknown</>.
415 Notice that <literal>IS UNKNOWN</> and <literal>IS NOT UNKNOWN</> are
416 effectively the same as <literal>IS NULL</literal> and
417 <literal>IS NOT NULL</literal>, respectively, except that the input
418 expression must be of Boolean type.
421 <!-- IS OF does not conform to the ISO SQL behavior, so it is undocumented here
424 <primary>IS OF</primary>
427 <primary>IS NOT OF</primary>
429 It is possible to check the data type of an expression using the
432 <replaceable>expression</replaceable> IS OF (typename, ...)
433 <replaceable>expression</replaceable> IS NOT OF (typename, ...)
435 They return a boolean value based on whether the expression's data
436 type is one of the listed data types.
441 Some comparison-related functions are also available, as shown in <xref
442 linkend="functions-comparison-func-table">.
445 <table id="functions-comparison-func-table">
446 <title>Comparison Functions</title>
450 <entry>Function</entry>
451 <entry>Description</entry>
452 <entry>Example</entry>
453 <entry>Example Result</entry>
460 <primary>num_nonnulls</primary>
462 <literal>num_nonnulls(VARIADIC "any")</literal>
464 <entry>returns the number of non-NULL arguments</entry>
465 <entry><literal>num_nonnulls(1, NULL, 2)</literal></entry>
466 <entry><literal>2</literal></entry>
471 <primary>num_nulls</primary>
473 <literal>num_nulls(VARIADIC "any")</literal>
475 <entry>returns the number of NULL arguments</entry>
476 <entry><literal>num_nulls(1, NULL, 2)</literal></entry>
477 <entry><literal>1</literal></entry>
485 <sect1 id="functions-math">
486 <title>Mathematical Functions and Operators</title>
489 Mathematical operators are provided for many
490 <productname>PostgreSQL</productname> types. For types without
491 standard mathematical conventions
492 (e.g., date/time types) we
493 describe the actual behavior in subsequent sections.
497 <xref linkend="functions-math-op-table"> shows the available mathematical operators.
500 <table id="functions-math-op-table">
501 <title>Mathematical Operators</title>
506 <entry>Operator</entry>
507 <entry>Description</entry>
508 <entry>Example</entry>
509 <entry>Result</entry>
515 <entry> <literal>+</literal> </entry>
516 <entry>addition</entry>
517 <entry><literal>2 + 3</literal></entry>
518 <entry><literal>5</literal></entry>
522 <entry> <literal>-</literal> </entry>
523 <entry>subtraction</entry>
524 <entry><literal>2 - 3</literal></entry>
525 <entry><literal>-1</literal></entry>
529 <entry> <literal>*</literal> </entry>
530 <entry>multiplication</entry>
531 <entry><literal>2 * 3</literal></entry>
532 <entry><literal>6</literal></entry>
536 <entry> <literal>/</literal> </entry>
537 <entry>division (integer division truncates the result)</entry>
538 <entry><literal>4 / 2</literal></entry>
539 <entry><literal>2</literal></entry>
543 <entry> <literal>%</literal> </entry>
544 <entry>modulo (remainder)</entry>
545 <entry><literal>5 % 4</literal></entry>
546 <entry><literal>1</literal></entry>
550 <entry> <literal>^</literal> </entry>
551 <entry>exponentiation (associates left to right)</entry>
552 <entry><literal>2.0 ^ 3.0</literal></entry>
553 <entry><literal>8</literal></entry>
557 <entry> <literal>|/</literal> </entry>
558 <entry>square root</entry>
559 <entry><literal>|/ 25.0</literal></entry>
560 <entry><literal>5</literal></entry>
564 <entry> <literal>||/</literal> </entry>
565 <entry>cube root</entry>
566 <entry><literal>||/ 27.0</literal></entry>
567 <entry><literal>3</literal></entry>
571 <entry> <literal>!</literal> </entry>
572 <entry>factorial</entry>
573 <entry><literal>5 !</literal></entry>
574 <entry><literal>120</literal></entry>
578 <entry> <literal>!!</literal> </entry>
579 <entry>factorial (prefix operator)</entry>
580 <entry><literal>!! 5</literal></entry>
581 <entry><literal>120</literal></entry>
585 <entry> <literal>@</literal> </entry>
586 <entry>absolute value</entry>
587 <entry><literal>@ -5.0</literal></entry>
588 <entry><literal>5</literal></entry>
592 <entry> <literal>&</literal> </entry>
593 <entry>bitwise AND</entry>
594 <entry><literal>91 & 15</literal></entry>
595 <entry><literal>11</literal></entry>
599 <entry> <literal>|</literal> </entry>
600 <entry>bitwise OR</entry>
601 <entry><literal>32 | 3</literal></entry>
602 <entry><literal>35</literal></entry>
606 <entry> <literal>#</literal> </entry>
607 <entry>bitwise XOR</entry>
608 <entry><literal>17 # 5</literal></entry>
609 <entry><literal>20</literal></entry>
613 <entry> <literal>~</literal> </entry>
614 <entry>bitwise NOT</entry>
615 <entry><literal>~1</literal></entry>
616 <entry><literal>-2</literal></entry>
620 <entry> <literal><<</literal> </entry>
621 <entry>bitwise shift left</entry>
622 <entry><literal>1 << 4</literal></entry>
623 <entry><literal>16</literal></entry>
627 <entry> <literal>>></literal> </entry>
628 <entry>bitwise shift right</entry>
629 <entry><literal>8 >> 2</literal></entry>
630 <entry><literal>2</literal></entry>
638 The bitwise operators work only on integral data types, whereas
639 the others are available for all numeric data types. The bitwise
640 operators are also available for the bit
641 string types <type>bit</type> and <type>bit varying</type>, as
642 shown in <xref linkend="functions-bit-string-op-table">.
646 <xref linkend="functions-math-func-table"> shows the available
647 mathematical functions. In the table, <literal>dp</literal>
648 indicates <type>double precision</type>. Many of these functions
649 are provided in multiple forms with different argument types.
650 Except where noted, any given form of a function returns the same
651 data type as its argument.
652 The functions working with <type>double precision</type> data are mostly
653 implemented on top of the host system's C library; accuracy and behavior in
654 boundary cases can therefore vary depending on the host system.
657 <table id="functions-math-func-table">
658 <title>Mathematical Functions</title>
662 <entry>Function</entry>
663 <entry>Return Type</entry>
664 <entry>Description</entry>
665 <entry>Example</entry>
666 <entry>Result</entry>
674 <primary>abs</primary>
676 <literal><function>abs(<replaceable>x</replaceable>)</function></literal>
678 <entry>(same as input)</entry>
679 <entry>absolute value</entry>
680 <entry><literal>abs(-17.4)</literal></entry>
681 <entry><literal>17.4</literal></entry>
687 <primary>cbrt</primary>
689 <literal><function>cbrt(<type>dp</type>)</function></literal>
691 <entry><type>dp</type></entry>
692 <entry>cube root</entry>
693 <entry><literal>cbrt(27.0)</literal></entry>
694 <entry><literal>3</literal></entry>
700 <primary>ceil</primary>
702 <literal><function>ceil(<type>dp</type> or <type>numeric</type>)</function></literal>
704 <entry>(same as input)</entry>
705 <entry>smallest integer not less than argument</entry>
706 <entry><literal>ceil(-42.8)</literal></entry>
707 <entry><literal>-42</literal></entry>
713 <primary>ceiling</primary>
715 <literal><function>ceiling(<type>dp</type> or <type>numeric</type>)</function></literal>
717 <entry>(same as input)</entry>
718 <entry>smallest integer not less than argument (alias for <function>ceil</function>)</entry>
719 <entry><literal>ceiling(-95.3)</literal></entry>
720 <entry><literal>-95</literal></entry>
726 <primary>degrees</primary>
728 <literal><function>degrees(<type>dp</type>)</function></literal>
730 <entry><type>dp</type></entry>
731 <entry>radians to degrees</entry>
732 <entry><literal>degrees(0.5)</literal></entry>
733 <entry><literal>28.6478897565412</literal></entry>
739 <primary>div</primary>
741 <literal><function>div(<parameter>y</parameter> <type>numeric</>,
742 <parameter>x</parameter> <type>numeric</>)</function></literal>
744 <entry><type>numeric</></entry>
745 <entry>integer quotient of <parameter>y</parameter>/<parameter>x</parameter></entry>
746 <entry><literal>div(9,4)</literal></entry>
747 <entry><literal>2</literal></entry>
753 <primary>exp</primary>
755 <literal><function>exp(<type>dp</type> or <type>numeric</type>)</function></literal>
757 <entry>(same as input)</entry>
758 <entry>exponential</entry>
759 <entry><literal>exp(1.0)</literal></entry>
760 <entry><literal>2.71828182845905</literal></entry>
766 <primary>floor</primary>
768 <literal><function>floor(<type>dp</type> or <type>numeric</type>)</function></literal>
770 <entry>(same as input)</entry>
771 <entry>largest integer not greater than argument</entry>
772 <entry><literal>floor(-42.8)</literal></entry>
773 <entry><literal>-43</literal></entry>
779 <primary>ln</primary>
781 <literal><function>ln(<type>dp</type> or <type>numeric</type>)</function></literal>
783 <entry>(same as input)</entry>
784 <entry>natural logarithm</entry>
785 <entry><literal>ln(2.0)</literal></entry>
786 <entry><literal>0.693147180559945</literal></entry>
792 <primary>log</primary>
794 <literal><function>log(<type>dp</type> or <type>numeric</type>)</function></literal>
796 <entry>(same as input)</entry>
797 <entry>base 10 logarithm</entry>
798 <entry><literal>log(100.0)</literal></entry>
799 <entry><literal>2</literal></entry>
803 <entry><literal><function>log(<parameter>b</parameter> <type>numeric</type>,
804 <parameter>x</parameter> <type>numeric</type>)</function></literal></entry>
805 <entry><type>numeric</type></entry>
806 <entry>logarithm to base <parameter>b</parameter></entry>
807 <entry><literal>log(2.0, 64.0)</literal></entry>
808 <entry><literal>6.0000000000</literal></entry>
814 <primary>mod</primary>
816 <literal><function>mod(<parameter>y</parameter>,
817 <parameter>x</parameter>)</function></literal>
819 <entry>(same as argument types)</entry>
820 <entry>remainder of <parameter>y</parameter>/<parameter>x</parameter></entry>
821 <entry><literal>mod(9,4)</literal></entry>
822 <entry><literal>1</literal></entry>
828 <primary>pi</primary>
830 <literal><function>pi()</function></literal>
832 <entry><type>dp</type></entry>
833 <entry><quote>π</quote> constant</entry>
834 <entry><literal>pi()</literal></entry>
835 <entry><literal>3.14159265358979</literal></entry>
841 <primary>power</primary>
843 <literal><function>power(<parameter>a</parameter> <type>dp</type>,
844 <parameter>b</parameter> <type>dp</type>)</function></literal>
846 <entry><type>dp</type></entry>
847 <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
848 <entry><literal>power(9.0, 3.0)</literal></entry>
849 <entry><literal>729</literal></entry>
853 <entry><literal><function>power(<parameter>a</parameter> <type>numeric</type>,
854 <parameter>b</parameter> <type>numeric</type>)</function></literal></entry>
855 <entry><type>numeric</type></entry>
856 <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
857 <entry><literal>power(9.0, 3.0)</literal></entry>
858 <entry><literal>729</literal></entry>
864 <primary>radians</primary>
866 <literal><function>radians(<type>dp</type>)</function></literal>
868 <entry><type>dp</type></entry>
869 <entry>degrees to radians</entry>
870 <entry><literal>radians(45.0)</literal></entry>
871 <entry><literal>0.785398163397448</literal></entry>
877 <primary>round</primary>
879 <literal><function>round(<type>dp</type> or <type>numeric</type>)</function></literal>
881 <entry>(same as input)</entry>
882 <entry>round to nearest integer</entry>
883 <entry><literal>round(42.4)</literal></entry>
884 <entry><literal>42</literal></entry>
888 <entry><literal><function>round(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</function></literal></entry>
889 <entry><type>numeric</type></entry>
890 <entry>round to <parameter>s</parameter> decimal places</entry>
891 <entry><literal>round(42.4382, 2)</literal></entry>
892 <entry><literal>42.44</literal></entry>
898 <primary>scale</primary>
900 <literal><function>scale(<type>numeric</type>)</function></literal>
902 <entry><type>numeric</type></entry>
903 <entry>scale of the argument (the number of decimal digits in the fractional part)</entry>
904 <entry><literal>scale(8.41)</literal></entry>
905 <entry><literal>2</literal></entry>
911 <primary>sign</primary>
913 <literal><function>sign(<type>dp</type> or <type>numeric</type>)</function></literal>
915 <entry>(same as input)</entry>
916 <entry>sign of the argument (-1, 0, +1)</entry>
917 <entry><literal>sign(-8.4)</literal></entry>
918 <entry><literal>-1</literal></entry>
924 <primary>sqrt</primary>
926 <literal><function>sqrt(<type>dp</type> or <type>numeric</type>)</function></literal>
928 <entry>(same as input)</entry>
929 <entry>square root</entry>
930 <entry><literal>sqrt(2.0)</literal></entry>
931 <entry><literal>1.4142135623731</literal></entry>
937 <primary>trunc</primary>
939 <literal><function>trunc(<type>dp</type> or <type>numeric</type>)</function></literal>
941 <entry>(same as input)</entry>
942 <entry>truncate toward zero</entry>
943 <entry><literal>trunc(42.8)</literal></entry>
944 <entry><literal>42</literal></entry>
948 <entry><literal><function>trunc(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</function></literal></entry>
949 <entry><type>numeric</type></entry>
950 <entry>truncate to <parameter>s</parameter> decimal places</entry>
951 <entry><literal>trunc(42.4382, 2)</literal></entry>
952 <entry><literal>42.43</literal></entry>
958 <primary>width_bucket</primary>
960 <literal><function>width_bucket(<parameter>operand</parameter> <type>dp</type>, <parameter>b1</parameter> <type>dp</type>, <parameter>b2</parameter> <type>dp</type>, <parameter>count</parameter> <type>int</type>)</function></literal></entry>
961 <entry><type>int</type></entry>
962 <entry>return the bucket number to which <parameter>operand</> would
963 be assigned in a histogram having <parameter>count</> equal-width
964 buckets spanning the range <parameter>b1</> to <parameter>b2</>;
965 returns <literal>0</> or <literal><parameter>count</>+1</literal> for
966 an input outside the range</entry>
967 <entry><literal>width_bucket(5.35, 0.024, 10.06, 5)</literal></entry>
968 <entry><literal>3</literal></entry>
972 <entry><literal><function>width_bucket(<parameter>operand</parameter> <type>numeric</type>, <parameter>b1</parameter> <type>numeric</type>, <parameter>b2</parameter> <type>numeric</type>, <parameter>count</parameter> <type>int</type>)</function></literal></entry>
973 <entry><type>int</type></entry>
974 <entry>return the bucket number to which <parameter>operand</> would
975 be assigned in a histogram having <parameter>count</> equal-width
976 buckets spanning the range <parameter>b1</> to <parameter>b2</>;
977 returns <literal>0</> or <literal><parameter>count</>+1</literal> for
978 an input outside the range</entry>
979 <entry><literal>width_bucket(5.35, 0.024, 10.06, 5)</literal></entry>
980 <entry><literal>3</literal></entry>
984 <entry><literal><function>width_bucket(<parameter>operand</parameter> <type>anyelement</type>, <parameter>thresholds</parameter> <type>anyarray</type>)</function></literal></entry>
985 <entry><type>int</type></entry>
986 <entry>return the bucket number to which <parameter>operand</> would
987 be assigned given an array listing the lower bounds of the buckets;
988 returns <literal>0</> for an input less than the first lower bound;
989 the <parameter>thresholds</> array <emphasis>must be sorted</>,
990 smallest first, or unexpected results will be obtained</entry>
991 <entry><literal>width_bucket(now(), array['yesterday', 'today', 'tomorrow']::timestamptz[])</literal></entry>
992 <entry><literal>2</literal></entry>
999 <xref linkend="functions-math-random-table"> shows functions for
1000 generating random numbers.
1003 <table id="functions-math-random-table">
1004 <title>Random Functions</title>
1009 <entry>Function</entry>
1010 <entry>Return Type</entry>
1011 <entry>Description</entry>
1018 <primary>random</primary>
1020 <literal><function>random()</function></literal>
1022 <entry><type>dp</type></entry>
1023 <entry>random value in the range 0.0 <= x < 1.0</entry>
1029 <primary>setseed</primary>
1031 <literal><function>setseed(<type>dp</type>)</function></literal>
1033 <entry><type>void</type></entry>
1034 <entry>set seed for subsequent <literal>random()</literal> calls (value between -1.0 and
1035 1.0, inclusive)</entry>
1042 The characteristics of the values returned by
1043 <literal><function>random()</function></literal> depend
1044 on the system implementation. It is not suitable for cryptographic
1045 applications; see <xref linkend="pgcrypto"> module for an alternative.
1049 Finally, <xref linkend="functions-math-trig-table"> shows the
1050 available trigonometric functions. All trigonometric functions
1051 take arguments and return values of type <type>double
1052 precision</type>. Each of the trigonometric functions comes in
1053 two variants, one that measures angles in radians and one that
1054 measures angles in degrees.
1057 <table id="functions-math-trig-table">
1058 <title>Trigonometric Functions</title>
1063 <entry>Function (radians)</entry>
1064 <entry>Function (degrees)</entry>
1065 <entry>Description</entry>
1073 <primary>acos</primary>
1074 </indexterm><literal><function>acos(<replaceable>x</replaceable>)</function></literal>
1078 <primary>acosd</primary>
1079 </indexterm><literal><function>acosd(<replaceable>x</replaceable>)</function></literal>
1081 <entry>inverse cosine</entry>
1087 <primary>asin</primary>
1089 <literal><function>asin(<replaceable>x</replaceable>)</function></literal>
1093 <primary>asind</primary>
1095 <literal><function>asind(<replaceable>x</replaceable>)</function></literal>
1097 <entry>inverse sine</entry>
1103 <primary>atan</primary>
1105 <literal><function>atan(<replaceable>x</replaceable>)</function></literal>
1109 <primary>atand</primary>
1111 <literal><function>atand(<replaceable>x</replaceable>)</function></literal>
1113 <entry>inverse tangent</entry>
1119 <primary>atan2</primary>
1121 <literal><function>atan2(<replaceable>y</replaceable>,
1122 <replaceable>x</replaceable>)</function></literal>
1126 <primary>atan2d</primary>
1128 <literal><function>atan2d(<replaceable>y</replaceable>,
1129 <replaceable>x</replaceable>)</function></literal>
1131 <entry>inverse tangent of
1132 <literal><replaceable>y</replaceable>/<replaceable>x</replaceable></literal></entry>
1138 <primary>cos</primary>
1140 <literal><function>cos(<replaceable>x</replaceable>)</function></literal>
1144 <primary>cosd</primary>
1146 <literal><function>cosd(<replaceable>x</replaceable>)</function></literal>
1148 <entry>cosine</entry>
1154 <primary>cot</primary>
1156 <literal><function>cot(<replaceable>x</replaceable>)</function></literal>
1160 <primary>cotd</primary>
1162 <literal><function>cotd(<replaceable>x</replaceable>)</function></literal>
1164 <entry>cotangent</entry>
1170 <primary>sin</primary>
1172 <literal><function>sin(<replaceable>x</replaceable>)</function></literal>
1176 <primary>sind</primary>
1178 <literal><function>sind(<replaceable>x</replaceable>)</function></literal>
1186 <primary>tan</primary>
1188 <literal><function>tan(<replaceable>x</replaceable>)</function></literal>
1192 <primary>tand</primary>
1194 <literal><function>tand(<replaceable>x</replaceable>)</function></literal>
1196 <entry>tangent</entry>
1204 Another way to work with angles measured in degrees is to use the unit
1205 transformation functions <literal><function>radians()</function></literal>
1206 and <literal><function>degrees()</function></literal> shown earlier.
1207 However, using the degree-based trigonometric functions is preferred,
1208 as that way avoids roundoff error for special cases such
1209 as <literal>sind(30)</>.
1216 <sect1 id="functions-string">
1217 <title>String Functions and Operators</title>
1220 This section describes functions and operators for examining and
1221 manipulating string values. Strings in this context include values
1222 of the types <type>character</type>, <type>character varying</type>,
1223 and <type>text</type>. Unless otherwise noted, all
1224 of the functions listed below work on all of these types, but be
1225 wary of potential effects of automatic space-padding when using the
1226 <type>character</type> type. Some functions also exist
1227 natively for the bit-string types.
1231 <acronym>SQL</acronym> defines some string functions that use
1232 key words, rather than commas, to separate
1233 arguments. Details are in
1234 <xref linkend="functions-string-sql">.
1235 <productname>PostgreSQL</> also provides versions of these functions
1236 that use the regular function invocation syntax
1237 (see <xref linkend="functions-string-other">).
1242 Before <productname>PostgreSQL</productname> 8.3, these functions would
1243 silently accept values of several non-string data types as well, due to
1244 the presence of implicit coercions from those data types to
1245 <type>text</>. Those coercions have been removed because they frequently
1246 caused surprising behaviors. However, the string concatenation operator
1247 (<literal>||</>) still accepts non-string input, so long as at least one
1248 input is of a string type, as shown in <xref
1249 linkend="functions-string-sql">. For other cases, insert an explicit
1250 coercion to <type>text</> if you need to duplicate the previous behavior.
1254 <table id="functions-string-sql">
1255 <title><acronym>SQL</acronym> String Functions and Operators</title>
1259 <entry>Function</entry>
1260 <entry>Return Type</entry>
1261 <entry>Description</entry>
1262 <entry>Example</entry>
1263 <entry>Result</entry>
1269 <entry><literal><parameter>string</parameter> <literal>||</literal>
1270 <parameter>string</parameter></literal></entry>
1271 <entry> <type>text</type> </entry>
1273 String concatenation
1275 <primary>character string</primary>
1276 <secondary>concatenation</secondary>
1279 <entry><literal>'Post' || 'greSQL'</literal></entry>
1280 <entry><literal>PostgreSQL</literal></entry>
1285 <literal><parameter>string</parameter> <literal>||</literal>
1286 <parameter>non-string</parameter></literal>
1288 <literal><parameter>non-string</parameter> <literal>||</literal>
1289 <parameter>string</parameter></literal>
1291 <entry> <type>text</type> </entry>
1293 String concatenation with one non-string input
1295 <entry><literal>'Value: ' || 42</literal></entry>
1296 <entry><literal>Value: 42</literal></entry>
1302 <primary>bit_length</primary>
1304 <literal><function>bit_length(<parameter>string</parameter>)</function></literal>
1306 <entry><type>int</type></entry>
1307 <entry>Number of bits in string</entry>
1308 <entry><literal>bit_length('jose')</literal></entry>
1309 <entry><literal>32</literal></entry>
1315 <primary>char_length</primary>
1317 <literal><function>char_length(<parameter>string</parameter>)</function></literal> or <literal><function>character_length(<parameter>string</parameter>)</function></literal>
1319 <entry><type>int</type></entry>
1321 Number of characters in string
1323 <primary>character string</primary>
1324 <secondary>length</secondary>
1327 <primary>length</primary>
1328 <secondary sortas="character string">of a character string</secondary>
1329 <see>character string, length</see>
1332 <entry><literal>char_length('jose')</literal></entry>
1333 <entry><literal>4</literal></entry>
1339 <primary>lower</primary>
1341 <literal><function>lower(<parameter>string</parameter>)</function></literal>
1343 <entry><type>text</type></entry>
1344 <entry>Convert string to lower case</entry>
1345 <entry><literal>lower('TOM')</literal></entry>
1346 <entry><literal>tom</literal></entry>
1352 <primary>octet_length</primary>
1354 <literal><function>octet_length(<parameter>string</parameter>)</function></literal>
1356 <entry><type>int</type></entry>
1357 <entry>Number of bytes in string</entry>
1358 <entry><literal>octet_length('jose')</literal></entry>
1359 <entry><literal>4</literal></entry>
1365 <primary>overlay</primary>
1367 <literal><function>overlay(<parameter>string</parameter> placing <parameter>string</parameter> from <type>int</type> <optional>for <type>int</type></optional>)</function></literal>
1369 <entry><type>text</type></entry>
1373 <entry><literal>overlay('Txxxxas' placing 'hom' from 2 for 4)</literal></entry>
1374 <entry><literal>Thomas</literal></entry>
1380 <primary>position</primary>
1382 <literal><function>position(<parameter>substring</parameter> in <parameter>string</parameter>)</function></literal>
1384 <entry><type>int</type></entry>
1385 <entry>Location of specified substring</entry>
1386 <entry><literal>position('om' in 'Thomas')</literal></entry>
1387 <entry><literal>3</literal></entry>
1393 <primary>substring</primary>
1395 <literal><function>substring(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</function></literal>
1397 <entry><type>text</type></entry>
1401 <entry><literal>substring('Thomas' from 2 for 3)</literal></entry>
1402 <entry><literal>hom</literal></entry>
1406 <entry><literal><function>substring(<parameter>string</parameter> from <replaceable>pattern</replaceable>)</function></literal></entry>
1407 <entry><type>text</type></entry>
1409 Extract substring matching POSIX regular expression. See
1410 <xref linkend="functions-matching"> for more information on pattern
1413 <entry><literal>substring('Thomas' from '...$')</literal></entry>
1414 <entry><literal>mas</literal></entry>
1418 <entry><literal><function>substring(<parameter>string</parameter> from <replaceable>pattern</replaceable> for <replaceable>escape</replaceable>)</function></literal></entry>
1419 <entry><type>text</type></entry>
1421 Extract substring matching <acronym>SQL</acronym> regular expression.
1422 See <xref linkend="functions-matching"> for more information on
1425 <entry><literal>substring('Thomas' from '%#"o_a#"_' for '#')</literal></entry>
1426 <entry><literal>oma</literal></entry>
1432 <primary>trim</primary>
1434 <literal><function>trim(<optional>leading | trailing | both</optional>
1435 <optional><parameter>characters</parameter></optional> from
1436 <parameter>string</parameter>)</function></literal>
1438 <entry><type>text</type></entry>
1440 Remove the longest string containing only the
1441 <parameter>characters</parameter> (a space by default) from the
1442 start/end/both ends of the <parameter>string</parameter>
1444 <entry><literal>trim(both 'x' from 'xTomxx')</literal></entry>
1445 <entry><literal>Tom</literal></entry>
1450 <literal><function>trim(<optional>leading | trailing
1451 | both</optional> <optional>from</optional>
1452 <parameter>string</parameter>
1453 <optional><parameter>, characters</parameter></optional>
1454 )</function></literal>
1456 <entry><type>text</type></entry>
1458 Non-standard version of <function>trim()</>
1460 <entry><literal>trim(both from 'xTomxx', 'x')</literal></entry>
1461 <entry><literal>Tom</literal></entry>
1467 <primary>upper</primary>
1469 <literal><function>upper(<parameter>string</parameter>)</function></literal>
1471 <entry><type>text</type></entry>
1472 <entry>Convert string to upper case</entry>
1473 <entry><literal>upper('tom')</literal></entry>
1474 <entry><literal>TOM</literal></entry>
1481 Additional string manipulation functions are available and are
1482 listed in <xref linkend="functions-string-other">. Some of them are used internally to implement the
1483 <acronym>SQL</acronym>-standard string functions listed in <xref linkend="functions-string-sql">.
1486 <table id="functions-string-other">
1487 <title>Other String Functions</title>
1491 <entry>Function</entry>
1492 <entry>Return Type</entry>
1493 <entry>Description</entry>
1494 <entry>Example</entry>
1495 <entry>Result</entry>
1503 <primary>ascii</primary>
1505 <literal><function>ascii(<parameter>string</parameter>)</function></literal>
1507 <entry><type>int</type></entry>
1509 <acronym>ASCII</acronym> code of the first character of the
1510 argument. For <acronym>UTF8</acronym> returns the Unicode code
1511 point of the character. For other multibyte encodings, the
1512 argument must be an <acronym>ASCII</acronym> character.
1514 <entry><literal>ascii('x')</literal></entry>
1515 <entry><literal>120</literal></entry>
1521 <primary>btrim</primary>
1523 <literal><function>btrim(<parameter>string</parameter> <type>text</type>
1524 <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
1526 <entry><type>text</type></entry>
1528 Remove the longest string consisting only of characters
1529 in <parameter>characters</parameter> (a space by default)
1530 from the start and end of <parameter>string</parameter>
1532 <entry><literal>btrim('xyxtrimyyx', 'xy')</literal></entry>
1533 <entry><literal>trim</literal></entry>
1539 <primary>chr</primary>
1541 <literal><function>chr(<type>int</type>)</function></literal>
1543 <entry><type>text</type></entry>
1545 Character with the given code. For <acronym>UTF8</acronym> the
1546 argument is treated as a Unicode code point. For other multibyte
1547 encodings the argument must designate an
1548 <acronym>ASCII</acronym> character. The NULL (0) character is not
1549 allowed because text data types cannot store such bytes.
1551 <entry><literal>chr(65)</literal></entry>
1552 <entry><literal>A</literal></entry>
1558 <primary>concat</primary>
1560 <literal><function>concat(<parameter>str</parameter> <type>"any"</type>
1561 [, <parameter>str</parameter> <type>"any"</type> [, ...] ])</function></literal>
1563 <entry><type>text</type></entry>
1565 Concatenate the text representations of all the arguments.
1566 NULL arguments are ignored.
1568 <entry><literal>concat('abcde', 2, NULL, 22)</literal></entry>
1569 <entry><literal>abcde222</literal></entry>
1575 <primary>concat_ws</primary>
1577 <literal><function>concat_ws(<parameter>sep</parameter> <type>text</type>,
1578 <parameter>str</parameter> <type>"any"</type>
1579 [, <parameter>str</parameter> <type>"any"</type> [, ...] ])</function></literal>
1581 <entry><type>text</type></entry>
1583 Concatenate all but the first argument with separators. The first
1584 argument is used as the separator string. NULL arguments are ignored.
1586 <entry><literal>concat_ws(',', 'abcde', 2, NULL, 22)</literal></entry>
1587 <entry><literal>abcde,2,22</literal></entry>
1593 <primary>convert</primary>
1595 <literal><function>convert(<parameter>string</parameter> <type>bytea</type>,
1596 <parameter>src_encoding</parameter> <type>name</type>,
1597 <parameter>dest_encoding</parameter> <type>name</type>)</function></literal>
1599 <entry><type>bytea</type></entry>
1601 Convert string to <parameter>dest_encoding</parameter>. The
1602 original encoding is specified by
1603 <parameter>src_encoding</parameter>. The
1604 <parameter>string</parameter> must be valid in this encoding.
1605 Conversions can be defined by <command>CREATE CONVERSION</command>.
1606 Also there are some predefined conversions. See <xref
1607 linkend="conversion-names"> for available conversions.
1609 <entry><literal>convert('text_in_utf8', 'UTF8', 'LATIN1')</literal></entry>
1610 <entry><literal>text_in_utf8</literal> represented in Latin-1
1611 encoding (ISO 8859-1)</entry>
1617 <primary>convert_from</primary>
1619 <literal><function>convert_from(<parameter>string</parameter> <type>bytea</type>,
1620 <parameter>src_encoding</parameter> <type>name</type>)</function></literal>
1622 <entry><type>text</type></entry>
1624 Convert string to the database encoding. The original encoding
1625 is specified by <parameter>src_encoding</parameter>. The
1626 <parameter>string</parameter> must be valid in this encoding.
1628 <entry><literal>convert_from('text_in_utf8', 'UTF8')</literal></entry>
1629 <entry><literal>text_in_utf8</literal> represented in the current database encoding</entry>
1635 <primary>convert_to</primary>
1637 <literal><function>convert_to(<parameter>string</parameter> <type>text</type>,
1638 <parameter>dest_encoding</parameter> <type>name</type>)</function></literal>
1640 <entry><type>bytea</type></entry>
1642 Convert string to <parameter>dest_encoding</parameter>.
1644 <entry><literal>convert_to('some text', 'UTF8')</literal></entry>
1645 <entry><literal>some text</literal> represented in the UTF8 encoding</entry>
1651 <primary>decode</primary>
1653 <literal><function>decode(<parameter>string</parameter> <type>text</type>,
1654 <parameter>format</parameter> <type>text</type>)</function></literal>
1656 <entry><type>bytea</type></entry>
1658 Decode binary data from textual representation in <parameter>string</>.
1659 Options for <parameter>format</> are same as in <function>encode</>.
1661 <entry><literal>decode('MTIzAAE=', 'base64')</literal></entry>
1662 <entry><literal>\x3132330001</literal></entry>
1668 <primary>encode</primary>
1670 <literal><function>encode(<parameter>data</parameter> <type>bytea</type>,
1671 <parameter>format</parameter> <type>text</type>)</function></literal>
1673 <entry><type>text</type></entry>
1675 Encode binary data into a textual representation. Supported
1676 formats are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
1677 <literal>escape</> converts zero bytes and high-bit-set bytes to
1678 octal sequences (<literal>\</><replaceable>nnn</>) and
1679 doubles backslashes.
1681 <entry><literal>encode(E'123\\000\\001', 'base64')</literal></entry>
1682 <entry><literal>MTIzAAE=</literal></entry>
1688 <primary>format</primary>
1690 <literal><function>format</function>(<parameter>formatstr</parameter> <type>text</type>
1691 [, <parameter>formatarg</parameter> <type>"any"</type> [, ...] ])</literal>
1693 <entry><type>text</type></entry>
1695 Format arguments according to a format string.
1696 This function is similar to the C function <function>sprintf</>.
1697 See <xref linkend="functions-string-format">.
1699 <entry><literal>format('Hello %s, %1$s', 'World')</literal></entry>
1700 <entry><literal>Hello World, World</literal></entry>
1706 <primary>initcap</primary>
1708 <literal><function>initcap(<parameter>string</parameter>)</function></literal>
1710 <entry><type>text</type></entry>
1712 Convert the first letter of each word to upper case and the
1713 rest to lower case. Words are sequences of alphanumeric
1714 characters separated by non-alphanumeric characters.
1716 <entry><literal>initcap('hi THOMAS')</literal></entry>
1717 <entry><literal>Hi Thomas</literal></entry>
1723 <primary>left</primary>
1725 <literal><function>left(<parameter>str</parameter> <type>text</type>,
1726 <parameter>n</parameter> <type>int</type>)</function></literal>
1728 <entry><type>text</type></entry>
1730 Return first <replaceable>n</> characters in the string. When <replaceable>n</>
1731 is negative, return all but last |<replaceable>n</>| characters.
1733 <entry><literal>left('abcde', 2)</literal></entry>
1734 <entry><literal>ab</literal></entry>
1740 <primary>length</primary>
1742 <literal><function>length(<parameter>string</parameter>)</function></literal>
1744 <entry><type>int</type></entry>
1746 Number of characters in <parameter>string</parameter>
1748 <entry><literal>length('jose')</literal></entry>
1749 <entry><literal>4</literal></entry>
1753 <entry><literal><function>length(<parameter>string</parameter> <type>bytea</type>,
1754 <parameter>encoding</parameter> <type>name</type> )</function></literal></entry>
1755 <entry><type>int</type></entry>
1757 Number of characters in <parameter>string</parameter> in the given
1758 <parameter>encoding</parameter>. The <parameter>string</parameter>
1759 must be valid in this encoding.
1761 <entry><literal>length('jose', 'UTF8')</literal></entry>
1762 <entry><literal>4</literal></entry>
1768 <primary>lpad</primary>
1770 <literal><function>lpad(<parameter>string</parameter> <type>text</type>,
1771 <parameter>length</parameter> <type>int</type>
1772 <optional>, <parameter>fill</parameter> <type>text</type></optional>)</function></literal>
1774 <entry><type>text</type></entry>
1776 Fill up the <parameter>string</parameter> to length
1777 <parameter>length</parameter> by prepending the characters
1778 <parameter>fill</parameter> (a space by default). If the
1779 <parameter>string</parameter> is already longer than
1780 <parameter>length</parameter> then it is truncated (on the
1783 <entry><literal>lpad('hi', 5, 'xy')</literal></entry>
1784 <entry><literal>xyxhi</literal></entry>
1790 <primary>ltrim</primary>
1792 <literal><function>ltrim(<parameter>string</parameter> <type>text</type>
1793 <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
1795 <entry><type>text</type></entry>
1797 Remove the longest string containing only characters from
1798 <parameter>characters</parameter> (a space by default) from the start of
1799 <parameter>string</parameter>
1801 <entry><literal>ltrim('zzzytrim', 'xyz')</literal></entry>
1802 <entry><literal>trim</literal></entry>
1808 <primary>md5</primary>
1810 <literal><function>md5(<parameter>string</parameter>)</function></literal>
1812 <entry><type>text</type></entry>
1814 Calculates the MD5 hash of <parameter>string</parameter>,
1815 returning the result in hexadecimal
1817 <entry><literal>md5('abc')</literal></entry>
1818 <entry><literal>900150983cd24fb0 d6963f7d28e17f72</literal></entry>
1824 <primary>parse_ident</primary>
1826 <literal><function>parse_ident(<parameter>qualified_identifier</parameter> <type>text</type>
1827 [, <parameter>strictmode</parameter> <type>boolean</type> DEFAULT true ] )</function></literal>
1829 <entry><type>text[]</type></entry>
1831 Split <parameter>qualified_identifier</parameter> into an array of
1832 identifiers, removing any quoting of individual identifiers. By
1833 default, extra characters after the last identifier are considered an
1834 error; but if the second parameter is <literal>false</>, then such
1835 extra characters are ignored. (This behavior is useful for parsing
1836 names for objects like functions.) Note that this function does not
1837 truncate over-length identifiers. If you want truncation you can cast
1838 the result to <type>name[]</>.
1840 <entry><literal>parse_ident('"SomeSchema".someTable')</literal></entry>
1841 <entry><literal>{SomeSchema,sometable}</literal></entry>
1847 <primary>pg_client_encoding</primary>
1849 <literal><function>pg_client_encoding()</function></literal>
1851 <entry><type>name</type></entry>
1853 Current client encoding name
1855 <entry><literal>pg_client_encoding()</literal></entry>
1856 <entry><literal>SQL_ASCII</literal></entry>
1862 <primary>quote_ident</primary>
1864 <literal><function>quote_ident(<parameter>string</parameter> <type>text</type>)</function></literal>
1866 <entry><type>text</type></entry>
1868 Return the given string suitably quoted to be used as an identifier
1869 in an <acronym>SQL</acronym> statement string.
1870 Quotes are added only if necessary (i.e., if the string contains
1871 non-identifier characters or would be case-folded).
1872 Embedded quotes are properly doubled.
1873 See also <xref linkend="plpgsql-quote-literal-example">.
1875 <entry><literal>quote_ident('Foo bar')</literal></entry>
1876 <entry><literal>"Foo bar"</literal></entry>
1882 <primary>quote_literal</primary>
1884 <literal><function>quote_literal(<parameter>string</parameter> <type>text</type>)</function></literal>
1886 <entry><type>text</type></entry>
1888 Return the given string suitably quoted to be used as a string literal
1889 in an <acronym>SQL</acronym> statement string.
1890 Embedded single-quotes and backslashes are properly doubled.
1891 Note that <function>quote_literal</function> returns null on null
1892 input; if the argument might be null,
1893 <function>quote_nullable</function> is often more suitable.
1894 See also <xref linkend="plpgsql-quote-literal-example">.
1896 <entry><literal>quote_literal(E'O\'Reilly')</literal></entry>
1897 <entry><literal>'O''Reilly'</literal></entry>
1901 <entry><literal><function>quote_literal(<parameter>value</parameter> <type>anyelement</type>)</function></literal></entry>
1902 <entry><type>text</type></entry>
1904 Coerce the given value to text and then quote it as a literal.
1905 Embedded single-quotes and backslashes are properly doubled.
1907 <entry><literal>quote_literal(42.5)</literal></entry>
1908 <entry><literal>'42.5'</literal></entry>
1914 <primary>quote_nullable</primary>
1916 <literal><function>quote_nullable(<parameter>string</parameter> <type>text</type>)</function></literal>
1918 <entry><type>text</type></entry>
1920 Return the given string suitably quoted to be used as a string literal
1921 in an <acronym>SQL</acronym> statement string; or, if the argument
1922 is null, return <literal>NULL</>.
1923 Embedded single-quotes and backslashes are properly doubled.
1924 See also <xref linkend="plpgsql-quote-literal-example">.
1926 <entry><literal>quote_nullable(NULL)</literal></entry>
1927 <entry><literal>NULL</literal></entry>
1931 <entry><literal><function>quote_nullable(<parameter>value</parameter> <type>anyelement</type>)</function></literal></entry>
1932 <entry><type>text</type></entry>
1934 Coerce the given value to text and then quote it as a literal;
1935 or, if the argument is null, return <literal>NULL</>.
1936 Embedded single-quotes and backslashes are properly doubled.
1938 <entry><literal>quote_nullable(42.5)</literal></entry>
1939 <entry><literal>'42.5'</literal></entry>
1945 <primary>regexp_matches</primary>
1947 <literal><function>regexp_matches(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
1949 <entry><type>setof text[]</type></entry>
1951 Return all captured substrings resulting from matching a POSIX regular
1952 expression against the <parameter>string</parameter>. See
1953 <xref linkend="functions-posix-regexp"> for more information.
1955 <entry><literal>regexp_matches('foobarbequebaz', '(bar)(beque)')</literal></entry>
1956 <entry><literal>{bar,beque}</literal></entry>
1962 <primary>regexp_replace</primary>
1964 <literal><function>regexp_replace(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type>, <parameter>replacement</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
1966 <entry><type>text</type></entry>
1968 Replace substring(s) matching a POSIX regular expression. See
1969 <xref linkend="functions-posix-regexp"> for more information.
1971 <entry><literal>regexp_replace('Thomas', '.[mN]a.', 'M')</literal></entry>
1972 <entry><literal>ThM</literal></entry>
1978 <primary>regexp_split_to_array</primary>
1980 <literal><function>regexp_split_to_array(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type> ])</function></literal>
1982 <entry><type>text[]</type></entry>
1984 Split <parameter>string</parameter> using a POSIX regular expression as
1985 the delimiter. See <xref linkend="functions-posix-regexp"> for more
1988 <entry><literal>regexp_split_to_array('hello world', E'\\s+')</literal></entry>
1989 <entry><literal>{hello,world}</literal></entry>
1995 <primary>regexp_split_to_table</primary>
1997 <literal><function>regexp_split_to_table(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
1999 <entry><type>setof text</type></entry>
2001 Split <parameter>string</parameter> using a POSIX regular expression as
2002 the delimiter. See <xref linkend="functions-posix-regexp"> for more
2005 <entry><literal>regexp_split_to_table('hello world', E'\\s+')</literal></entry>
2006 <entry><literal>hello</literal><para><literal>world</literal></para> (2 rows)</entry>
2012 <primary>repeat</primary>
2014 <literal><function>repeat(<parameter>string</parameter> <type>text</type>, <parameter>number</parameter> <type>int</type>)</function></literal>
2016 <entry><type>text</type></entry>
2017 <entry>Repeat <parameter>string</parameter> the specified
2018 <parameter>number</parameter> of times</entry>
2019 <entry><literal>repeat('Pg', 4)</literal></entry>
2020 <entry><literal>PgPgPgPg</literal></entry>
2026 <primary>replace</primary>
2028 <literal><function>replace(<parameter>string</parameter> <type>text</type>,
2029 <parameter>from</parameter> <type>text</type>,
2030 <parameter>to</parameter> <type>text</type>)</function></literal>
2032 <entry><type>text</type></entry>
2033 <entry>Replace all occurrences in <parameter>string</parameter> of substring
2034 <parameter>from</parameter> with substring <parameter>to</parameter>
2036 <entry><literal>replace('abcdefabcdef', 'cd', 'XX')</literal></entry>
2037 <entry><literal>abXXefabXXef</literal></entry>
2043 <primary>reverse</primary>
2045 <literal><function>reverse(<parameter>str</parameter>)</function></literal>
2047 <entry><type>text</type></entry>
2049 Return reversed string.
2051 <entry><literal>reverse('abcde')</literal></entry>
2052 <entry><literal>edcba</literal></entry>
2058 <primary>right</primary>
2060 <literal><function>right(<parameter>str</parameter> <type>text</type>,
2061 <parameter>n</parameter> <type>int</type>)</function></literal>
2063 <entry><type>text</type></entry>
2065 Return last <replaceable>n</> characters in the string. When <replaceable>n</>
2066 is negative, return all but first |<replaceable>n</>| characters.
2068 <entry><literal>right('abcde', 2)</literal></entry>
2069 <entry><literal>de</literal></entry>
2075 <primary>rpad</primary>
2077 <literal><function>rpad(<parameter>string</parameter> <type>text</type>,
2078 <parameter>length</parameter> <type>int</type>
2079 <optional>, <parameter>fill</parameter> <type>text</type></optional>)</function></literal>
2081 <entry><type>text</type></entry>
2083 Fill up the <parameter>string</parameter> to length
2084 <parameter>length</parameter> by appending the characters
2085 <parameter>fill</parameter> (a space by default). If the
2086 <parameter>string</parameter> is already longer than
2087 <parameter>length</parameter> then it is truncated.
2089 <entry><literal>rpad('hi', 5, 'xy')</literal></entry>
2090 <entry><literal>hixyx</literal></entry>
2096 <primary>rtrim</primary>
2098 <literal><function>rtrim(<parameter>string</parameter> <type>text</type>
2099 <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
2101 <entry><type>text</type></entry>
2103 Remove the longest string containing only characters from
2104 <parameter>characters</parameter> (a space by default) from the end of
2105 <parameter>string</parameter>
2107 <entry><literal>rtrim('trimxxxx', 'x')</literal></entry>
2108 <entry><literal>trim</literal></entry>
2114 <primary>split_part</primary>
2116 <literal><function>split_part(<parameter>string</parameter> <type>text</type>,
2117 <parameter>delimiter</parameter> <type>text</type>,
2118 <parameter>field</parameter> <type>int</type>)</function></literal>
2120 <entry><type>text</type></entry>
2121 <entry>Split <parameter>string</parameter> on <parameter>delimiter</parameter>
2122 and return the given field (counting from one)
2124 <entry><literal>split_part('abc~@~def~@~ghi', '~@~', 2)</literal></entry>
2125 <entry><literal>def</literal></entry>
2131 <primary>strpos</primary>
2133 <literal><function>strpos(<parameter>string</parameter>, <parameter>substring</parameter>)</function></literal>
2135 <entry><type>int</type></entry>
2137 Location of specified substring (same as
2138 <literal>position(<parameter>substring</parameter> in
2139 <parameter>string</parameter>)</literal>, but note the reversed
2142 <entry><literal>strpos('high', 'ig')</literal></entry>
2143 <entry><literal>2</literal></entry>
2149 <primary>substr</primary>
2151 <literal><function>substr(<parameter>string</parameter>, <parameter>from</parameter> <optional>, <parameter>count</parameter></optional>)</function></literal>
2153 <entry><type>text</type></entry>
2155 Extract substring (same as
2156 <literal>substring(<parameter>string</parameter> from <parameter>from</parameter> for <parameter>count</parameter>)</literal>)
2158 <entry><literal>substr('alphabet', 3, 2)</literal></entry>
2159 <entry><literal>ph</literal></entry>
2165 <primary>to_ascii</primary>
2167 <literal><function>to_ascii(<parameter>string</parameter> <type>text</type>
2168 <optional>, <parameter>encoding</parameter> <type>text</type></optional>)</function></literal>
2170 <entry><type>text</type></entry>
2172 Convert <parameter>string</parameter> to <acronym>ASCII</acronym> from another encoding
2173 (only supports conversion from <literal>LATIN1</>, <literal>LATIN2</>, <literal>LATIN9</>,
2174 and <literal>WIN1250</> encodings)
2176 <entry><literal>to_ascii('Karel')</literal></entry>
2177 <entry><literal>Karel</literal></entry>
2183 <primary>to_hex</primary>
2185 <literal><function>to_hex(<parameter>number</parameter> <type>int</type>
2186 or <type>bigint</type>)</function></literal>
2188 <entry><type>text</type></entry>
2189 <entry>Convert <parameter>number</parameter> to its equivalent hexadecimal
2192 <entry><literal>to_hex(2147483647)</literal></entry>
2193 <entry><literal>7fffffff</literal></entry>
2199 <primary>translate</primary>
2201 <literal><function>translate(<parameter>string</parameter> <type>text</type>,
2202 <parameter>from</parameter> <type>text</type>,
2203 <parameter>to</parameter> <type>text</type>)</function></literal>
2205 <entry><type>text</type></entry>
2207 Any character in <parameter>string</parameter> that matches a
2208 character in the <parameter>from</parameter> set is replaced by
2209 the corresponding character in the <parameter>to</parameter>
2210 set. If <parameter>from</parameter> is longer than
2211 <parameter>to</parameter>, occurrences of the extra characters in
2212 <parameter>from</parameter> are removed.
2214 <entry><literal>translate('12345', '143', 'ax')</literal></entry>
2215 <entry><literal>a2x5</literal></entry>
2223 The <function>concat</function>, <function>concat_ws</function> and
2224 <function>format</function> functions are variadic, so it is possible to
2225 pass the values to be concatenated or formatted as an array marked with
2226 the <literal>VARIADIC</literal> keyword (see <xref
2227 linkend="xfunc-sql-variadic-functions">). The array's elements are
2228 treated as if they were separate ordinary arguments to the function.
2229 If the variadic array argument is NULL, <function>concat</function>
2230 and <function>concat_ws</function> return NULL, but
2231 <function>format</function> treats a NULL as a zero-element array.
2235 See also the aggregate function <function>string_agg</function> in
2236 <xref linkend="functions-aggregate">.
2239 <table id="conversion-names">
2240 <title>Built-in Conversions</title>
2244 <entry>Conversion Name
2247 The conversion names follow a standard naming scheme: The
2248 official name of the source encoding with all
2249 non-alphanumeric characters replaced by underscores, followed
2250 by <literal>_to_</literal>, followed by the similarly processed
2251 destination encoding name. Therefore, the names might deviate
2252 from the customary encoding names.
2256 <entry>Source Encoding</entry>
2257 <entry>Destination Encoding</entry>
2263 <entry><literal>ascii_to_mic</literal></entry>
2264 <entry><literal>SQL_ASCII</literal></entry>
2265 <entry><literal>MULE_INTERNAL</literal></entry>
2269 <entry><literal>ascii_to_utf8</literal></entry>
2270 <entry><literal>SQL_ASCII</literal></entry>
2271 <entry><literal>UTF8</literal></entry>
2275 <entry><literal>big5_to_euc_tw</literal></entry>
2276 <entry><literal>BIG5</literal></entry>
2277 <entry><literal>EUC_TW</literal></entry>
2281 <entry><literal>big5_to_mic</literal></entry>
2282 <entry><literal>BIG5</literal></entry>
2283 <entry><literal>MULE_INTERNAL</literal></entry>
2287 <entry><literal>big5_to_utf8</literal></entry>
2288 <entry><literal>BIG5</literal></entry>
2289 <entry><literal>UTF8</literal></entry>
2293 <entry><literal>euc_cn_to_mic</literal></entry>
2294 <entry><literal>EUC_CN</literal></entry>
2295 <entry><literal>MULE_INTERNAL</literal></entry>
2299 <entry><literal>euc_cn_to_utf8</literal></entry>
2300 <entry><literal>EUC_CN</literal></entry>
2301 <entry><literal>UTF8</literal></entry>
2305 <entry><literal>euc_jp_to_mic</literal></entry>
2306 <entry><literal>EUC_JP</literal></entry>
2307 <entry><literal>MULE_INTERNAL</literal></entry>
2311 <entry><literal>euc_jp_to_sjis</literal></entry>
2312 <entry><literal>EUC_JP</literal></entry>
2313 <entry><literal>SJIS</literal></entry>
2317 <entry><literal>euc_jp_to_utf8</literal></entry>
2318 <entry><literal>EUC_JP</literal></entry>
2319 <entry><literal>UTF8</literal></entry>
2323 <entry><literal>euc_kr_to_mic</literal></entry>
2324 <entry><literal>EUC_KR</literal></entry>
2325 <entry><literal>MULE_INTERNAL</literal></entry>
2329 <entry><literal>euc_kr_to_utf8</literal></entry>
2330 <entry><literal>EUC_KR</literal></entry>
2331 <entry><literal>UTF8</literal></entry>
2335 <entry><literal>euc_tw_to_big5</literal></entry>
2336 <entry><literal>EUC_TW</literal></entry>
2337 <entry><literal>BIG5</literal></entry>
2341 <entry><literal>euc_tw_to_mic</literal></entry>
2342 <entry><literal>EUC_TW</literal></entry>
2343 <entry><literal>MULE_INTERNAL</literal></entry>
2347 <entry><literal>euc_tw_to_utf8</literal></entry>
2348 <entry><literal>EUC_TW</literal></entry>
2349 <entry><literal>UTF8</literal></entry>
2353 <entry><literal>gb18030_to_utf8</literal></entry>
2354 <entry><literal>GB18030</literal></entry>
2355 <entry><literal>UTF8</literal></entry>
2359 <entry><literal>gbk_to_utf8</literal></entry>
2360 <entry><literal>GBK</literal></entry>
2361 <entry><literal>UTF8</literal></entry>
2365 <entry><literal>iso_8859_10_to_utf8</literal></entry>
2366 <entry><literal>LATIN6</literal></entry>
2367 <entry><literal>UTF8</literal></entry>
2371 <entry><literal>iso_8859_13_to_utf8</literal></entry>
2372 <entry><literal>LATIN7</literal></entry>
2373 <entry><literal>UTF8</literal></entry>
2377 <entry><literal>iso_8859_14_to_utf8</literal></entry>
2378 <entry><literal>LATIN8</literal></entry>
2379 <entry><literal>UTF8</literal></entry>
2383 <entry><literal>iso_8859_15_to_utf8</literal></entry>
2384 <entry><literal>LATIN9</literal></entry>
2385 <entry><literal>UTF8</literal></entry>
2389 <entry><literal>iso_8859_16_to_utf8</literal></entry>
2390 <entry><literal>LATIN10</literal></entry>
2391 <entry><literal>UTF8</literal></entry>
2395 <entry><literal>iso_8859_1_to_mic</literal></entry>
2396 <entry><literal>LATIN1</literal></entry>
2397 <entry><literal>MULE_INTERNAL</literal></entry>
2401 <entry><literal>iso_8859_1_to_utf8</literal></entry>
2402 <entry><literal>LATIN1</literal></entry>
2403 <entry><literal>UTF8</literal></entry>
2407 <entry><literal>iso_8859_2_to_mic</literal></entry>
2408 <entry><literal>LATIN2</literal></entry>
2409 <entry><literal>MULE_INTERNAL</literal></entry>
2413 <entry><literal>iso_8859_2_to_utf8</literal></entry>
2414 <entry><literal>LATIN2</literal></entry>
2415 <entry><literal>UTF8</literal></entry>
2419 <entry><literal>iso_8859_2_to_windows_1250</literal></entry>
2420 <entry><literal>LATIN2</literal></entry>
2421 <entry><literal>WIN1250</literal></entry>
2425 <entry><literal>iso_8859_3_to_mic</literal></entry>
2426 <entry><literal>LATIN3</literal></entry>
2427 <entry><literal>MULE_INTERNAL</literal></entry>
2431 <entry><literal>iso_8859_3_to_utf8</literal></entry>
2432 <entry><literal>LATIN3</literal></entry>
2433 <entry><literal>UTF8</literal></entry>
2437 <entry><literal>iso_8859_4_to_mic</literal></entry>
2438 <entry><literal>LATIN4</literal></entry>
2439 <entry><literal>MULE_INTERNAL</literal></entry>
2443 <entry><literal>iso_8859_4_to_utf8</literal></entry>
2444 <entry><literal>LATIN4</literal></entry>
2445 <entry><literal>UTF8</literal></entry>
2449 <entry><literal>iso_8859_5_to_koi8_r</literal></entry>
2450 <entry><literal>ISO_8859_5</literal></entry>
2451 <entry><literal>KOI8R</literal></entry>
2455 <entry><literal>iso_8859_5_to_mic</literal></entry>
2456 <entry><literal>ISO_8859_5</literal></entry>
2457 <entry><literal>MULE_INTERNAL</literal></entry>
2461 <entry><literal>iso_8859_5_to_utf8</literal></entry>
2462 <entry><literal>ISO_8859_5</literal></entry>
2463 <entry><literal>UTF8</literal></entry>
2467 <entry><literal>iso_8859_5_to_windows_1251</literal></entry>
2468 <entry><literal>ISO_8859_5</literal></entry>
2469 <entry><literal>WIN1251</literal></entry>
2473 <entry><literal>iso_8859_5_to_windows_866</literal></entry>
2474 <entry><literal>ISO_8859_5</literal></entry>
2475 <entry><literal>WIN866</literal></entry>
2479 <entry><literal>iso_8859_6_to_utf8</literal></entry>
2480 <entry><literal>ISO_8859_6</literal></entry>
2481 <entry><literal>UTF8</literal></entry>
2485 <entry><literal>iso_8859_7_to_utf8</literal></entry>
2486 <entry><literal>ISO_8859_7</literal></entry>
2487 <entry><literal>UTF8</literal></entry>
2491 <entry><literal>iso_8859_8_to_utf8</literal></entry>
2492 <entry><literal>ISO_8859_8</literal></entry>
2493 <entry><literal>UTF8</literal></entry>
2497 <entry><literal>iso_8859_9_to_utf8</literal></entry>
2498 <entry><literal>LATIN5</literal></entry>
2499 <entry><literal>UTF8</literal></entry>
2503 <entry><literal>johab_to_utf8</literal></entry>
2504 <entry><literal>JOHAB</literal></entry>
2505 <entry><literal>UTF8</literal></entry>
2509 <entry><literal>koi8_r_to_iso_8859_5</literal></entry>
2510 <entry><literal>KOI8R</literal></entry>
2511 <entry><literal>ISO_8859_5</literal></entry>
2515 <entry><literal>koi8_r_to_mic</literal></entry>
2516 <entry><literal>KOI8R</literal></entry>
2517 <entry><literal>MULE_INTERNAL</literal></entry>
2521 <entry><literal>koi8_r_to_utf8</literal></entry>
2522 <entry><literal>KOI8R</literal></entry>
2523 <entry><literal>UTF8</literal></entry>
2527 <entry><literal>koi8_r_to_windows_1251</literal></entry>
2528 <entry><literal>KOI8R</literal></entry>
2529 <entry><literal>WIN1251</literal></entry>
2533 <entry><literal>koi8_r_to_windows_866</literal></entry>
2534 <entry><literal>KOI8R</literal></entry>
2535 <entry><literal>WIN866</literal></entry>
2539 <entry><literal>koi8_u_to_utf8</literal></entry>
2540 <entry><literal>KOI8U</literal></entry>
2541 <entry><literal>UTF8</literal></entry>
2545 <entry><literal>mic_to_ascii</literal></entry>
2546 <entry><literal>MULE_INTERNAL</literal></entry>
2547 <entry><literal>SQL_ASCII</literal></entry>
2551 <entry><literal>mic_to_big5</literal></entry>
2552 <entry><literal>MULE_INTERNAL</literal></entry>
2553 <entry><literal>BIG5</literal></entry>
2557 <entry><literal>mic_to_euc_cn</literal></entry>
2558 <entry><literal>MULE_INTERNAL</literal></entry>
2559 <entry><literal>EUC_CN</literal></entry>
2563 <entry><literal>mic_to_euc_jp</literal></entry>
2564 <entry><literal>MULE_INTERNAL</literal></entry>
2565 <entry><literal>EUC_JP</literal></entry>
2569 <entry><literal>mic_to_euc_kr</literal></entry>
2570 <entry><literal>MULE_INTERNAL</literal></entry>
2571 <entry><literal>EUC_KR</literal></entry>
2575 <entry><literal>mic_to_euc_tw</literal></entry>
2576 <entry><literal>MULE_INTERNAL</literal></entry>
2577 <entry><literal>EUC_TW</literal></entry>
2581 <entry><literal>mic_to_iso_8859_1</literal></entry>
2582 <entry><literal>MULE_INTERNAL</literal></entry>
2583 <entry><literal>LATIN1</literal></entry>
2587 <entry><literal>mic_to_iso_8859_2</literal></entry>
2588 <entry><literal>MULE_INTERNAL</literal></entry>
2589 <entry><literal>LATIN2</literal></entry>
2593 <entry><literal>mic_to_iso_8859_3</literal></entry>
2594 <entry><literal>MULE_INTERNAL</literal></entry>
2595 <entry><literal>LATIN3</literal></entry>
2599 <entry><literal>mic_to_iso_8859_4</literal></entry>
2600 <entry><literal>MULE_INTERNAL</literal></entry>
2601 <entry><literal>LATIN4</literal></entry>
2605 <entry><literal>mic_to_iso_8859_5</literal></entry>
2606 <entry><literal>MULE_INTERNAL</literal></entry>
2607 <entry><literal>ISO_8859_5</literal></entry>
2611 <entry><literal>mic_to_koi8_r</literal></entry>
2612 <entry><literal>MULE_INTERNAL</literal></entry>
2613 <entry><literal>KOI8R</literal></entry>
2617 <entry><literal>mic_to_sjis</literal></entry>
2618 <entry><literal>MULE_INTERNAL</literal></entry>
2619 <entry><literal>SJIS</literal></entry>
2623 <entry><literal>mic_to_windows_1250</literal></entry>
2624 <entry><literal>MULE_INTERNAL</literal></entry>
2625 <entry><literal>WIN1250</literal></entry>
2629 <entry><literal>mic_to_windows_1251</literal></entry>
2630 <entry><literal>MULE_INTERNAL</literal></entry>
2631 <entry><literal>WIN1251</literal></entry>
2635 <entry><literal>mic_to_windows_866</literal></entry>
2636 <entry><literal>MULE_INTERNAL</literal></entry>
2637 <entry><literal>WIN866</literal></entry>
2641 <entry><literal>sjis_to_euc_jp</literal></entry>
2642 <entry><literal>SJIS</literal></entry>
2643 <entry><literal>EUC_JP</literal></entry>
2647 <entry><literal>sjis_to_mic</literal></entry>
2648 <entry><literal>SJIS</literal></entry>
2649 <entry><literal>MULE_INTERNAL</literal></entry>
2653 <entry><literal>sjis_to_utf8</literal></entry>
2654 <entry><literal>SJIS</literal></entry>
2655 <entry><literal>UTF8</literal></entry>
2659 <entry><literal>tcvn_to_utf8</literal></entry>
2660 <entry><literal>WIN1258</literal></entry>
2661 <entry><literal>UTF8</literal></entry>
2665 <entry><literal>uhc_to_utf8</literal></entry>
2666 <entry><literal>UHC</literal></entry>
2667 <entry><literal>UTF8</literal></entry>
2671 <entry><literal>utf8_to_ascii</literal></entry>
2672 <entry><literal>UTF8</literal></entry>
2673 <entry><literal>SQL_ASCII</literal></entry>
2677 <entry><literal>utf8_to_big5</literal></entry>
2678 <entry><literal>UTF8</literal></entry>
2679 <entry><literal>BIG5</literal></entry>
2683 <entry><literal>utf8_to_euc_cn</literal></entry>
2684 <entry><literal>UTF8</literal></entry>
2685 <entry><literal>EUC_CN</literal></entry>
2689 <entry><literal>utf8_to_euc_jp</literal></entry>
2690 <entry><literal>UTF8</literal></entry>
2691 <entry><literal>EUC_JP</literal></entry>
2695 <entry><literal>utf8_to_euc_kr</literal></entry>
2696 <entry><literal>UTF8</literal></entry>
2697 <entry><literal>EUC_KR</literal></entry>
2701 <entry><literal>utf8_to_euc_tw</literal></entry>
2702 <entry><literal>UTF8</literal></entry>
2703 <entry><literal>EUC_TW</literal></entry>
2707 <entry><literal>utf8_to_gb18030</literal></entry>
2708 <entry><literal>UTF8</literal></entry>
2709 <entry><literal>GB18030</literal></entry>
2713 <entry><literal>utf8_to_gbk</literal></entry>
2714 <entry><literal>UTF8</literal></entry>
2715 <entry><literal>GBK</literal></entry>
2719 <entry><literal>utf8_to_iso_8859_1</literal></entry>
2720 <entry><literal>UTF8</literal></entry>
2721 <entry><literal>LATIN1</literal></entry>
2725 <entry><literal>utf8_to_iso_8859_10</literal></entry>
2726 <entry><literal>UTF8</literal></entry>
2727 <entry><literal>LATIN6</literal></entry>
2731 <entry><literal>utf8_to_iso_8859_13</literal></entry>
2732 <entry><literal>UTF8</literal></entry>
2733 <entry><literal>LATIN7</literal></entry>
2737 <entry><literal>utf8_to_iso_8859_14</literal></entry>
2738 <entry><literal>UTF8</literal></entry>
2739 <entry><literal>LATIN8</literal></entry>
2743 <entry><literal>utf8_to_iso_8859_15</literal></entry>
2744 <entry><literal>UTF8</literal></entry>
2745 <entry><literal>LATIN9</literal></entry>
2749 <entry><literal>utf8_to_iso_8859_16</literal></entry>
2750 <entry><literal>UTF8</literal></entry>
2751 <entry><literal>LATIN10</literal></entry>
2755 <entry><literal>utf8_to_iso_8859_2</literal></entry>
2756 <entry><literal>UTF8</literal></entry>
2757 <entry><literal>LATIN2</literal></entry>
2761 <entry><literal>utf8_to_iso_8859_3</literal></entry>
2762 <entry><literal>UTF8</literal></entry>
2763 <entry><literal>LATIN3</literal></entry>
2767 <entry><literal>utf8_to_iso_8859_4</literal></entry>
2768 <entry><literal>UTF8</literal></entry>
2769 <entry><literal>LATIN4</literal></entry>
2773 <entry><literal>utf8_to_iso_8859_5</literal></entry>
2774 <entry><literal>UTF8</literal></entry>
2775 <entry><literal>ISO_8859_5</literal></entry>
2779 <entry><literal>utf8_to_iso_8859_6</literal></entry>
2780 <entry><literal>UTF8</literal></entry>
2781 <entry><literal>ISO_8859_6</literal></entry>
2785 <entry><literal>utf8_to_iso_8859_7</literal></entry>
2786 <entry><literal>UTF8</literal></entry>
2787 <entry><literal>ISO_8859_7</literal></entry>
2791 <entry><literal>utf8_to_iso_8859_8</literal></entry>
2792 <entry><literal>UTF8</literal></entry>
2793 <entry><literal>ISO_8859_8</literal></entry>
2797 <entry><literal>utf8_to_iso_8859_9</literal></entry>
2798 <entry><literal>UTF8</literal></entry>
2799 <entry><literal>LATIN5</literal></entry>
2803 <entry><literal>utf8_to_johab</literal></entry>
2804 <entry><literal>UTF8</literal></entry>
2805 <entry><literal>JOHAB</literal></entry>
2809 <entry><literal>utf8_to_koi8_r</literal></entry>
2810 <entry><literal>UTF8</literal></entry>
2811 <entry><literal>KOI8R</literal></entry>
2815 <entry><literal>utf8_to_koi8_u</literal></entry>
2816 <entry><literal>UTF8</literal></entry>
2817 <entry><literal>KOI8U</literal></entry>
2821 <entry><literal>utf8_to_sjis</literal></entry>
2822 <entry><literal>UTF8</literal></entry>
2823 <entry><literal>SJIS</literal></entry>
2827 <entry><literal>utf8_to_tcvn</literal></entry>
2828 <entry><literal>UTF8</literal></entry>
2829 <entry><literal>WIN1258</literal></entry>
2833 <entry><literal>utf8_to_uhc</literal></entry>
2834 <entry><literal>UTF8</literal></entry>
2835 <entry><literal>UHC</literal></entry>
2839 <entry><literal>utf8_to_windows_1250</literal></entry>
2840 <entry><literal>UTF8</literal></entry>
2841 <entry><literal>WIN1250</literal></entry>
2845 <entry><literal>utf8_to_windows_1251</literal></entry>
2846 <entry><literal>UTF8</literal></entry>
2847 <entry><literal>WIN1251</literal></entry>
2851 <entry><literal>utf8_to_windows_1252</literal></entry>
2852 <entry><literal>UTF8</literal></entry>
2853 <entry><literal>WIN1252</literal></entry>
2857 <entry><literal>utf8_to_windows_1253</literal></entry>
2858 <entry><literal>UTF8</literal></entry>
2859 <entry><literal>WIN1253</literal></entry>
2863 <entry><literal>utf8_to_windows_1254</literal></entry>
2864 <entry><literal>UTF8</literal></entry>
2865 <entry><literal>WIN1254</literal></entry>
2869 <entry><literal>utf8_to_windows_1255</literal></entry>
2870 <entry><literal>UTF8</literal></entry>
2871 <entry><literal>WIN1255</literal></entry>
2875 <entry><literal>utf8_to_windows_1256</literal></entry>
2876 <entry><literal>UTF8</literal></entry>
2877 <entry><literal>WIN1256</literal></entry>
2881 <entry><literal>utf8_to_windows_1257</literal></entry>
2882 <entry><literal>UTF8</literal></entry>
2883 <entry><literal>WIN1257</literal></entry>
2887 <entry><literal>utf8_to_windows_866</literal></entry>
2888 <entry><literal>UTF8</literal></entry>
2889 <entry><literal>WIN866</literal></entry>
2893 <entry><literal>utf8_to_windows_874</literal></entry>
2894 <entry><literal>UTF8</literal></entry>
2895 <entry><literal>WIN874</literal></entry>
2899 <entry><literal>windows_1250_to_iso_8859_2</literal></entry>
2900 <entry><literal>WIN1250</literal></entry>
2901 <entry><literal>LATIN2</literal></entry>
2905 <entry><literal>windows_1250_to_mic</literal></entry>
2906 <entry><literal>WIN1250</literal></entry>
2907 <entry><literal>MULE_INTERNAL</literal></entry>
2911 <entry><literal>windows_1250_to_utf8</literal></entry>
2912 <entry><literal>WIN1250</literal></entry>
2913 <entry><literal>UTF8</literal></entry>
2917 <entry><literal>windows_1251_to_iso_8859_5</literal></entry>
2918 <entry><literal>WIN1251</literal></entry>
2919 <entry><literal>ISO_8859_5</literal></entry>
2923 <entry><literal>windows_1251_to_koi8_r</literal></entry>
2924 <entry><literal>WIN1251</literal></entry>
2925 <entry><literal>KOI8R</literal></entry>
2929 <entry><literal>windows_1251_to_mic</literal></entry>
2930 <entry><literal>WIN1251</literal></entry>
2931 <entry><literal>MULE_INTERNAL</literal></entry>
2935 <entry><literal>windows_1251_to_utf8</literal></entry>
2936 <entry><literal>WIN1251</literal></entry>
2937 <entry><literal>UTF8</literal></entry>
2941 <entry><literal>windows_1251_to_windows_866</literal></entry>
2942 <entry><literal>WIN1251</literal></entry>
2943 <entry><literal>WIN866</literal></entry>
2947 <entry><literal>windows_1252_to_utf8</literal></entry>
2948 <entry><literal>WIN1252</literal></entry>
2949 <entry><literal>UTF8</literal></entry>
2953 <entry><literal>windows_1256_to_utf8</literal></entry>
2954 <entry><literal>WIN1256</literal></entry>
2955 <entry><literal>UTF8</literal></entry>
2959 <entry><literal>windows_866_to_iso_8859_5</literal></entry>
2960 <entry><literal>WIN866</literal></entry>
2961 <entry><literal>ISO_8859_5</literal></entry>
2965 <entry><literal>windows_866_to_koi8_r</literal></entry>
2966 <entry><literal>WIN866</literal></entry>
2967 <entry><literal>KOI8R</literal></entry>
2971 <entry><literal>windows_866_to_mic</literal></entry>
2972 <entry><literal>WIN866</literal></entry>
2973 <entry><literal>MULE_INTERNAL</literal></entry>
2977 <entry><literal>windows_866_to_utf8</literal></entry>
2978 <entry><literal>WIN866</literal></entry>
2979 <entry><literal>UTF8</literal></entry>
2983 <entry><literal>windows_866_to_windows_1251</literal></entry>
2984 <entry><literal>WIN866</literal></entry>
2985 <entry><literal>WIN</literal></entry>
2989 <entry><literal>windows_874_to_utf8</literal></entry>
2990 <entry><literal>WIN874</literal></entry>
2991 <entry><literal>UTF8</literal></entry>
2995 <entry><literal>euc_jis_2004_to_utf8</literal></entry>
2996 <entry><literal>EUC_JIS_2004</literal></entry>
2997 <entry><literal>UTF8</literal></entry>
3001 <entry><literal>utf8_to_euc_jis_2004</literal></entry>
3002 <entry><literal>UTF8</literal></entry>
3003 <entry><literal>EUC_JIS_2004</literal></entry>
3007 <entry><literal>shift_jis_2004_to_utf8</literal></entry>
3008 <entry><literal>SHIFT_JIS_2004</literal></entry>
3009 <entry><literal>UTF8</literal></entry>
3013 <entry><literal>utf8_to_shift_jis_2004</literal></entry>
3014 <entry><literal>UTF8</literal></entry>
3015 <entry><literal>SHIFT_JIS_2004</literal></entry>
3019 <entry><literal>euc_jis_2004_to_shift_jis_2004</literal></entry>
3020 <entry><literal>EUC_JIS_2004</literal></entry>
3021 <entry><literal>SHIFT_JIS_2004</literal></entry>
3025 <entry><literal>shift_jis_2004_to_euc_jis_2004</literal></entry>
3026 <entry><literal>SHIFT_JIS_2004</literal></entry>
3027 <entry><literal>EUC_JIS_2004</literal></entry>
3034 <sect2 id="functions-string-format">
3035 <title><function>format</function></title>
3038 <primary>format</primary>
3042 The function <function>format</> produces output formatted according to
3043 a format string, in a style similar to the C function
3044 <function>sprintf</>.
3049 <function>format</>(<parameter>formatstr</> <type>text</> [, <parameter>formatarg</> <type>"any"</> [, ...] ])
3051 <replaceable>formatstr</> is a format string that specifies how the
3052 result should be formatted. Text in the format string is copied
3053 directly to the result, except where <firstterm>format specifiers</> are
3054 used. Format specifiers act as placeholders in the string, defining how
3055 subsequent function arguments should be formatted and inserted into the
3056 result. Each <replaceable>formatarg</> argument is converted to text
3057 according to the usual output rules for its data type, and then formatted
3058 and inserted into the result string according to the format specifier(s).
3062 Format specifiers are introduced by a <literal>%</> character and have
3065 %[<replaceable>position</>][<replaceable>flags</>][<replaceable>width</>]<replaceable>type</>
3067 where the component fields are:
3071 <term><replaceable>position</replaceable> (optional)</term>
3074 A string of the form <literal><replaceable>n</>$</> where
3075 <replaceable>n</> is the index of the argument to print.
3076 Index 1 means the first argument after
3077 <replaceable>formatstr</>. If the <replaceable>position</> is
3078 omitted, the default is to use the next argument in sequence.
3084 <term><replaceable>flags</replaceable> (optional)</term>
3087 Additional options controlling how the format specifier's output is
3088 formatted. Currently the only supported flag is a minus sign
3089 (<literal>-</>) which will cause the format specifier's output to be
3090 left-justified. This has no effect unless the <replaceable>width</>
3091 field is also specified.
3097 <term><replaceable>width</replaceable> (optional)</term>
3100 Specifies the <emphasis>minimum</> number of characters to use to
3101 display the format specifier's output. The output is padded on the
3102 left or right (depending on the <literal>-</> flag) with spaces as
3103 needed to fill the width. A too-small width does not cause
3104 truncation of the output, but is simply ignored. The width may be
3105 specified using any of the following: a positive integer; an
3106 asterisk (<literal>*</>) to use the next function argument as the
3107 width; or a string of the form <literal>*<replaceable>n</>$</> to
3108 use the <replaceable>n</>th function argument as the width.
3112 If the width comes from a function argument, that argument is
3113 consumed before the argument that is used for the format specifier's
3114 value. If the width argument is negative, the result is left
3115 aligned (as if the <literal>-</> flag had been specified) within a
3116 field of length <function>abs</>(<replaceable>width</replaceable>).
3122 <term><replaceable>type</replaceable> (required)</term>
3125 The type of format conversion to use to produce the format
3126 specifier's output. The following types are supported:
3130 <literal>s</literal> formats the argument value as a simple
3131 string. A null value is treated as an empty string.
3136 <literal>I</literal> treats the argument value as an SQL
3137 identifier, double-quoting it if necessary.
3138 It is an error for the value to be null (equivalent to
3139 <function>quote_ident</>).
3144 <literal>L</literal> quotes the argument value as an SQL literal.
3145 A null value is displayed as the string <literal>NULL</>, without
3146 quotes (equivalent to <function>quote_nullable</function>).
3157 In addition to the format specifiers described above, the special sequence
3158 <literal>%%</> may be used to output a literal <literal>%</> character.
3162 Here are some examples of the basic format conversions:
3165 SELECT format('Hello %s', 'World');
3166 <lineannotation>Result: </lineannotation><computeroutput>Hello World</computeroutput>
3168 SELECT format('Testing %s, %s, %s, %%', 'one', 'two', 'three');
3169 <lineannotation>Result: </><computeroutput>Testing one, two, three, %</>
3171 SELECT format('INSERT INTO %I VALUES(%L)', 'Foo bar', E'O\'Reilly');
3172 <lineannotation>Result: </lineannotation><computeroutput>INSERT INTO "Foo bar" VALUES('O''Reilly')</computeroutput>
3174 SELECT format('INSERT INTO %I VALUES(%L)', 'locations', E'C:\\Program Files');
3175 <lineannotation>Result: </lineannotation><computeroutput>INSERT INTO locations VALUES(E'C:\\Program Files')</computeroutput>
3180 Here are examples using <replaceable>width</replaceable> fields
3181 and the <literal>-</> flag:
3184 SELECT format('|%10s|', 'foo');
3185 <lineannotation>Result: </><computeroutput>| foo|</>
3187 SELECT format('|%-10s|', 'foo');
3188 <lineannotation>Result: </><computeroutput>|foo |</>
3190 SELECT format('|%*s|', 10, 'foo');
3191 <lineannotation>Result: </><computeroutput>| foo|</>
3193 SELECT format('|%*s|', -10, 'foo');
3194 <lineannotation>Result: </><computeroutput>|foo |</>
3196 SELECT format('|%-*s|', 10, 'foo');
3197 <lineannotation>Result: </><computeroutput>|foo |</>
3199 SELECT format('|%-*s|', -10, 'foo');
3200 <lineannotation>Result: </><computeroutput>|foo |</>
3205 These examples show use of <replaceable>position</> fields:
3208 SELECT format('Testing %3$s, %2$s, %1$s', 'one', 'two', 'three');
3209 <lineannotation>Result: </><computeroutput>Testing three, two, one</>
3211 SELECT format('|%*2$s|', 'foo', 10, 'bar');
3212 <lineannotation>Result: </><computeroutput>| bar|</>
3214 SELECT format('|%1$*2$s|', 'foo', 10, 'bar');
3215 <lineannotation>Result: </><computeroutput>| foo|</>
3220 Unlike the standard C function <function>sprintf</>,
3221 <productname>PostgreSQL</>'s <function>format</> function allows format
3222 specifiers with and without <replaceable>position</> fields to be mixed
3223 in the same format string. A format specifier without a
3224 <replaceable>position</> field always uses the next argument after the
3225 last argument consumed.
3226 In addition, the <function>format</> function does not require all
3227 function arguments to be used in the format string.
3231 SELECT format('Testing %3$s, %2$s, %s', 'one', 'two', 'three');
3232 <lineannotation>Result: </><computeroutput>Testing three, two, three</>
3237 The <literal>%I</> and <literal>%L</> format specifiers are particularly
3238 useful for safely constructing dynamic SQL statements. See
3239 <xref linkend="plpgsql-quote-literal-example">.
3246 <sect1 id="functions-binarystring">
3247 <title>Binary String Functions and Operators</title>
3249 <indexterm zone="functions-binarystring">
3250 <primary>binary data</primary>
3251 <secondary>functions</secondary>
3255 This section describes functions and operators for examining and
3256 manipulating values of type <type>bytea</type>.
3260 <acronym>SQL</acronym> defines some string functions that use
3261 key words, rather than commas, to separate
3262 arguments. Details are in
3263 <xref linkend="functions-binarystring-sql">.
3264 <productname>PostgreSQL</> also provides versions of these functions
3265 that use the regular function invocation syntax
3266 (see <xref linkend="functions-binarystring-other">).
3271 The sample results shown on this page assume that the server parameter
3272 <link linkend="guc-bytea-output"><varname>bytea_output</></link> is set
3273 to <literal>escape</literal> (the traditional PostgreSQL format).
3277 <table id="functions-binarystring-sql">
3278 <title><acronym>SQL</acronym> Binary String Functions and Operators</title>
3282 <entry>Function</entry>
3283 <entry>Return Type</entry>
3284 <entry>Description</entry>
3285 <entry>Example</entry>
3286 <entry>Result</entry>
3292 <entry><literal><parameter>string</parameter> <literal>||</literal>
3293 <parameter>string</parameter></literal></entry>
3294 <entry> <type>bytea</type> </entry>
3296 String concatenation
3298 <primary>binary string</primary>
3299 <secondary>concatenation</secondary>
3302 <entry><literal>E'\\\\Post'::bytea || E'\\047gres\\000'::bytea</literal></entry>
3303 <entry><literal>\\Post'gres\000</literal></entry>
3309 <primary>octet_length</primary>
3311 <literal><function>octet_length(<parameter>string</parameter>)</function></literal>
3313 <entry><type>int</type></entry>
3314 <entry>Number of bytes in binary string</entry>
3315 <entry><literal>octet_length(E'jo\\000se'::bytea)</literal></entry>
3316 <entry><literal>5</literal></entry>
3322 <primary>overlay</primary>
3324 <literal><function>overlay(<parameter>string</parameter> placing <parameter>string</parameter> from <type>int</type> <optional>for <type>int</type></optional>)</function></literal>
3326 <entry><type>bytea</type></entry>
3330 <entry><literal>overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 2 for 3)</literal></entry>
3331 <entry><literal>T\\002\\003mas</literal></entry>
3337 <primary>position</primary>
3339 <literal><function>position(<parameter>substring</parameter> in <parameter>string</parameter>)</function></literal>
3341 <entry><type>int</type></entry>
3342 <entry>Location of specified substring</entry>
3343 <entry><literal>position(E'\\000om'::bytea in E'Th\\000omas'::bytea)</literal></entry>
3344 <entry><literal>3</literal></entry>
3350 <primary>substring</primary>
3352 <literal><function>substring(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</function></literal>
3354 <entry><type>bytea</type></entry>
3358 <entry><literal>substring(E'Th\\000omas'::bytea from 2 for 3)</literal></entry>
3359 <entry><literal>h\000o</literal></entry>
3365 <primary>trim</primary>
3367 <literal><function>trim(<optional>both</optional>
3368 <parameter>bytes</parameter> from
3369 <parameter>string</parameter>)</function></literal>
3371 <entry><type>bytea</type></entry>
3373 Remove the longest string containing only the bytes in
3374 <parameter>bytes</parameter> from the start
3375 and end of <parameter>string</parameter>
3377 <entry><literal>trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea)</literal></entry>
3378 <entry><literal>Tom</literal></entry>
3385 Additional binary string manipulation functions are available and
3386 are listed in <xref linkend="functions-binarystring-other">. Some
3387 of them are used internally to implement the
3388 <acronym>SQL</acronym>-standard string functions listed in <xref
3389 linkend="functions-binarystring-sql">.
3392 <table id="functions-binarystring-other">
3393 <title>Other Binary String Functions</title>
3397 <entry>Function</entry>
3398 <entry>Return Type</entry>
3399 <entry>Description</entry>
3400 <entry>Example</entry>
3401 <entry>Result</entry>
3409 <primary>btrim</primary>
3411 <literal><function>btrim(<parameter>string</parameter>
3412 <type>bytea</type>, <parameter>bytes</parameter> <type>bytea</type>)</function></literal>
3414 <entry><type>bytea</type></entry>
3416 Remove the longest string consisting only of bytes
3417 in <parameter>bytes</parameter> from the start and end of
3418 <parameter>string</parameter>
3420 <entry><literal>btrim(E'\\000trim\\000'::bytea, E'\\000'::bytea)</literal></entry>
3421 <entry><literal>trim</literal></entry>
3427 <primary>decode</primary>
3429 <literal><function>decode(<parameter>string</parameter> <type>text</type>,
3430 <parameter>format</parameter> <type>text</type>)</function></literal>
3432 <entry><type>bytea</type></entry>
3434 Decode binary data from textual representation in <parameter>string</>.
3435 Options for <parameter>format</> are same as in <function>encode</>.
3437 <entry><literal>decode(E'123\\000456', 'escape')</literal></entry>
3438 <entry><literal>123\000456</literal></entry>
3444 <primary>encode</primary>
3446 <literal><function>encode(<parameter>data</parameter> <type>bytea</type>,
3447 <parameter>format</parameter> <type>text</type>)</function></literal>
3449 <entry><type>text</type></entry>
3451 Encode binary data into a textual representation. Supported
3452 formats are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
3453 <literal>escape</> converts zero bytes and high-bit-set bytes to
3454 octal sequences (<literal>\</><replaceable>nnn</>) and
3455 doubles backslashes.
3457 <entry><literal>encode(E'123\\000456'::bytea, 'escape')</literal></entry>
3458 <entry><literal>123\000456</literal></entry>
3464 <primary>get_bit</primary>
3466 <literal><function>get_bit(<parameter>string</parameter>, <parameter>offset</parameter>)</function></literal>
3468 <entry><type>int</type></entry>
3470 Extract bit from string
3472 <entry><literal>get_bit(E'Th\\000omas'::bytea, 45)</literal></entry>
3473 <entry><literal>1</literal></entry>
3479 <primary>get_byte</primary>
3481 <literal><function>get_byte(<parameter>string</parameter>, <parameter>offset</parameter>)</function></literal>
3483 <entry><type>int</type></entry>
3485 Extract byte from string
3487 <entry><literal>get_byte(E'Th\\000omas'::bytea, 4)</literal></entry>
3488 <entry><literal>109</literal></entry>
3494 <primary>length</primary>
3496 <literal><function>length(<parameter>string</parameter>)</function></literal>
3498 <entry><type>int</type></entry>
3500 Length of binary string
3502 <primary>binary string</primary>
3503 <secondary>length</secondary>
3506 <primary>length</primary>
3507 <secondary sortas="binary string">of a binary string</secondary>
3508 <see>binary strings, length</see>
3511 <entry><literal>length(E'jo\\000se'::bytea)</literal></entry>
3512 <entry><literal>5</literal></entry>
3518 <primary>md5</primary>
3520 <literal><function>md5(<parameter>string</parameter>)</function></literal>
3522 <entry><type>text</type></entry>
3524 Calculates the MD5 hash of <parameter>string</parameter>,
3525 returning the result in hexadecimal
3527 <entry><literal>md5(E'Th\\000omas'::bytea)</literal></entry>
3528 <entry><literal>8ab2d3c9689aaf18 b4958c334c82d8b1</literal></entry>
3534 <primary>set_bit</primary>
3536 <literal><function>set_bit(<parameter>string</parameter>,
3537 <parameter>offset</parameter>, <parameter>newvalue</>)</function></literal>
3539 <entry><type>bytea</type></entry>
3543 <entry><literal>set_bit(E'Th\\000omas'::bytea, 45, 0)</literal></entry>
3544 <entry><literal>Th\000omAs</literal></entry>
3550 <primary>set_byte</primary>
3552 <literal><function>set_byte(<parameter>string</parameter>,
3553 <parameter>offset</parameter>, <parameter>newvalue</>)</function></literal>
3555 <entry><type>bytea</type></entry>
3559 <entry><literal>set_byte(E'Th\\000omas'::bytea, 4, 64)</literal></entry>
3560 <entry><literal>Th\000o@as</literal></entry>
3567 <function>get_byte</> and <function>set_byte</> number the first byte
3568 of a binary string as byte 0.
3569 <function>get_bit</> and <function>set_bit</> number bits from the
3570 right within each byte; for example bit 0 is the least significant bit of
3571 the first byte, and bit 15 is the most significant bit of the second byte.
3575 See also the aggregate function <function>string_agg</function> in
3576 <xref linkend="functions-aggregate"> and the large object functions
3577 in <xref linkend="lo-funcs">.
3582 <sect1 id="functions-bitstring">
3583 <title>Bit String Functions and Operators</title>
3585 <indexterm zone="functions-bitstring">
3586 <primary>bit strings</primary>
3587 <secondary>functions</secondary>
3591 This section describes functions and operators for examining and
3592 manipulating bit strings, that is values of the types
3593 <type>bit</type> and <type>bit varying</type>. Aside from the
3594 usual comparison operators, the operators
3595 shown in <xref linkend="functions-bit-string-op-table"> can be used.
3596 Bit string operands of <literal>&</literal>, <literal>|</literal>,
3597 and <literal>#</literal> must be of equal length. When bit
3598 shifting, the original length of the string is preserved, as shown
3602 <table id="functions-bit-string-op-table">
3603 <title>Bit String Operators</title>
3608 <entry>Operator</entry>
3609 <entry>Description</entry>
3610 <entry>Example</entry>
3611 <entry>Result</entry>
3617 <entry> <literal>||</literal> </entry>
3618 <entry>concatenation</entry>
3619 <entry><literal>B'10001' || B'011'</literal></entry>
3620 <entry><literal>10001011</literal></entry>
3624 <entry> <literal>&</literal> </entry>
3625 <entry>bitwise AND</entry>
3626 <entry><literal>B'10001' & B'01101'</literal></entry>
3627 <entry><literal>00001</literal></entry>
3631 <entry> <literal>|</literal> </entry>
3632 <entry>bitwise OR</entry>
3633 <entry><literal>B'10001' | B'01101'</literal></entry>
3634 <entry><literal>11101</literal></entry>
3638 <entry> <literal>#</literal> </entry>
3639 <entry>bitwise XOR</entry>
3640 <entry><literal>B'10001' # B'01101'</literal></entry>
3641 <entry><literal>11100</literal></entry>
3645 <entry> <literal>~</literal> </entry>
3646 <entry>bitwise NOT</entry>
3647 <entry><literal>~ B'10001'</literal></entry>
3648 <entry><literal>01110</literal></entry>
3652 <entry> <literal><<</literal> </entry>
3653 <entry>bitwise shift left</entry>
3654 <entry><literal>B'10001' << 3</literal></entry>
3655 <entry><literal>01000</literal></entry>
3659 <entry> <literal>>></literal> </entry>
3660 <entry>bitwise shift right</entry>
3661 <entry><literal>B'10001' >> 2</literal></entry>
3662 <entry><literal>00100</literal></entry>
3669 The following <acronym>SQL</acronym>-standard functions work on bit
3670 strings as well as character strings:
3671 <literal><function>length</function></literal>,
3672 <literal><function>bit_length</function></literal>,
3673 <literal><function>octet_length</function></literal>,
3674 <literal><function>position</function></literal>,
3675 <literal><function>substring</function></literal>,
3676 <literal><function>overlay</function></literal>.
3680 The following functions work on bit strings as well as binary
3682 <literal><function>get_bit</function></literal>,
3683 <literal><function>set_bit</function></literal>.
3684 When working with a bit string, these functions number the first
3685 (leftmost) bit of the string as bit 0.
3689 In addition, it is possible to cast integral values to and from type
3693 44::bit(10) <lineannotation>0000101100</lineannotation>
3694 44::bit(3) <lineannotation>100</lineannotation>
3695 cast(-44 as bit(12)) <lineannotation>111111010100</lineannotation>
3696 '1110'::bit(4)::integer <lineannotation>14</lineannotation>
3698 Note that casting to just <quote>bit</> means casting to
3699 <literal>bit(1)</>, and so will deliver only the least significant
3705 Casting an integer to <type>bit(n)</> copies the rightmost
3706 <literal>n</> bits. Casting an integer to a bit string width wider
3707 than the integer itself will sign-extend on the left.
3714 <sect1 id="functions-matching">
3715 <title>Pattern Matching</title>
3717 <indexterm zone="functions-matching">
3718 <primary>pattern matching</primary>
3722 There are three separate approaches to pattern matching provided
3723 by <productname>PostgreSQL</productname>: the traditional
3724 <acronym>SQL</acronym> <function>LIKE</function> operator, the
3725 more recent <function>SIMILAR TO</function> operator (added in
3726 SQL:1999), and <acronym>POSIX</acronym>-style regular
3727 expressions. Aside from the basic <quote>does this string match
3728 this pattern?</> operators, functions are available to extract
3729 or replace matching substrings and to split a string at matching
3735 If you have pattern matching needs that go beyond this,
3736 consider writing a user-defined function in Perl or Tcl.
3742 While most regular-expression searches can be executed very quickly,
3743 regular expressions can be contrived that take arbitrary amounts of
3744 time and memory to process. Be wary of accepting regular-expression
3745 search patterns from hostile sources. If you must do so, it is
3746 advisable to impose a statement timeout.
3750 Searches using <function>SIMILAR TO</function> patterns have the same
3751 security hazards, since <function>SIMILAR TO</function> provides many
3752 of the same capabilities as <acronym>POSIX</acronym>-style regular
3757 <function>LIKE</function> searches, being much simpler than the other
3758 two options, are safer to use with possibly-hostile pattern sources.
3762 <sect2 id="functions-like">
3763 <title><function>LIKE</function></title>
3766 <primary>LIKE</primary>
3770 <replaceable>string</replaceable> LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3771 <replaceable>string</replaceable> NOT LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3775 The <function>LIKE</function> expression returns true if the
3776 <replaceable>string</replaceable> matches the supplied
3777 <replaceable>pattern</replaceable>. (As
3778 expected, the <function>NOT LIKE</function> expression returns
3779 false if <function>LIKE</function> returns true, and vice versa.
3780 An equivalent expression is
3781 <literal>NOT (<replaceable>string</replaceable> LIKE
3782 <replaceable>pattern</replaceable>)</literal>.)
3786 If <replaceable>pattern</replaceable> does not contain percent
3787 signs or underscores, then the pattern only represents the string
3788 itself; in that case <function>LIKE</function> acts like the
3789 equals operator. An underscore (<literal>_</literal>) in
3790 <replaceable>pattern</replaceable> stands for (matches) any single
3791 character; a percent sign (<literal>%</literal>) matches any sequence
3792 of zero or more characters.
3798 'abc' LIKE 'abc' <lineannotation>true</lineannotation>
3799 'abc' LIKE 'a%' <lineannotation>true</lineannotation>
3800 'abc' LIKE '_b_' <lineannotation>true</lineannotation>
3801 'abc' LIKE 'c' <lineannotation>false</lineannotation>
3806 <function>LIKE</function> pattern matching always covers the entire
3807 string. Therefore, if it's desired to match a sequence anywhere within
3808 a string, the pattern must start and end with a percent sign.
3812 To match a literal underscore or percent sign without matching
3813 other characters, the respective character in
3814 <replaceable>pattern</replaceable> must be
3815 preceded by the escape character. The default escape
3816 character is the backslash but a different one can be selected by
3817 using the <literal>ESCAPE</literal> clause. To match the escape
3818 character itself, write two escape characters.
3823 If you have <xref linkend="guc-standard-conforming-strings"> turned off,
3824 any backslashes you write in literal string constants will need to be
3825 doubled. See <xref linkend="sql-syntax-strings"> for more information.
3830 It's also possible to select no escape character by writing
3831 <literal>ESCAPE ''</literal>. This effectively disables the
3832 escape mechanism, which makes it impossible to turn off the
3833 special meaning of underscore and percent signs in the pattern.
3837 The key word <token>ILIKE</token> can be used instead of
3838 <token>LIKE</token> to make the match case-insensitive according
3839 to the active locale. This is not in the <acronym>SQL</acronym> standard but is a
3840 <productname>PostgreSQL</productname> extension.
3844 The operator <literal>~~</literal> is equivalent to
3845 <function>LIKE</function>, and <literal>~~*</literal> corresponds to
3846 <function>ILIKE</function>. There are also
3847 <literal>!~~</literal> and <literal>!~~*</literal> operators that
3848 represent <function>NOT LIKE</function> and <function>NOT
3849 ILIKE</function>, respectively. All of these operators are
3850 <productname>PostgreSQL</productname>-specific.
3855 <sect2 id="functions-similarto-regexp">
3856 <title><function>SIMILAR TO</function> Regular Expressions</title>
3859 <primary>regular expression</primary>
3860 <!-- <seealso>pattern matching</seealso> breaks index build -->
3864 <primary>SIMILAR TO</primary>
3867 <primary>substring</primary>
3871 <replaceable>string</replaceable> SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3872 <replaceable>string</replaceable> NOT SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3876 The <function>SIMILAR TO</function> operator returns true or
3877 false depending on whether its pattern matches the given string.
3878 It is similar to <function>LIKE</function>, except that it
3879 interprets the pattern using the SQL standard's definition of a
3880 regular expression. SQL regular expressions are a curious cross
3881 between <function>LIKE</function> notation and common regular
3882 expression notation.
3886 Like <function>LIKE</function>, the <function>SIMILAR TO</function>
3887 operator succeeds only if its pattern matches the entire string;
3888 this is unlike common regular expression behavior where the pattern
3889 can match any part of the string.
3891 <function>LIKE</function>, <function>SIMILAR TO</function> uses
3892 <literal>_</> and <literal>%</> as wildcard characters denoting
3893 any single character and any string, respectively (these are
3894 comparable to <literal>.</> and <literal>.*</> in POSIX regular
3899 In addition to these facilities borrowed from <function>LIKE</function>,
3900 <function>SIMILAR TO</function> supports these pattern-matching
3901 metacharacters borrowed from POSIX regular expressions:
3906 <literal>|</literal> denotes alternation (either of two alternatives).
3911 <literal>*</literal> denotes repetition of the previous item zero
3917 <literal>+</literal> denotes repetition of the previous item one
3923 <literal>?</literal> denotes repetition of the previous item zero
3929 <literal>{</><replaceable>m</><literal>}</literal> denotes repetition
3930 of the previous item exactly <replaceable>m</> times.
3935 <literal>{</><replaceable>m</><literal>,}</literal> denotes repetition
3936 of the previous item <replaceable>m</> or more times.
3941 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</>
3942 denotes repetition of the previous item at least <replaceable>m</> and
3943 not more than <replaceable>n</> times.
3948 Parentheses <literal>()</literal> can be used to group items into
3949 a single logical item.
3954 A bracket expression <literal>[...]</literal> specifies a character
3955 class, just as in POSIX regular expressions.
3960 Notice that the period (<literal>.</>) is not a metacharacter
3961 for <function>SIMILAR TO</>.
3965 As with <function>LIKE</>, a backslash disables the special meaning
3966 of any of these metacharacters; or a different escape character can
3967 be specified with <literal>ESCAPE</>.
3973 'abc' SIMILAR TO 'abc' <lineannotation>true</lineannotation>
3974 'abc' SIMILAR TO 'a' <lineannotation>false</lineannotation>
3975 'abc' SIMILAR TO '%(b|d)%' <lineannotation>true</lineannotation>
3976 'abc' SIMILAR TO '(b|c)%' <lineannotation>false</lineannotation>
3981 The <function>substring</> function with three parameters,
3982 <function>substring(<replaceable>string</replaceable> from
3983 <replaceable>pattern</replaceable> for
3984 <replaceable>escape-character</replaceable>)</function>, provides
3985 extraction of a substring that matches an SQL
3986 regular expression pattern. As with <literal>SIMILAR TO</>, the
3987 specified pattern must match the entire data string, or else the
3988 function fails and returns null. To indicate the part of the
3989 pattern that should be returned on success, the pattern must contain
3990 two occurrences of the escape character followed by a double quote
3991 (<literal>"</>). <!-- " font-lock sanity -->
3992 The text matching the portion of the pattern
3993 between these markers is returned.
3997 Some examples, with <literal>#"</> delimiting the return string:
3999 substring('foobar' from '%#"o_b#"%' for '#') <lineannotation>oob</lineannotation>
4000 substring('foobar' from '#"o_b#"%' for '#') <lineannotation>NULL</lineannotation>
4005 <sect2 id="functions-posix-regexp">
4006 <title><acronym>POSIX</acronym> Regular Expressions</title>
4008 <indexterm zone="functions-posix-regexp">
4009 <primary>regular expression</primary>
4010 <seealso>pattern matching</seealso>
4013 <primary>substring</primary>
4016 <primary>regexp_replace</primary>
4019 <primary>regexp_matches</primary>
4022 <primary>regexp_split_to_table</primary>
4025 <primary>regexp_split_to_array</primary>
4029 <xref linkend="functions-posix-table"> lists the available
4030 operators for pattern matching using POSIX regular expressions.
4033 <table id="functions-posix-table">
4034 <title>Regular Expression Match Operators</title>
4039 <entry>Operator</entry>
4040 <entry>Description</entry>
4041 <entry>Example</entry>
4047 <entry> <literal>~</literal> </entry>
4048 <entry>Matches regular expression, case sensitive</entry>
4049 <entry><literal>'thomas' ~ '.*thomas.*'</literal></entry>
4053 <entry> <literal>~*</literal> </entry>
4054 <entry>Matches regular expression, case insensitive</entry>
4055 <entry><literal>'thomas' ~* '.*Thomas.*'</literal></entry>
4059 <entry> <literal>!~</literal> </entry>
4060 <entry>Does not match regular expression, case sensitive</entry>
4061 <entry><literal>'thomas' !~ '.*Thomas.*'</literal></entry>
4065 <entry> <literal>!~*</literal> </entry>
4066 <entry>Does not match regular expression, case insensitive</entry>
4067 <entry><literal>'thomas' !~* '.*vadim.*'</literal></entry>
4074 <acronym>POSIX</acronym> regular expressions provide a more
4075 powerful means for pattern matching than the <function>LIKE</function> and
4076 <function>SIMILAR TO</> operators.
4077 Many Unix tools such as <command>egrep</command>,
4078 <command>sed</command>, or <command>awk</command> use a pattern
4079 matching language that is similar to the one described here.
4083 A regular expression is a character sequence that is an
4084 abbreviated definition of a set of strings (a <firstterm>regular
4085 set</firstterm>). A string is said to match a regular expression
4086 if it is a member of the regular set described by the regular
4087 expression. As with <function>LIKE</function>, pattern characters
4088 match string characters exactly unless they are special characters
4089 in the regular expression language — but regular expressions use
4090 different special characters than <function>LIKE</function> does.
4091 Unlike <function>LIKE</function> patterns, a
4092 regular expression is allowed to match anywhere within a string, unless
4093 the regular expression is explicitly anchored to the beginning or
4100 'abc' ~ 'abc' <lineannotation>true</lineannotation>
4101 'abc' ~ '^a' <lineannotation>true</lineannotation>
4102 'abc' ~ '(b|d)' <lineannotation>true</lineannotation>
4103 'abc' ~ '^(b|c)' <lineannotation>false</lineannotation>
4108 The <acronym>POSIX</acronym> pattern language is described in much
4109 greater detail below.
4113 The <function>substring</> function with two parameters,
4114 <function>substring(<replaceable>string</replaceable> from
4115 <replaceable>pattern</replaceable>)</function>, provides extraction of a
4117 that matches a POSIX regular expression pattern. It returns null if
4118 there is no match, otherwise the portion of the text that matched the
4119 pattern. But if the pattern contains any parentheses, the portion
4120 of the text that matched the first parenthesized subexpression (the
4121 one whose left parenthesis comes first) is
4122 returned. You can put parentheses around the whole expression
4123 if you want to use parentheses within it without triggering this
4124 exception. If you need parentheses in the pattern before the
4125 subexpression you want to extract, see the non-capturing parentheses
4132 substring('foobar' from 'o.b') <lineannotation>oob</lineannotation>
4133 substring('foobar' from 'o(.)b') <lineannotation>o</lineannotation>
4138 The <function>regexp_replace</> function provides substitution of
4139 new text for substrings that match POSIX regular expression patterns.
4141 <function>regexp_replace</function>(<replaceable>source</>,
4142 <replaceable>pattern</>, <replaceable>replacement</>
4143 <optional>, <replaceable>flags</> </optional>).
4144 The <replaceable>source</> string is returned unchanged if
4145 there is no match to the <replaceable>pattern</>. If there is a
4146 match, the <replaceable>source</> string is returned with the
4147 <replaceable>replacement</> string substituted for the matching
4148 substring. The <replaceable>replacement</> string can contain
4149 <literal>\</><replaceable>n</>, where <replaceable>n</> is 1
4150 through 9, to indicate that the source substring matching the
4151 <replaceable>n</>'th parenthesized subexpression of the pattern should be
4152 inserted, and it can contain <literal>\&</> to indicate that the
4153 substring matching the entire pattern should be inserted. Write
4154 <literal>\\</> if you need to put a literal backslash in the replacement
4156 The <replaceable>flags</> parameter is an optional text
4157 string containing zero or more single-letter flags that change the
4158 function's behavior. Flag <literal>i</> specifies case-insensitive
4159 matching, while flag <literal>g</> specifies replacement of each matching
4160 substring rather than only the first one. Supported flags (though
4161 not <literal>g</>) are
4162 described in <xref linkend="posix-embedded-options-table">.
4168 regexp_replace('foobarbaz', 'b..', 'X')
4169 <lineannotation>fooXbaz</lineannotation>
4170 regexp_replace('foobarbaz', 'b..', 'X', 'g')
4171 <lineannotation>fooXX</lineannotation>
4172 regexp_replace('foobarbaz', 'b(..)', E'X\\1Y', 'g')
4173 <lineannotation>fooXarYXazY</lineannotation>
4178 The <function>regexp_matches</> function returns a text array of
4179 all of the captured substrings resulting from matching a POSIX
4180 regular expression pattern. It has the syntax
4181 <function>regexp_matches</function>(<replaceable>string</>, <replaceable>pattern</>
4182 <optional>, <replaceable>flags</> </optional>).
4183 The function can return no rows, one row, or multiple rows (see
4184 the <literal>g</> flag below). If the <replaceable>pattern</>
4185 does not match, the function returns no rows. If the pattern
4186 contains no parenthesized subexpressions, then each row
4187 returned is a single-element text array containing the substring
4188 matching the whole pattern. If the pattern contains parenthesized
4189 subexpressions, the function returns a text array whose
4190 <replaceable>n</>'th element is the substring matching the
4191 <replaceable>n</>'th parenthesized subexpression of the pattern
4192 (not counting <quote>non-capturing</> parentheses; see below for
4194 The <replaceable>flags</> parameter is an optional text
4195 string containing zero or more single-letter flags that change the
4196 function's behavior. Flag <literal>g</> causes the function to find
4197 each match in the string, not only the first one, and return a row for
4198 each such match. Supported flags (though
4200 are described in <xref linkend="posix-embedded-options-table">.
4206 SELECT regexp_matches('foobarbequebaz', '(bar)(beque)');
4212 SELECT regexp_matches('foobarbequebazilbarfbonk', '(b[^b]+)(b[^b]+)', 'g');
4219 SELECT regexp_matches('foobarbequebaz', 'barbeque');
4228 It is possible to force <function>regexp_matches()</> to always
4229 return one row by using a sub-select; this is particularly useful
4230 in a <literal>SELECT</> target list when you want all rows
4231 returned, even non-matching ones:
4233 SELECT col1, (SELECT regexp_matches(col2, '(bar)(beque)')) FROM tab;
4238 The <function>regexp_split_to_table</> function splits a string using a POSIX
4239 regular expression pattern as a delimiter. It has the syntax
4240 <function>regexp_split_to_table</function>(<replaceable>string</>, <replaceable>pattern</>
4241 <optional>, <replaceable>flags</> </optional>).
4242 If there is no match to the <replaceable>pattern</>, the function returns the
4243 <replaceable>string</>. If there is at least one match, for each match it returns
4244 the text from the end of the last match (or the beginning of the string)
4245 to the beginning of the match. When there are no more matches, it
4246 returns the text from the end of the last match to the end of the string.
4247 The <replaceable>flags</> parameter is an optional text string containing
4248 zero or more single-letter flags that change the function's behavior.
4249 <function>regexp_split_to_table</function> supports the flags described in
4250 <xref linkend="posix-embedded-options-table">.
4254 The <function>regexp_split_to_array</> function behaves the same as
4255 <function>regexp_split_to_table</>, except that <function>regexp_split_to_array</>
4256 returns its result as an array of <type>text</>. It has the syntax
4257 <function>regexp_split_to_array</function>(<replaceable>string</>, <replaceable>pattern</>
4258 <optional>, <replaceable>flags</> </optional>).
4259 The parameters are the same as for <function>regexp_split_to_table</>.
4266 SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', E'\\s+') AS foo;
4280 SELECT regexp_split_to_array('the quick brown fox jumps over the lazy dog', E'\\s+');
4281 regexp_split_to_array
4282 -----------------------------------------------
4283 {the,quick,brown,fox,jumps,over,the,lazy,dog}
4286 SELECT foo FROM regexp_split_to_table('the quick brown fox', E'\\s*') AS foo;
4310 As the last example demonstrates, the regexp split functions ignore
4311 zero-length matches that occur at the start or end of the string
4312 or immediately after a previous match. This is contrary to the strict
4313 definition of regexp matching that is implemented by
4314 <function>regexp_matches</>, but is usually the most convenient behavior
4315 in practice. Other software systems such as Perl use similar definitions.
4318 <!-- derived from the re_syntax.n man page -->
4320 <sect3 id="posix-syntax-details">
4321 <title>Regular Expression Details</title>
4324 <productname>PostgreSQL</productname>'s regular expressions are implemented
4325 using a software package written by Henry Spencer. Much of
4326 the description of regular expressions below is copied verbatim from his
4331 Regular expressions (<acronym>RE</acronym>s), as defined in
4332 <acronym>POSIX</acronym> 1003.2, come in two forms:
4333 <firstterm>extended</> <acronym>RE</acronym>s or <acronym>ERE</>s
4334 (roughly those of <command>egrep</command>), and
4335 <firstterm>basic</> <acronym>RE</acronym>s or <acronym>BRE</>s
4336 (roughly those of <command>ed</command>).
4337 <productname>PostgreSQL</productname> supports both forms, and
4338 also implements some extensions
4339 that are not in the POSIX standard, but have become widely used
4340 due to their availability in programming languages such as Perl and Tcl.
4341 <acronym>RE</acronym>s using these non-POSIX extensions are called
4342 <firstterm>advanced</> <acronym>RE</acronym>s or <acronym>ARE</>s
4343 in this documentation. AREs are almost an exact superset of EREs,
4344 but BREs have several notational incompatibilities (as well as being
4346 We first describe the ARE and ERE forms, noting features that apply
4347 only to AREs, and then describe how BREs differ.
4352 <productname>PostgreSQL</> always initially presumes that a regular
4353 expression follows the ARE rules. However, the more limited ERE or
4354 BRE rules can be chosen by prepending an <firstterm>embedded option</>
4355 to the RE pattern, as described in <xref linkend="posix-metasyntax">.
4356 This can be useful for compatibility with applications that expect
4357 exactly the <acronym>POSIX</acronym> 1003.2 rules.
4362 A regular expression is defined as one or more
4363 <firstterm>branches</firstterm>, separated by
4364 <literal>|</literal>. It matches anything that matches one of the
4369 A branch is zero or more <firstterm>quantified atoms</> or
4370 <firstterm>constraints</>, concatenated.
4371 It matches a match for the first, followed by a match for the second, etc;
4372 an empty branch matches the empty string.
4376 A quantified atom is an <firstterm>atom</> possibly followed
4377 by a single <firstterm>quantifier</>.
4378 Without a quantifier, it matches a match for the atom.
4379 With a quantifier, it can match some number of matches of the atom.
4380 An <firstterm>atom</firstterm> can be any of the possibilities
4381 shown in <xref linkend="posix-atoms-table">.
4382 The possible quantifiers and their meanings are shown in
4383 <xref linkend="posix-quantifiers-table">.
4387 A <firstterm>constraint</> matches an empty string, but matches only when
4388 specific conditions are met. A constraint can be used where an atom
4389 could be used, except it cannot be followed by a quantifier.
4390 The simple constraints are shown in
4391 <xref linkend="posix-constraints-table">;
4392 some more constraints are described later.
4396 <table id="posix-atoms-table">
4397 <title>Regular Expression Atoms</title>
4403 <entry>Description</entry>
4409 <entry> <literal>(</><replaceable>re</><literal>)</> </entry>
4410 <entry> (where <replaceable>re</> is any regular expression)
4412 <replaceable>re</>, with the match noted for possible reporting </entry>
4416 <entry> <literal>(?:</><replaceable>re</><literal>)</> </entry>
4417 <entry> as above, but the match is not noted for reporting
4418 (a <quote>non-capturing</> set of parentheses)
4419 (AREs only) </entry>
4423 <entry> <literal>.</> </entry>
4424 <entry> matches any single character </entry>
4428 <entry> <literal>[</><replaceable>chars</><literal>]</> </entry>
4429 <entry> a <firstterm>bracket expression</>,
4430 matching any one of the <replaceable>chars</> (see
4431 <xref linkend="posix-bracket-expressions"> for more detail) </entry>
4435 <entry> <literal>\</><replaceable>k</> </entry>
4436 <entry> (where <replaceable>k</> is a non-alphanumeric character)
4437 matches that character taken as an ordinary character,
4438 e.g., <literal>\\</> matches a backslash character </entry>
4442 <entry> <literal>\</><replaceable>c</> </entry>
4443 <entry> where <replaceable>c</> is alphanumeric
4444 (possibly followed by other characters)
4445 is an <firstterm>escape</>, see <xref linkend="posix-escape-sequences">
4446 (AREs only; in EREs and BREs, this matches <replaceable>c</>) </entry>
4450 <entry> <literal>{</> </entry>
4451 <entry> when followed by a character other than a digit,
4452 matches the left-brace character <literal>{</>;
4453 when followed by a digit, it is the beginning of a
4454 <replaceable>bound</> (see below) </entry>
4458 <entry> <replaceable>x</> </entry>
4459 <entry> where <replaceable>x</> is a single character with no other
4460 significance, matches that character </entry>
4467 An RE cannot end with a backslash (<literal>\</>).
4472 If you have <xref linkend="guc-standard-conforming-strings"> turned off,
4473 any backslashes you write in literal string constants will need to be
4474 doubled. See <xref linkend="sql-syntax-strings"> for more information.
4478 <table id="posix-quantifiers-table">
4479 <title>Regular Expression Quantifiers</title>
4484 <entry>Quantifier</entry>
4485 <entry>Matches</entry>
4491 <entry> <literal>*</> </entry>
4492 <entry> a sequence of 0 or more matches of the atom </entry>
4496 <entry> <literal>+</> </entry>
4497 <entry> a sequence of 1 or more matches of the atom </entry>
4501 <entry> <literal>?</> </entry>
4502 <entry> a sequence of 0 or 1 matches of the atom </entry>
4506 <entry> <literal>{</><replaceable>m</><literal>}</> </entry>
4507 <entry> a sequence of exactly <replaceable>m</> matches of the atom </entry>
4511 <entry> <literal>{</><replaceable>m</><literal>,}</> </entry>
4512 <entry> a sequence of <replaceable>m</> or more matches of the atom </entry>
4517 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
4518 <entry> a sequence of <replaceable>m</> through <replaceable>n</>
4519 (inclusive) matches of the atom; <replaceable>m</> cannot exceed
4520 <replaceable>n</> </entry>
4524 <entry> <literal>*?</> </entry>
4525 <entry> non-greedy version of <literal>*</> </entry>
4529 <entry> <literal>+?</> </entry>
4530 <entry> non-greedy version of <literal>+</> </entry>
4534 <entry> <literal>??</> </entry>
4535 <entry> non-greedy version of <literal>?</> </entry>
4539 <entry> <literal>{</><replaceable>m</><literal>}?</> </entry>
4540 <entry> non-greedy version of <literal>{</><replaceable>m</><literal>}</> </entry>
4544 <entry> <literal>{</><replaceable>m</><literal>,}?</> </entry>
4545 <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,}</> </entry>
4550 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</> </entry>
4551 <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
4558 The forms using <literal>{</><replaceable>...</><literal>}</>
4559 are known as <firstterm>bounds</>.
4560 The numbers <replaceable>m</> and <replaceable>n</> within a bound are
4561 unsigned decimal integers with permissible values from 0 to 255 inclusive.
4565 <firstterm>Non-greedy</> quantifiers (available in AREs only) match the
4566 same possibilities as their corresponding normal (<firstterm>greedy</>)
4567 counterparts, but prefer the smallest number rather than the largest
4569 See <xref linkend="posix-matching-rules"> for more detail.
4574 A quantifier cannot immediately follow another quantifier, e.g.,
4575 <literal>**</> is invalid.
4577 begin an expression or subexpression or follow
4578 <literal>^</literal> or <literal>|</literal>.
4582 <table id="posix-constraints-table">
4583 <title>Regular Expression Constraints</title>
4588 <entry>Constraint</entry>
4589 <entry>Description</entry>
4595 <entry> <literal>^</> </entry>
4596 <entry> matches at the beginning of the string </entry>
4600 <entry> <literal>$</> </entry>
4601 <entry> matches at the end of the string </entry>
4605 <entry> <literal>(?=</><replaceable>re</><literal>)</> </entry>
4606 <entry> <firstterm>positive lookahead</> matches at any point
4607 where a substring matching <replaceable>re</> begins
4608 (AREs only) </entry>
4612 <entry> <literal>(?!</><replaceable>re</><literal>)</> </entry>
4613 <entry> <firstterm>negative lookahead</> matches at any point
4614 where no substring matching <replaceable>re</> begins
4615 (AREs only) </entry>
4619 <entry> <literal>(?<=</><replaceable>re</><literal>)</> </entry>
4620 <entry> <firstterm>positive lookbehind</> matches at any point
4621 where a substring matching <replaceable>re</> ends
4622 (AREs only) </entry>
4626 <entry> <literal>(?<!</><replaceable>re</><literal>)</> </entry>
4627 <entry> <firstterm>negative lookbehind</> matches at any point
4628 where no substring matching <replaceable>re</> ends
4629 (AREs only) </entry>
4636 Lookahead and lookbehind constraints cannot contain <firstterm>back
4637 references</> (see <xref linkend="posix-escape-sequences">),
4638 and all parentheses within them are considered non-capturing.
4642 <sect3 id="posix-bracket-expressions">
4643 <title>Bracket Expressions</title>
4646 A <firstterm>bracket expression</firstterm> is a list of
4647 characters enclosed in <literal>[]</literal>. It normally matches
4648 any single character from the list (but see below). If the list
4649 begins with <literal>^</literal>, it matches any single character
4650 <emphasis>not</> from the rest of the list.
4652 in the list are separated by <literal>-</literal>, this is
4653 shorthand for the full range of characters between those two
4654 (inclusive) in the collating sequence,
4655 e.g., <literal>[0-9]</literal> in <acronym>ASCII</acronym> matches
4656 any decimal digit. It is illegal for two ranges to share an
4657 endpoint, e.g., <literal>a-c-e</literal>. Ranges are very
4658 collating-sequence-dependent, so portable programs should avoid
4663 To include a literal <literal>]</literal> in the list, make it the
4664 first character (after <literal>^</literal>, if that is used). To
4665 include a literal <literal>-</literal>, make it the first or last
4666 character, or the second endpoint of a range. To use a literal
4667 <literal>-</literal> as the first endpoint of a range, enclose it
4668 in <literal>[.</literal> and <literal>.]</literal> to make it a
4669 collating element (see below). With the exception of these characters,
4670 some combinations using <literal>[</literal>
4671 (see next paragraphs), and escapes (AREs only), all other special
4672 characters lose their special significance within a bracket expression.
4673 In particular, <literal>\</literal> is not special when following
4674 ERE or BRE rules, though it is special (as introducing an escape)
4679 Within a bracket expression, a collating element (a character, a
4680 multiple-character sequence that collates as if it were a single
4681 character, or a collating-sequence name for either) enclosed in
4682 <literal>[.</literal> and <literal>.]</literal> stands for the
4683 sequence of characters of that collating element. The sequence is
4684 treated as a single element of the bracket expression's list. This
4686 expression containing a multiple-character collating element to
4687 match more than one character, e.g., if the collating sequence
4688 includes a <literal>ch</literal> collating element, then the RE
4689 <literal>[[.ch.]]*c</literal> matches the first five characters of
4690 <literal>chchcc</literal>.
4695 <productname>PostgreSQL</> currently does not support multi-character collating
4696 elements. This information describes possible future behavior.
4701 Within a bracket expression, a collating element enclosed in
4702 <literal>[=</literal> and <literal>=]</literal> is an <firstterm>equivalence
4703 class</>, standing for the sequences of characters of all collating
4704 elements equivalent to that one, including itself. (If there are
4705 no other equivalent collating elements, the treatment is as if the
4706 enclosing delimiters were <literal>[.</literal> and
4707 <literal>.]</literal>.) For example, if <literal>o</literal> and
4708 <literal>^</literal> are the members of an equivalence class, then
4709 <literal>[[=o=]]</literal>, <literal>[[=^=]]</literal>, and
4710 <literal>[o^]</literal> are all synonymous. An equivalence class
4711 cannot be an endpoint of a range.
4715 Within a bracket expression, the name of a character class
4716 enclosed in <literal>[:</literal> and <literal>:]</literal> stands
4717 for the list of all characters belonging to that class. Standard
4718 character class names are: <literal>alnum</literal>,
4719 <literal>alpha</literal>, <literal>blank</literal>,
4720 <literal>cntrl</literal>, <literal>digit</literal>,
4721 <literal>graph</literal>, <literal>lower</literal>,
4722 <literal>print</literal>, <literal>punct</literal>,
4723 <literal>space</literal>, <literal>upper</literal>,
4724 <literal>xdigit</literal>. These stand for the character classes
4726 <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>.
4727 A locale can provide others. A character class cannot be used as
4728 an endpoint of a range.
4732 There are two special cases of bracket expressions: the bracket
4733 expressions <literal>[[:<:]]</literal> and
4734 <literal>[[:>:]]</literal> are constraints,
4735 matching empty strings at the beginning
4736 and end of a word respectively. A word is defined as a sequence
4737 of word characters that is neither preceded nor followed by word
4738 characters. A word character is an <literal>alnum</> character (as
4740 <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>)
4741 or an underscore. This is an extension, compatible with but not
4742 specified by <acronym>POSIX</acronym> 1003.2, and should be used with
4743 caution in software intended to be portable to other systems.
4744 The constraint escapes described below are usually preferable; they
4745 are no more standard, but are easier to type.
4749 <sect3 id="posix-escape-sequences">
4750 <title>Regular Expression Escapes</title>
4753 <firstterm>Escapes</> are special sequences beginning with <literal>\</>
4754 followed by an alphanumeric character. Escapes come in several varieties:
4755 character entry, class shorthands, constraint escapes, and back references.
4756 A <literal>\</> followed by an alphanumeric character but not constituting
4757 a valid escape is illegal in AREs.
4758 In EREs, there are no escapes: outside a bracket expression,
4759 a <literal>\</> followed by an alphanumeric character merely stands for
4760 that character as an ordinary character, and inside a bracket expression,
4761 <literal>\</> is an ordinary character.
4762 (The latter is the one actual incompatibility between EREs and AREs.)
4766 <firstterm>Character-entry escapes</> exist to make it easier to specify
4767 non-printing and other inconvenient characters in REs. They are
4768 shown in <xref linkend="posix-character-entry-escapes-table">.
4772 <firstterm>Class-shorthand escapes</> provide shorthands for certain
4773 commonly-used character classes. They are
4774 shown in <xref linkend="posix-class-shorthand-escapes-table">.
4778 A <firstterm>constraint escape</> is a constraint,
4779 matching the empty string if specific conditions are met,
4780 written as an escape. They are
4781 shown in <xref linkend="posix-constraint-escapes-table">.
4785 A <firstterm>back reference</> (<literal>\</><replaceable>n</>) matches the
4786 same string matched by the previous parenthesized subexpression specified
4787 by the number <replaceable>n</>
4788 (see <xref linkend="posix-constraint-backref-table">). For example,
4789 <literal>([bc])\1</> matches <literal>bb</> or <literal>cc</>
4790 but not <literal>bc</> or <literal>cb</>.
4791 The subexpression must entirely precede the back reference in the RE.
4792 Subexpressions are numbered in the order of their leading parentheses.
4793 Non-capturing parentheses do not define subexpressions.
4796 <table id="posix-character-entry-escapes-table">
4797 <title>Regular Expression Character-entry Escapes</title>
4802 <entry>Escape</entry>
4803 <entry>Description</entry>
4809 <entry> <literal>\a</> </entry>
4810 <entry> alert (bell) character, as in C </entry>
4814 <entry> <literal>\b</> </entry>
4815 <entry> backspace, as in C </entry>
4819 <entry> <literal>\B</> </entry>
4820 <entry> synonym for backslash (<literal>\</>) to help reduce the need for backslash
4825 <entry> <literal>\c</><replaceable>X</> </entry>
4826 <entry> (where <replaceable>X</> is any character) the character whose
4827 low-order 5 bits are the same as those of
4828 <replaceable>X</>, and whose other bits are all zero </entry>
4832 <entry> <literal>\e</> </entry>
4833 <entry> the character whose collating-sequence name
4835 or failing that, the character with octal value <literal>033</> </entry>
4839 <entry> <literal>\f</> </entry>
4840 <entry> form feed, as in C </entry>
4844 <entry> <literal>\n</> </entry>
4845 <entry> newline, as in C </entry>
4849 <entry> <literal>\r</> </entry>
4850 <entry> carriage return, as in C </entry>
4854 <entry> <literal>\t</> </entry>
4855 <entry> horizontal tab, as in C </entry>
4859 <entry> <literal>\u</><replaceable>wxyz</> </entry>
4860 <entry> (where <replaceable>wxyz</> is exactly four hexadecimal digits)
4861 the character whose hexadecimal value is
4862 <literal>0x</><replaceable>wxyz</>
4867 <entry> <literal>\U</><replaceable>stuvwxyz</> </entry>
4868 <entry> (where <replaceable>stuvwxyz</> is exactly eight hexadecimal
4870 the character whose hexadecimal value is
4871 <literal>0x</><replaceable>stuvwxyz</>
4876 <entry> <literal>\v</> </entry>
4877 <entry> vertical tab, as in C </entry>
4881 <entry> <literal>\x</><replaceable>hhh</> </entry>
4882 <entry> (where <replaceable>hhh</> is any sequence of hexadecimal
4884 the character whose hexadecimal value is
4885 <literal>0x</><replaceable>hhh</>
4886 (a single character no matter how many hexadecimal digits are used)
4891 <entry> <literal>\0</> </entry>
4892 <entry> the character whose value is <literal>0</> (the null byte)</entry>
4896 <entry> <literal>\</><replaceable>xy</> </entry>
4897 <entry> (where <replaceable>xy</> is exactly two octal digits,
4898 and is not a <firstterm>back reference</>)
4899 the character whose octal value is
4900 <literal>0</><replaceable>xy</> </entry>
4904 <entry> <literal>\</><replaceable>xyz</> </entry>
4905 <entry> (where <replaceable>xyz</> is exactly three octal digits,
4906 and is not a <firstterm>back reference</>)
4907 the character whose octal value is
4908 <literal>0</><replaceable>xyz</> </entry>
4915 Hexadecimal digits are <literal>0</>-<literal>9</>,
4916 <literal>a</>-<literal>f</>, and <literal>A</>-<literal>F</>.
4917 Octal digits are <literal>0</>-<literal>7</>.
4921 Numeric character-entry escapes specifying values outside the ASCII range
4922 (0-127) have meanings dependent on the database encoding. When the
4923 encoding is UTF-8, escape values are equivalent to Unicode code points,
4924 for example <literal>\u1234</> means the character <literal>U+1234</>.
4925 For other multibyte encodings, character-entry escapes usually just
4926 specify the concatenation of the byte values for the character. If the
4927 escape value does not correspond to any legal character in the database
4928 encoding, no error will be raised, but it will never match any data.
4932 The character-entry escapes are always taken as ordinary characters.
4933 For example, <literal>\135</> is <literal>]</> in ASCII, but
4934 <literal>\135</> does not terminate a bracket expression.
4937 <table id="posix-class-shorthand-escapes-table">
4938 <title>Regular Expression Class-shorthand Escapes</title>
4943 <entry>Escape</entry>
4944 <entry>Description</entry>
4950 <entry> <literal>\d</> </entry>
4951 <entry> <literal>[[:digit:]]</> </entry>
4955 <entry> <literal>\s</> </entry>
4956 <entry> <literal>[[:space:]]</> </entry>
4960 <entry> <literal>\w</> </entry>
4961 <entry> <literal>[[:alnum:]_]</>
4962 (note underscore is included) </entry>
4966 <entry> <literal>\D</> </entry>
4967 <entry> <literal>[^[:digit:]]</> </entry>
4971 <entry> <literal>\S</> </entry>
4972 <entry> <literal>[^[:space:]]</> </entry>
4976 <entry> <literal>\W</> </entry>
4977 <entry> <literal>[^[:alnum:]_]</>
4978 (note underscore is included) </entry>
4985 Within bracket expressions, <literal>\d</>, <literal>\s</>,
4986 and <literal>\w</> lose their outer brackets,
4987 and <literal>\D</>, <literal>\S</>, and <literal>\W</> are illegal.
4988 (So, for example, <literal>[a-c\d]</> is equivalent to
4989 <literal>[a-c[:digit:]]</>.
4990 Also, <literal>[a-c\D]</>, which is equivalent to
4991 <literal>[a-c^[:digit:]]</>, is illegal.)
4994 <table id="posix-constraint-escapes-table">
4995 <title>Regular Expression Constraint Escapes</title>
5000 <entry>Escape</entry>
5001 <entry>Description</entry>
5007 <entry> <literal>\A</> </entry>
5008 <entry> matches only at the beginning of the string
5009 (see <xref linkend="posix-matching-rules"> for how this differs from
5010 <literal>^</>) </entry>
5014 <entry> <literal>\m</> </entry>
5015 <entry> matches only at the beginning of a word </entry>
5019 <entry> <literal>\M</> </entry>
5020 <entry> matches only at the end of a word </entry>
5024 <entry> <literal>\y</> </entry>
5025 <entry> matches only at the beginning or end of a word </entry>
5029 <entry> <literal>\Y</> </entry>
5030 <entry> matches only at a point that is not the beginning or end of a
5035 <entry> <literal>\Z</> </entry>
5036 <entry> matches only at the end of the string
5037 (see <xref linkend="posix-matching-rules"> for how this differs from
5038 <literal>$</>) </entry>
5045 A word is defined as in the specification of
5046 <literal>[[:<:]]</> and <literal>[[:>:]]</> above.
5047 Constraint escapes are illegal within bracket expressions.
5050 <table id="posix-constraint-backref-table">
5051 <title>Regular Expression Back References</title>
5056 <entry>Escape</entry>
5057 <entry>Description</entry>
5063 <entry> <literal>\</><replaceable>m</> </entry>
5064 <entry> (where <replaceable>m</> is a nonzero digit)
5065 a back reference to the <replaceable>m</>'th subexpression </entry>
5069 <entry> <literal>\</><replaceable>mnn</> </entry>
5070 <entry> (where <replaceable>m</> is a nonzero digit, and
5071 <replaceable>nn</> is some more digits, and the decimal value
5072 <replaceable>mnn</> is not greater than the number of closing capturing
5073 parentheses seen so far)
5074 a back reference to the <replaceable>mnn</>'th subexpression </entry>
5082 There is an inherent ambiguity between octal character-entry
5083 escapes and back references, which is resolved by the following heuristics,
5085 A leading zero always indicates an octal escape.
5086 A single non-zero digit, not followed by another digit,
5087 is always taken as a back reference.
5088 A multi-digit sequence not starting with a zero is taken as a back
5089 reference if it comes after a suitable subexpression
5090 (i.e., the number is in the legal range for a back reference),
5091 and otherwise is taken as octal.
5096 <sect3 id="posix-metasyntax">
5097 <title>Regular Expression Metasyntax</title>
5100 In addition to the main syntax described above, there are some special
5101 forms and miscellaneous syntactic facilities available.
5105 An RE can begin with one of two special <firstterm>director</> prefixes.
5106 If an RE begins with <literal>***:</>,
5107 the rest of the RE is taken as an ARE. (This normally has no effect in
5108 <productname>PostgreSQL</>, since REs are assumed to be AREs;
5109 but it does have an effect if ERE or BRE mode had been specified by
5110 the <replaceable>flags</> parameter to a regex function.)
5111 If an RE begins with <literal>***=</>,
5112 the rest of the RE is taken to be a literal string,
5113 with all characters considered ordinary characters.
5117 An ARE can begin with <firstterm>embedded options</>:
5118 a sequence <literal>(?</><replaceable>xyz</><literal>)</>
5119 (where <replaceable>xyz</> is one or more alphabetic characters)
5120 specifies options affecting the rest of the RE.
5121 These options override any previously determined options —
5122 in particular, they can override the case-sensitivity behavior implied by
5123 a regex operator, or the <replaceable>flags</> parameter to a regex
5125 The available option letters are
5126 shown in <xref linkend="posix-embedded-options-table">.
5127 Note that these same option letters are used in the <replaceable>flags</>
5128 parameters of regex functions.
5131 <table id="posix-embedded-options-table">
5132 <title>ARE Embedded-option Letters</title>
5137 <entry>Option</entry>
5138 <entry>Description</entry>
5144 <entry> <literal>b</> </entry>
5145 <entry> rest of RE is a BRE </entry>
5149 <entry> <literal>c</> </entry>
5150 <entry> case-sensitive matching (overrides operator type) </entry>
5154 <entry> <literal>e</> </entry>
5155 <entry> rest of RE is an ERE </entry>
5159 <entry> <literal>i</> </entry>
5160 <entry> case-insensitive matching (see
5161 <xref linkend="posix-matching-rules">) (overrides operator type) </entry>
5165 <entry> <literal>m</> </entry>
5166 <entry> historical synonym for <literal>n</> </entry>
5170 <entry> <literal>n</> </entry>
5171 <entry> newline-sensitive matching (see
5172 <xref linkend="posix-matching-rules">) </entry>
5176 <entry> <literal>p</> </entry>
5177 <entry> partial newline-sensitive matching (see
5178 <xref linkend="posix-matching-rules">) </entry>
5182 <entry> <literal>q</> </entry>
5183 <entry> rest of RE is a literal (<quote>quoted</>) string, all ordinary
5188 <entry> <literal>s</> </entry>
5189 <entry> non-newline-sensitive matching (default) </entry>
5193 <entry> <literal>t</> </entry>
5194 <entry> tight syntax (default; see below) </entry>
5198 <entry> <literal>w</> </entry>
5199 <entry> inverse partial newline-sensitive (<quote>weird</>) matching
5200 (see <xref linkend="posix-matching-rules">) </entry>
5204 <entry> <literal>x</> </entry>
5205 <entry> expanded syntax (see below) </entry>
5212 Embedded options take effect at the <literal>)</> terminating the sequence.
5213 They can appear only at the start of an ARE (after the
5214 <literal>***:</> director if any).
5218 In addition to the usual (<firstterm>tight</>) RE syntax, in which all
5219 characters are significant, there is an <firstterm>expanded</> syntax,
5220 available by specifying the embedded <literal>x</> option.
5221 In the expanded syntax,
5222 white-space characters in the RE are ignored, as are
5223 all characters between a <literal>#</>
5224 and the following newline (or the end of the RE). This
5225 permits paragraphing and commenting a complex RE.
5226 There are three exceptions to that basic rule:
5231 a white-space character or <literal>#</> preceded by <literal>\</> is
5237 white space or <literal>#</> within a bracket expression is retained
5242 white space and comments cannot appear within multi-character symbols,
5243 such as <literal>(?:</>
5248 For this purpose, white-space characters are blank, tab, newline, and
5249 any character that belongs to the <replaceable>space</> character class.
5253 Finally, in an ARE, outside bracket expressions, the sequence
5254 <literal>(?#</><replaceable>ttt</><literal>)</>
5255 (where <replaceable>ttt</> is any text not containing a <literal>)</>)
5256 is a comment, completely ignored.
5257 Again, this is not allowed between the characters of
5258 multi-character symbols, like <literal>(?:</>.
5259 Such comments are more a historical artifact than a useful facility,
5260 and their use is deprecated; use the expanded syntax instead.
5264 <emphasis>None</> of these metasyntax extensions is available if
5265 an initial <literal>***=</> director
5266 has specified that the user's input be treated as a literal string
5267 rather than as an RE.
5271 <sect3 id="posix-matching-rules">
5272 <title>Regular Expression Matching Rules</title>
5275 In the event that an RE could match more than one substring of a given
5276 string, the RE matches the one starting earliest in the string.
5277 If the RE could match more than one substring starting at that point,
5278 either the longest possible match or the shortest possible match will
5279 be taken, depending on whether the RE is <firstterm>greedy</> or
5280 <firstterm>non-greedy</>.
5284 Whether an RE is greedy or not is determined by the following rules:
5288 Most atoms, and all constraints, have no greediness attribute (because
5289 they cannot match variable amounts of text anyway).
5294 Adding parentheses around an RE does not change its greediness.
5299 A quantified atom with a fixed-repetition quantifier
5300 (<literal>{</><replaceable>m</><literal>}</>
5302 <literal>{</><replaceable>m</><literal>}?</>)
5303 has the same greediness (possibly none) as the atom itself.
5308 A quantified atom with other normal quantifiers (including
5309 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</>
5310 with <replaceable>m</> equal to <replaceable>n</>)
5311 is greedy (prefers longest match).
5316 A quantified atom with a non-greedy quantifier (including
5317 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</>
5318 with <replaceable>m</> equal to <replaceable>n</>)
5319 is non-greedy (prefers shortest match).
5324 A branch — that is, an RE that has no top-level
5325 <literal>|</> operator — has the same greediness as the first
5326 quantified atom in it that has a greediness attribute.
5331 An RE consisting of two or more branches connected by the
5332 <literal>|</> operator is always greedy.
5339 The above rules associate greediness attributes not only with individual
5340 quantified atoms, but with branches and entire REs that contain quantified
5341 atoms. What that means is that the matching is done in such a way that
5342 the branch, or whole RE, matches the longest or shortest possible
5343 substring <emphasis>as a whole</>. Once the length of the entire match
5344 is determined, the part of it that matches any particular subexpression
5345 is determined on the basis of the greediness attribute of that
5346 subexpression, with subexpressions starting earlier in the RE taking
5347 priority over ones starting later.
5351 An example of what this means:
5353 SELECT SUBSTRING('XY1234Z', 'Y*([0-9]{1,3})');
5354 <lineannotation>Result: </lineannotation><computeroutput>123</computeroutput>
5355 SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{1,3})');
5356 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
5358 In the first case, the RE as a whole is greedy because <literal>Y*</>
5359 is greedy. It can match beginning at the <literal>Y</>, and it matches
5360 the longest possible string starting there, i.e., <literal>Y123</>.
5361 The output is the parenthesized part of that, or <literal>123</>.
5362 In the second case, the RE as a whole is non-greedy because <literal>Y*?</>
5363 is non-greedy. It can match beginning at the <literal>Y</>, and it matches
5364 the shortest possible string starting there, i.e., <literal>Y1</>.
5365 The subexpression <literal>[0-9]{1,3}</> is greedy but it cannot change
5366 the decision as to the overall match length; so it is forced to match
5371 In short, when an RE contains both greedy and non-greedy subexpressions,
5372 the total match length is either as long as possible or as short as
5373 possible, according to the attribute assigned to the whole RE. The
5374 attributes assigned to the subexpressions only affect how much of that
5375 match they are allowed to <quote>eat</> relative to each other.
5379 The quantifiers <literal>{1,1}</> and <literal>{1,1}?</>
5380 can be used to force greediness or non-greediness, respectively,
5381 on a subexpression or a whole RE.
5382 This is useful when you need the whole RE to have a greediness attribute
5383 different from what's deduced from its elements. As an example,
5384 suppose that we are trying to separate a string containing some digits
5385 into the digits and the parts before and after them. We might try to
5388 SELECT regexp_matches('abc01234xyz', '(.*)(\d+)(.*)');
5389 <lineannotation>Result: </lineannotation><computeroutput>{abc0123,4,xyz}</computeroutput>
5391 That didn't work: the first <literal>.*</> is greedy so
5392 it <quote>eats</> as much as it can, leaving the <literal>\d+</> to
5393 match at the last possible place, the last digit. We might try to fix
5394 that by making it non-greedy:
5396 SELECT regexp_matches('abc01234xyz', '(.*?)(\d+)(.*)');
5397 <lineannotation>Result: </lineannotation><computeroutput>{abc,0,""}</computeroutput>
5399 That didn't work either, because now the RE as a whole is non-greedy
5400 and so it ends the overall match as soon as possible. We can get what
5401 we want by forcing the RE as a whole to be greedy:
5403 SELECT regexp_matches('abc01234xyz', '(?:(.*?)(\d+)(.*)){1,1}');
5404 <lineannotation>Result: </lineannotation><computeroutput>{abc,01234,xyz}</computeroutput>
5406 Controlling the RE's overall greediness separately from its components'
5407 greediness allows great flexibility in handling variable-length patterns.
5411 When deciding what is a longer or shorter match,
5412 match lengths are measured in characters, not collating elements.
5413 An empty string is considered longer than no match at all.
5416 matches the three middle characters of <literal>abbbc</>;
5417 <literal>(week|wee)(night|knights)</>
5418 matches all ten characters of <literal>weeknights</>;
5419 when <literal>(.*).*</>
5420 is matched against <literal>abc</> the parenthesized subexpression
5421 matches all three characters; and when
5422 <literal>(a*)*</> is matched against <literal>bc</>
5423 both the whole RE and the parenthesized
5424 subexpression match an empty string.
5428 If case-independent matching is specified,
5429 the effect is much as if all case distinctions had vanished from the
5431 When an alphabetic that exists in multiple cases appears as an
5432 ordinary character outside a bracket expression, it is effectively
5433 transformed into a bracket expression containing both cases,
5434 e.g., <literal>x</> becomes <literal>[xX]</>.
5435 When it appears inside a bracket expression, all case counterparts
5436 of it are added to the bracket expression, e.g.,
5437 <literal>[x]</> becomes <literal>[xX]</>
5438 and <literal>[^x]</> becomes <literal>[^xX]</>.
5442 If newline-sensitive matching is specified, <literal>.</>
5443 and bracket expressions using <literal>^</>
5444 will never match the newline character
5445 (so that matches will never cross newlines unless the RE
5446 explicitly arranges it)
5447 and <literal>^</> and <literal>$</>
5448 will match the empty string after and before a newline
5449 respectively, in addition to matching at beginning and end of string
5451 But the ARE escapes <literal>\A</> and <literal>\Z</>
5452 continue to match beginning or end of string <emphasis>only</>.
5456 If partial newline-sensitive matching is specified,
5457 this affects <literal>.</> and bracket expressions
5458 as with newline-sensitive matching, but not <literal>^</>
5463 If inverse partial newline-sensitive matching is specified,
5464 this affects <literal>^</> and <literal>$</>
5465 as with newline-sensitive matching, but not <literal>.</>
5466 and bracket expressions.
5467 This isn't very useful but is provided for symmetry.
5471 <sect3 id="posix-limits-compatibility">
5472 <title>Limits and Compatibility</title>
5475 No particular limit is imposed on the length of REs in this
5476 implementation. However,
5477 programs intended to be highly portable should not employ REs longer
5479 as a POSIX-compliant implementation can refuse to accept such REs.
5483 The only feature of AREs that is actually incompatible with
5484 POSIX EREs is that <literal>\</> does not lose its special
5485 significance inside bracket expressions.
5486 All other ARE features use syntax which is illegal or has
5487 undefined or unspecified effects in POSIX EREs;
5488 the <literal>***</> syntax of directors likewise is outside the POSIX
5489 syntax for both BREs and EREs.
5493 Many of the ARE extensions are borrowed from Perl, but some have
5494 been changed to clean them up, and a few Perl extensions are not present.
5495 Incompatibilities of note include <literal>\b</>, <literal>\B</>,
5496 the lack of special treatment for a trailing newline,
5497 the addition of complemented bracket expressions to the things
5498 affected by newline-sensitive matching,
5499 the restrictions on parentheses and back references in lookahead/lookbehind
5500 constraints, and the longest/shortest-match (rather than first-match)
5505 Two significant incompatibilities exist between AREs and the ERE syntax
5506 recognized by pre-7.4 releases of <productname>PostgreSQL</>:
5511 In AREs, <literal>\</> followed by an alphanumeric character is either
5512 an escape or an error, while in previous releases, it was just another
5513 way of writing the alphanumeric.
5514 This should not be much of a problem because there was no reason to
5515 write such a sequence in earlier releases.
5520 In AREs, <literal>\</> remains a special character within
5521 <literal>[]</>, so a literal <literal>\</> within a bracket
5522 expression must be written <literal>\\</>.
5529 <sect3 id="posix-basic-regexes">
5530 <title>Basic Regular Expressions</title>
5533 BREs differ from EREs in several respects.
5534 In BREs, <literal>|</>, <literal>+</>, and <literal>?</>
5535 are ordinary characters and there is no equivalent
5536 for their functionality.
5537 The delimiters for bounds are
5538 <literal>\{</> and <literal>\}</>,
5539 with <literal>{</> and <literal>}</>
5540 by themselves ordinary characters.
5541 The parentheses for nested subexpressions are
5542 <literal>\(</> and <literal>\)</>,
5543 with <literal>(</> and <literal>)</> by themselves ordinary characters.
5544 <literal>^</> is an ordinary character except at the beginning of the
5545 RE or the beginning of a parenthesized subexpression,
5546 <literal>$</> is an ordinary character except at the end of the
5547 RE or the end of a parenthesized subexpression,
5548 and <literal>*</> is an ordinary character if it appears at the beginning
5549 of the RE or the beginning of a parenthesized subexpression
5550 (after a possible leading <literal>^</>).
5551 Finally, single-digit back references are available, and
5552 <literal>\<</> and <literal>\></>
5554 <literal>[[:<:]]</> and <literal>[[:>:]]</>
5555 respectively; no other escapes are available in BREs.
5559 <!-- end re_syntax.n man page -->
5565 <sect1 id="functions-formatting">
5566 <title>Data Type Formatting Functions</title>
5569 <primary>formatting</primary>
5573 The <productname>PostgreSQL</productname> formatting functions
5574 provide a powerful set of tools for converting various data types
5575 (date/time, integer, floating point, numeric) to formatted strings
5576 and for converting from formatted strings to specific data types.
5577 <xref linkend="functions-formatting-table"> lists them.
5578 These functions all follow a common calling convention: the first
5579 argument is the value to be formatted and the second argument is a
5580 template that defines the output or input format.
5583 <table id="functions-formatting-table">
5584 <title>Formatting Functions</title>
5588 <entry>Function</entry>
5589 <entry>Return Type</entry>
5590 <entry>Description</entry>
5591 <entry>Example</entry>
5598 <primary>to_char</primary>
5600 <literal><function>to_char(<type>timestamp</type>, <type>text</type>)</function></literal>
5602 <entry><type>text</type></entry>
5603 <entry>convert time stamp to string</entry>
5604 <entry><literal>to_char(current_timestamp, 'HH12:MI:SS')</literal></entry>
5607 <entry><literal><function>to_char(<type>interval</type>, <type>text</type>)</function></literal></entry>
5608 <entry><type>text</type></entry>
5609 <entry>convert interval to string</entry>
5610 <entry><literal>to_char(interval '15h 2m 12s', 'HH24:MI:SS')</literal></entry>
5613 <entry><literal><function>to_char(<type>int</type>, <type>text</type>)</function></literal></entry>
5614 <entry><type>text</type></entry>
5615 <entry>convert integer to string</entry>
5616 <entry><literal>to_char(125, '999')</literal></entry>
5619 <entry><literal><function>to_char</function>(<type>double precision</type>,
5620 <type>text</type>)</literal></entry>
5621 <entry><type>text</type></entry>
5622 <entry>convert real/double precision to string</entry>
5623 <entry><literal>to_char(125.8::real, '999D9')</literal></entry>
5626 <entry><literal><function>to_char(<type>numeric</type>, <type>text</type>)</function></literal></entry>
5627 <entry><type>text</type></entry>
5628 <entry>convert numeric to string</entry>
5629 <entry><literal>to_char(-125.8, '999D99S')</literal></entry>
5634 <primary>to_date</primary>
5636 <literal><function>to_date(<type>text</type>, <type>text</type>)</function></literal>
5638 <entry><type>date</type></entry>
5639 <entry>convert string to date</entry>
5640 <entry><literal>to_date('05 Dec 2000', 'DD Mon YYYY')</literal></entry>
5645 <primary>to_number</primary>
5647 <literal><function>to_number(<type>text</type>, <type>text</type>)</function></literal>
5649 <entry><type>numeric</type></entry>
5650 <entry>convert string to numeric</entry>
5651 <entry><literal>to_number('12,454.8-', '99G999D9S')</literal></entry>
5656 <primary>to_timestamp</primary>
5658 <literal><function>to_timestamp(<type>text</type>, <type>text</type>)</function></literal>
5660 <entry><type>timestamp with time zone</type></entry>
5661 <entry>convert string to time stamp</entry>
5662 <entry><literal>to_timestamp('05 Dec 2000', 'DD Mon YYYY')</literal></entry>
5670 There is also a single-argument <function>to_timestamp</function>
5671 function; see <xref linkend="functions-datetime-table">.
5676 In a <function>to_char</> output template string, there are certain
5677 patterns that are recognized and replaced with appropriately-formatted
5678 data based on the given value. Any text that is not a template pattern is
5679 simply copied verbatim. Similarly, in an input template string (for the
5680 other functions), template patterns identify the values to be supplied by
5681 the input data string.
5685 <xref linkend="functions-formatting-datetime-table"> shows the
5686 template patterns available for formatting date and time values.
5689 <table id="functions-formatting-datetime-table">
5690 <title>Template Patterns for Date/Time Formatting</title>
5694 <entry>Pattern</entry>
5695 <entry>Description</entry>
5700 <entry><literal>HH</literal></entry>
5701 <entry>hour of day (01-12)</entry>
5704 <entry><literal>HH12</literal></entry>
5705 <entry>hour of day (01-12)</entry>
5708 <entry><literal>HH24</literal></entry>
5709 <entry>hour of day (00-23)</entry>
5712 <entry><literal>MI</literal></entry>
5713 <entry>minute (00-59)</entry>
5716 <entry><literal>SS</literal></entry>
5717 <entry>second (00-59)</entry>
5720 <entry><literal>MS</literal></entry>
5721 <entry>millisecond (000-999)</entry>
5724 <entry><literal>US</literal></entry>
5725 <entry>microsecond (000000-999999)</entry>
5728 <entry><literal>SSSS</literal></entry>
5729 <entry>seconds past midnight (0-86399)</entry>
5732 <entry><literal>AM</literal>, <literal>am</literal>,
5733 <literal>PM</literal> or <literal>pm</literal></entry>
5734 <entry>meridiem indicator (without periods)</entry>
5737 <entry><literal>A.M.</literal>, <literal>a.m.</literal>,
5738 <literal>P.M.</literal> or <literal>p.m.</literal></entry>
5739 <entry>meridiem indicator (with periods)</entry>
5742 <entry><literal>Y,YYY</literal></entry>
5743 <entry>year (4 or more digits) with comma</entry>
5746 <entry><literal>YYYY</literal></entry>
5747 <entry>year (4 or more digits)</entry>
5750 <entry><literal>YYY</literal></entry>
5751 <entry>last 3 digits of year</entry>
5754 <entry><literal>YY</literal></entry>
5755 <entry>last 2 digits of year</entry>
5758 <entry><literal>Y</literal></entry>
5759 <entry>last digit of year</entry>
5762 <entry><literal>IYYY</literal></entry>
5763 <entry>ISO 8601 week-numbering year (4 or more digits)</entry>
5766 <entry><literal>IYY</literal></entry>
5767 <entry>last 3 digits of ISO 8601 week-numbering year</entry>
5770 <entry><literal>IY</literal></entry>
5771 <entry>last 2 digits of ISO 8601 week-numbering year</entry>
5774 <entry><literal>I</literal></entry>
5775 <entry>last digit of ISO 8601 week-numbering year</entry>
5778 <entry><literal>BC</literal>, <literal>bc</literal>,
5779 <literal>AD</literal> or <literal>ad</literal></entry>
5780 <entry>era indicator (without periods)</entry>
5783 <entry><literal>B.C.</literal>, <literal>b.c.</literal>,
5784 <literal>A.D.</literal> or <literal>a.d.</literal></entry>
5785 <entry>era indicator (with periods)</entry>
5788 <entry><literal>MONTH</literal></entry>
5789 <entry>full upper case month name (blank-padded to 9 chars)</entry>
5792 <entry><literal>Month</literal></entry>
5793 <entry>full capitalized month name (blank-padded to 9 chars)</entry>
5796 <entry><literal>month</literal></entry>
5797 <entry>full lower case month name (blank-padded to 9 chars)</entry>
5800 <entry><literal>MON</literal></entry>
5801 <entry>abbreviated upper case month name (3 chars in English, localized lengths vary)</entry>
5804 <entry><literal>Mon</literal></entry>
5805 <entry>abbreviated capitalized month name (3 chars in English, localized lengths vary)</entry>
5808 <entry><literal>mon</literal></entry>
5809 <entry>abbreviated lower case month name (3 chars in English, localized lengths vary)</entry>
5812 <entry><literal>MM</literal></entry>
5813 <entry>month number (01-12)</entry>
5816 <entry><literal>DAY</literal></entry>
5817 <entry>full upper case day name (blank-padded to 9 chars)</entry>
5820 <entry><literal>Day</literal></entry>
5821 <entry>full capitalized day name (blank-padded to 9 chars)</entry>
5824 <entry><literal>day</literal></entry>
5825 <entry>full lower case day name (blank-padded to 9 chars)</entry>
5828 <entry><literal>DY</literal></entry>
5829 <entry>abbreviated upper case day name (3 chars in English, localized lengths vary)</entry>
5832 <entry><literal>Dy</literal></entry>
5833 <entry>abbreviated capitalized day name (3 chars in English, localized lengths vary)</entry>
5836 <entry><literal>dy</literal></entry>
5837 <entry>abbreviated lower case day name (3 chars in English, localized lengths vary)</entry>
5840 <entry><literal>DDD</literal></entry>
5841 <entry>day of year (001-366)</entry>
5844 <entry><literal>IDDD</literal></entry>
5845 <entry>day of ISO 8601 week-numbering year (001-371; day 1 of the year is Monday of the first ISO week)</entry>
5848 <entry><literal>DD</literal></entry>
5849 <entry>day of month (01-31)</entry>
5852 <entry><literal>D</literal></entry>
5853 <entry>day of the week, Sunday (<literal>1</>) to Saturday (<literal>7</>)</entry>
5856 <entry><literal>ID</literal></entry>
5857 <entry>ISO 8601 day of the week, Monday (<literal>1</>) to Sunday (<literal>7</>)</entry>
5860 <entry><literal>W</literal></entry>
5861 <entry>week of month (1-5) (the first week starts on the first day of the month)</entry>
5864 <entry><literal>WW</literal></entry>
5865 <entry>week number of year (1-53) (the first week starts on the first day of the year)</entry>
5868 <entry><literal>IW</literal></entry>
5869 <entry>week number of ISO 8601 week-numbering year (01-53; the first Thursday of the year is in week 1)</entry>
5872 <entry><literal>CC</literal></entry>
5873 <entry>century (2 digits) (the twenty-first century starts on 2001-01-01)</entry>
5876 <entry><literal>J</literal></entry>
5877 <entry>Julian Day (integer days since November 24, 4714 BC at midnight UTC)</entry>
5880 <entry><literal>Q</literal></entry>
5881 <entry>quarter (ignored by <function>to_date</> and <function>to_timestamp</>)</entry>
5884 <entry><literal>RM</literal></entry>
5885 <entry>month in upper case Roman numerals (I-XII; I=January)</entry>
5888 <entry><literal>rm</literal></entry>
5889 <entry>month in lower case Roman numerals (i-xii; i=January)</entry>
5892 <entry><literal>TZ</literal></entry>
5893 <entry>upper case time-zone name</entry>
5896 <entry><literal>tz</literal></entry>
5897 <entry>lower case time-zone name</entry>
5900 <entry><literal>OF</literal></entry>
5901 <entry>time-zone offset</entry>
5908 Modifiers can be applied to any template pattern to alter its
5909 behavior. For example, <literal>FMMonth</literal>
5910 is the <literal>Month</literal> pattern with the
5911 <literal>FM</literal> modifier.
5912 <xref linkend="functions-formatting-datetimemod-table"> shows the
5913 modifier patterns for date/time formatting.
5916 <table id="functions-formatting-datetimemod-table">
5917 <title>Template Pattern Modifiers for Date/Time Formatting</title>
5921 <entry>Modifier</entry>
5922 <entry>Description</entry>
5923 <entry>Example</entry>
5928 <entry><literal>FM</literal> prefix</entry>
5929 <entry>fill mode (suppress leading zeroes and padding blanks)</entry>
5930 <entry><literal>FMMonth</literal></entry>
5933 <entry><literal>TH</literal> suffix</entry>
5934 <entry>upper case ordinal number suffix</entry>
5935 <entry><literal>DDTH</literal>, e.g., <literal>12TH</></entry>
5938 <entry><literal>th</literal> suffix</entry>
5939 <entry>lower case ordinal number suffix</entry>
5940 <entry><literal>DDth</literal>, e.g., <literal>12th</></entry>
5943 <entry><literal>FX</literal> prefix</entry>
5944 <entry>fixed format global option (see usage notes)</entry>
5945 <entry><literal>FX Month DD Day</literal></entry>
5948 <entry><literal>TM</literal> prefix</entry>
5949 <entry>translation mode (print localized day and month names based on
5950 <xref linkend="guc-lc-time">)</entry>
5951 <entry><literal>TMMonth</literal></entry>
5954 <entry><literal>SP</literal> suffix</entry>
5955 <entry>spell mode (not implemented)</entry>
5956 <entry><literal>DDSP</literal></entry>
5963 Usage notes for date/time formatting:
5968 <literal>FM</literal> suppresses leading zeroes and trailing blanks
5969 that would otherwise be added to make the output of a pattern be
5970 fixed-width. In <productname>PostgreSQL</productname>,
5971 <literal>FM</literal> modifies only the next specification, while in
5972 Oracle <literal>FM</literal> affects all subsequent
5973 specifications, and repeated <literal>FM</literal> modifiers
5974 toggle fill mode on and off.
5980 <literal>TM</literal> does not include trailing blanks.
5981 <function>to_timestamp</> and <function>to_date</> ignore
5982 the <literal>TM</literal> modifier.
5988 <function>to_timestamp</function> and <function>to_date</function>
5989 skip multiple blank spaces in the input string unless the
5990 <literal>FX</literal> option is used. For example,
5991 <literal>to_timestamp('2000 JUN', 'YYYY MON')</literal> works, but
5992 <literal>to_timestamp('2000 JUN', 'FXYYYY MON')</literal> returns an error
5993 because <function>to_timestamp</function> expects one space only.
5994 <literal>FX</literal> must be specified as the first item in
6001 <function>to_timestamp</function> and <function>to_date</function>
6002 exist to handle input formats that cannot be converted by
6003 simple casting. These functions interpret input liberally,
6004 with minimal error checking. While they produce valid output,
6005 the conversion can yield unexpected results. For example,
6006 input to these functions is not restricted by normal ranges,
6007 thus <literal>to_date('20096040','YYYYMMDD')</literal> returns
6008 <literal>2014-01-17</literal> rather than causing an error.
6009 Casting does not have this behavior.
6015 Ordinary text is allowed in <function>to_char</function>
6016 templates and will be output literally. You can put a substring
6017 in double quotes to force it to be interpreted as literal text
6018 even if it contains pattern key words. For example, in
6019 <literal>'"Hello Year "YYYY'</literal>, the <literal>YYYY</literal>
6020 will be replaced by the year data, but the single <literal>Y</literal> in <literal>Year</literal>
6021 will not be. In <function>to_date</>, <function>to_number</>,
6022 and <function>to_timestamp</>, double-quoted strings skip the number of
6023 input characters contained in the string, e.g. <literal>"XX"</>
6024 skips two input characters.
6030 If you want to have a double quote in the output you must
6031 precede it with a backslash, for example <literal>'\"YYYY
6032 Month\"'</literal>. <!-- "" font-lock sanity :-) -->
6038 If the year format specification is less than four digits, e.g.
6039 <literal>YYY</>, and the supplied year is less than four digits,
6040 the year will be adjusted to be nearest to the year 2020, e.g.
6041 <literal>95</> becomes 1995.
6047 The <literal>YYYY</literal> conversion from string to <type>timestamp</type> or
6048 <type>date</type> has a restriction when processing years with more than 4 digits. You must
6049 use some non-digit character or template after <literal>YYYY</literal>,
6050 otherwise the year is always interpreted as 4 digits. For example
6051 (with the year 20000):
6052 <literal>to_date('200001131', 'YYYYMMDD')</literal> will be
6053 interpreted as a 4-digit year; instead use a non-digit
6054 separator after the year, like
6055 <literal>to_date('20000-1131', 'YYYY-MMDD')</literal> or
6056 <literal>to_date('20000Nov31', 'YYYYMonDD')</literal>.
6062 In conversions from string to <type>timestamp</type> or
6063 <type>date</type>, the <literal>CC</literal> (century) field is ignored
6064 if there is a <literal>YYY</literal>, <literal>YYYY</literal> or
6065 <literal>Y,YYY</literal> field. If <literal>CC</literal> is used with
6066 <literal>YY</literal> or <literal>Y</literal> then the year is computed
6067 as the year in the specified century. If the century is
6068 specified but the year is not, the first year of the century
6075 An ISO 8601 week-numbering date (as distinct from a Gregorian date)
6076 can be specified to <function>to_timestamp</function> and
6077 <function>to_date</function> in one of two ways:
6081 Year, week number, and weekday: for
6082 example <literal>to_date('2006-42-4', 'IYYY-IW-ID')</literal>
6083 returns the date <literal>2006-10-19</literal>.
6084 If you omit the weekday it is assumed to be 1 (Monday).
6089 Year and day of year: for example <literal>to_date('2006-291',
6090 'IYYY-IDDD')</literal> also returns <literal>2006-10-19</literal>.
6096 Attempting to enter a date using a mixture of ISO 8601 week-numbering
6097 fields and Gregorian date fields is nonsensical, and will cause an
6098 error. In the context of an ISO 8601 week-numbering year, the
6099 concept of a <quote>month</> or <quote>day of month</> has no
6100 meaning. In the context of a Gregorian year, the ISO week has no
6105 While <function>to_date</function> will reject a mixture of
6106 Gregorian and ISO week-numbering date
6107 fields, <function>to_char</function> will not, since output format
6108 specifications like <literal>YYYY-MM-DD (IYYY-IDDD)</> can be
6109 useful. But avoid writing something like <literal>IYYY-MM-DD</>;
6110 that would yield surprising results near the start of the year.
6111 (See <xref linkend="functions-datetime-extract"> for more
6119 In a conversion from string to <type>timestamp</type>, millisecond
6120 (<literal>MS</literal>) or microsecond (<literal>US</literal>)
6121 values are used as the
6122 seconds digits after the decimal point. For example
6123 <literal>to_timestamp('12:3', 'SS:MS')</literal> is not 3 milliseconds,
6124 but 300, because the conversion counts it as 12 + 0.3 seconds.
6125 This means for the format <literal>SS:MS</literal>, the input values
6126 <literal>12:3</literal>, <literal>12:30</literal>, and <literal>12:300</literal> specify the
6127 same number of milliseconds. To get three milliseconds, one must use
6128 <literal>12:003</literal>, which the conversion counts as
6129 12 + 0.003 = 12.003 seconds.
6135 <literal>to_timestamp('15:12:02.020.001230', 'HH:MI:SS.MS.US')</literal>
6136 is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds +
6137 1230 microseconds = 2.021230 seconds.
6143 <function>to_char(..., 'ID')</function>'s day of the week numbering
6144 matches the <function>extract(isodow from ...)</function> function, but
6145 <function>to_char(..., 'D')</function>'s does not match
6146 <function>extract(dow from ...)</function>'s day numbering.
6152 <function>to_char(interval)</function> formats <literal>HH</> and
6153 <literal>HH12</> as shown on a 12-hour clock, i.e. zero hours
6154 and 36 hours output as <literal>12</>, while <literal>HH24</>
6155 outputs the full hour value, which can exceed 23 for intervals.
6163 <xref linkend="functions-formatting-numeric-table"> shows the
6164 template patterns available for formatting numeric values.
6167 <table id="functions-formatting-numeric-table">
6168 <title>Template Patterns for Numeric Formatting</title>
6172 <entry>Pattern</entry>
6173 <entry>Description</entry>
6178 <entry><literal>9</literal></entry>
6179 <entry>value with the specified number of digits</entry>
6182 <entry><literal>0</literal></entry>
6183 <entry>value with leading zeros</entry>
6186 <entry><literal>.</literal> (period)</entry>
6187 <entry>decimal point</entry>
6190 <entry><literal>,</literal> (comma)</entry>
6191 <entry>group (thousand) separator</entry>
6194 <entry><literal>PR</literal></entry>
6195 <entry>negative value in angle brackets</entry>
6198 <entry><literal>S</literal></entry>
6199 <entry>sign anchored to number (uses locale)</entry>
6202 <entry><literal>L</literal></entry>
6203 <entry>currency symbol (uses locale)</entry>
6206 <entry><literal>D</literal></entry>
6207 <entry>decimal point (uses locale)</entry>
6210 <entry><literal>G</literal></entry>
6211 <entry>group separator (uses locale)</entry>
6214 <entry><literal>MI</literal></entry>
6215 <entry>minus sign in specified position (if number < 0)</entry>
6218 <entry><literal>PL</literal></entry>
6219 <entry>plus sign in specified position (if number > 0)</entry>
6222 <entry><literal>SG</literal></entry>
6223 <entry>plus/minus sign in specified position</entry>
6226 <entry><literal>RN</literal></entry>
6227 <entry>Roman numeral (input between 1 and 3999)</entry>
6230 <entry><literal>TH</literal> or <literal>th</literal></entry>
6231 <entry>ordinal number suffix</entry>
6234 <entry><literal>V</literal></entry>
6235 <entry>shift specified number of digits (see notes)</entry>
6238 <entry><literal>EEEE</literal></entry>
6239 <entry>exponent for scientific notation</entry>
6246 Usage notes for numeric formatting:
6251 A sign formatted using <literal>SG</literal>, <literal>PL</literal>, or
6252 <literal>MI</literal> is not anchored to
6253 the number; for example,
6254 <literal>to_char(-12, 'MI9999')</literal> produces <literal>'- 12'</literal>
6255 but <literal>to_char(-12, 'S9999')</literal> produces <literal>' -12'</literal>.
6256 The Oracle implementation does not allow the use of
6257 <literal>MI</literal> before <literal>9</literal>, but rather
6258 requires that <literal>9</literal> precede
6259 <literal>MI</literal>.
6265 <literal>9</literal> results in a value with the same number of
6266 digits as there are <literal>9</literal>s. If a digit is
6267 not available it outputs a space.
6273 <literal>TH</literal> does not convert values less than zero
6274 and does not convert fractional numbers.
6280 <literal>PL</literal>, <literal>SG</literal>, and
6281 <literal>TH</literal> are <productname>PostgreSQL</productname>
6288 <literal>V</literal> with <function>to_char</function>
6289 multiplies the input values by
6290 <literal>10^<replaceable>n</replaceable></literal>, where
6291 <replaceable>n</replaceable> is the number of digits following
6292 <literal>V</literal>. <literal>V</literal> with
6293 <function>to_number</function> divides in a similar manner.
6294 <function>to_char</function> and <function>to_number</function>
6295 do not support the use of
6296 <literal>V</literal> combined with a decimal point
6297 (e.g., <literal>99.9V99</literal> is not allowed).
6303 <literal>EEEE</literal> (scientific notation) cannot be used in
6304 combination with any of the other formatting patterns or
6305 modifiers other than digit and decimal point patterns, and must be at the end of the format string
6306 (e.g., <literal>9.99EEEE</literal> is a valid pattern).
6313 Certain modifiers can be applied to any template pattern to alter its
6314 behavior. For example, <literal>FM9999</literal>
6315 is the <literal>9999</literal> pattern with the
6316 <literal>FM</literal> modifier.
6317 <xref linkend="functions-formatting-numericmod-table"> shows the
6318 modifier patterns for numeric formatting.
6321 <table id="functions-formatting-numericmod-table">
6322 <title>Template Pattern Modifiers for Numeric Formatting</title>
6326 <entry>Modifier</entry>
6327 <entry>Description</entry>
6328 <entry>Example</entry>
6333 <entry><literal>FM</literal> prefix</entry>
6334 <entry>fill mode (suppress leading zeroes and padding blanks)</entry>
6335 <entry><literal>FM9999</literal></entry>
6338 <entry><literal>TH</literal> suffix</entry>
6339 <entry>upper case ordinal number suffix</entry>
6340 <entry><literal>999TH</literal></entry>
6343 <entry><literal>th</literal> suffix</entry>
6344 <entry>lower case ordinal number suffix</entry>
6345 <entry><literal>999th</literal></entry>
6352 <xref linkend="functions-formatting-examples-table"> shows some
6353 examples of the use of the <function>to_char</function> function.
6356 <table id="functions-formatting-examples-table">
6357 <title><function>to_char</function> Examples</title>
6361 <entry>Expression</entry>
6362 <entry>Result</entry>
6367 <entry><literal>to_char(current_timestamp, 'Day, DD HH12:MI:SS')</literal></entry>
6368 <entry><literal>'Tuesday , 06 05:39:18'</literal></entry>
6371 <entry><literal>to_char(current_timestamp, 'FMDay, FMDD HH12:MI:SS')</literal></entry>
6372 <entry><literal>'Tuesday, 6 05:39:18'</literal></entry>
6375 <entry><literal>to_char(-0.1, '99.99')</literal></entry>
6376 <entry><literal>' -.10'</literal></entry>
6379 <entry><literal>to_char(-0.1, 'FM9.99')</literal></entry>
6380 <entry><literal>'-.1'</literal></entry>
6383 <entry><literal>to_char(0.1, '0.9')</literal></entry>
6384 <entry><literal>' 0.1'</literal></entry>
6387 <entry><literal>to_char(12, '9990999.9')</literal></entry>
6388 <entry><literal>' 0012.0'</literal></entry>
6391 <entry><literal>to_char(12, 'FM9990999.9')</literal></entry>
6392 <entry><literal>'0012.'</literal></entry>
6395 <entry><literal>to_char(485, '999')</literal></entry>
6396 <entry><literal>' 485'</literal></entry>
6399 <entry><literal>to_char(-485, '999')</literal></entry>
6400 <entry><literal>'-485'</literal></entry>
6403 <entry><literal>to_char(485, '9 9 9')</literal></entry>
6404 <entry><literal>' 4 8 5'</literal></entry>
6407 <entry><literal>to_char(1485, '9,999')</literal></entry>
6408 <entry><literal>' 1,485'</literal></entry>
6411 <entry><literal>to_char(1485, '9G999')</literal></entry>
6412 <entry><literal>' 1 485'</literal></entry>
6415 <entry><literal>to_char(148.5, '999.999')</literal></entry>
6416 <entry><literal>' 148.500'</literal></entry>
6419 <entry><literal>to_char(148.5, 'FM999.999')</literal></entry>
6420 <entry><literal>'148.5'</literal></entry>
6423 <entry><literal>to_char(148.5, 'FM999.990')</literal></entry>
6424 <entry><literal>'148.500'</literal></entry>
6427 <entry><literal>to_char(148.5, '999D999')</literal></entry>
6428 <entry><literal>' 148,500'</literal></entry>
6431 <entry><literal>to_char(3148.5, '9G999D999')</literal></entry>
6432 <entry><literal>' 3 148,500'</literal></entry>
6435 <entry><literal>to_char(-485, '999S')</literal></entry>
6436 <entry><literal>'485-'</literal></entry>
6439 <entry><literal>to_char(-485, '999MI')</literal></entry>
6440 <entry><literal>'485-'</literal></entry>
6443 <entry><literal>to_char(485, '999MI')</literal></entry>
6444 <entry><literal>'485 '</literal></entry>
6447 <entry><literal>to_char(485, 'FM999MI')</literal></entry>
6448 <entry><literal>'485'</literal></entry>
6451 <entry><literal>to_char(485, 'PL999')</literal></entry>
6452 <entry><literal>'+485'</literal></entry>
6455 <entry><literal>to_char(485, 'SG999')</literal></entry>
6456 <entry><literal>'+485'</literal></entry>
6459 <entry><literal>to_char(-485, 'SG999')</literal></entry>
6460 <entry><literal>'-485'</literal></entry>
6463 <entry><literal>to_char(-485, '9SG99')</literal></entry>
6464 <entry><literal>'4-85'</literal></entry>
6467 <entry><literal>to_char(-485, '999PR')</literal></entry>
6468 <entry><literal>'<485>'</literal></entry>
6471 <entry><literal>to_char(485, 'L999')</literal></entry>
6472 <entry><literal>'DM 485'</literal></entry>
6475 <entry><literal>to_char(485, 'RN')</literal></entry>
6476 <entry><literal>' CDLXXXV'</literal></entry>
6479 <entry><literal>to_char(485, 'FMRN')</literal></entry>
6480 <entry><literal>'CDLXXXV'</literal></entry>
6483 <entry><literal>to_char(5.2, 'FMRN')</literal></entry>
6484 <entry><literal>'V'</literal></entry>
6487 <entry><literal>to_char(482, '999th')</literal></entry>
6488 <entry><literal>' 482nd'</literal></entry>
6491 <entry><literal>to_char(485, '"Good number:"999')</literal></entry>
6492 <entry><literal>'Good number: 485'</literal></entry>
6495 <entry><literal>to_char(485.8, '"Pre:"999" Post:" .999')</literal></entry>
6496 <entry><literal>'Pre: 485 Post: .800'</literal></entry>
6499 <entry><literal>to_char(12, '99V999')</literal></entry>
6500 <entry><literal>' 12000'</literal></entry>
6503 <entry><literal>to_char(12.4, '99V999')</literal></entry>
6504 <entry><literal>' 12400'</literal></entry>
6507 <entry><literal>to_char(12.45, '99V9')</literal></entry>
6508 <entry><literal>' 125'</literal></entry>
6511 <entry><literal>to_char(0.0004859, '9.99EEEE')</literal></entry>
6512 <entry><literal>' 4.86e-04'</literal></entry>
6521 <sect1 id="functions-datetime">
6522 <title>Date/Time Functions and Operators</title>
6525 <xref linkend="functions-datetime-table"> shows the available
6526 functions for date/time value processing, with details appearing in
6527 the following subsections. <xref
6528 linkend="operators-datetime-table"> illustrates the behaviors of
6529 the basic arithmetic operators (<literal>+</literal>,
6530 <literal>*</literal>, etc.). For formatting functions, refer to
6531 <xref linkend="functions-formatting">. You should be familiar with
6532 the background information on date/time data types from <xref
6533 linkend="datatype-datetime">.
6537 All the functions and operators described below that take <type>time</type> or <type>timestamp</type>
6538 inputs actually come in two variants: one that takes <type>time with time zone</type> or <type>timestamp
6539 with time zone</type>, and one that takes <type>time without time zone</type> or <type>timestamp without time zone</type>.
6540 For brevity, these variants are not shown separately. Also, the
6541 <literal>+</> and <literal>*</> operators come in commutative pairs (for
6542 example both date + integer and integer + date); we show only one of each
6546 <table id="operators-datetime-table">
6547 <title>Date/Time Operators</title>
6552 <entry>Operator</entry>
6553 <entry>Example</entry>
6554 <entry>Result</entry>
6560 <entry> <literal>+</literal> </entry>
6561 <entry><literal>date '2001-09-28' + integer '7'</literal></entry>
6562 <entry><literal>date '2001-10-05'</literal></entry>
6566 <entry> <literal>+</literal> </entry>
6567 <entry><literal>date '2001-09-28' + interval '1 hour'</literal></entry>
6568 <entry><literal>timestamp '2001-09-28 01:00:00'</literal></entry>
6572 <entry> <literal>+</literal> </entry>
6573 <entry><literal>date '2001-09-28' + time '03:00'</literal></entry>
6574 <entry><literal>timestamp '2001-09-28 03:00:00'</literal></entry>
6578 <entry> <literal>+</literal> </entry>
6579 <entry><literal>interval '1 day' + interval '1 hour'</literal></entry>
6580 <entry><literal>interval '1 day 01:00:00'</literal></entry>
6584 <entry> <literal>+</literal> </entry>
6585 <entry><literal>timestamp '2001-09-28 01:00' + interval '23 hours'</literal></entry>
6586 <entry><literal>timestamp '2001-09-29 00:00:00'</literal></entry>
6590 <entry> <literal>+</literal> </entry>
6591 <entry><literal>time '01:00' + interval '3 hours'</literal></entry>
6592 <entry><literal>time '04:00:00'</literal></entry>
6596 <entry> <literal>-</literal> </entry>
6597 <entry><literal>- interval '23 hours'</literal></entry>
6598 <entry><literal>interval '-23:00:00'</literal></entry>
6602 <entry> <literal>-</literal> </entry>
6603 <entry><literal>date '2001-10-01' - date '2001-09-28'</literal></entry>
6604 <entry><literal>integer '3'</literal> (days)</entry>
6608 <entry> <literal>-</literal> </entry>
6609 <entry><literal>date '2001-10-01' - integer '7'</literal></entry>
6610 <entry><literal>date '2001-09-24'</literal></entry>
6614 <entry> <literal>-</literal> </entry>
6615 <entry><literal>date '2001-09-28' - interval '1 hour'</literal></entry>
6616 <entry><literal>timestamp '2001-09-27 23:00:00'</literal></entry>
6620 <entry> <literal>-</literal> </entry>
6621 <entry><literal>time '05:00' - time '03:00'</literal></entry>
6622 <entry><literal>interval '02:00:00'</literal></entry>
6626 <entry> <literal>-</literal> </entry>
6627 <entry><literal>time '05:00' - interval '2 hours'</literal></entry>
6628 <entry><literal>time '03:00:00'</literal></entry>
6632 <entry> <literal>-</literal> </entry>
6633 <entry><literal>timestamp '2001-09-28 23:00' - interval '23 hours'</literal></entry>
6634 <entry><literal>timestamp '2001-09-28 00:00:00'</literal></entry>
6638 <entry> <literal>-</literal> </entry>
6639 <entry><literal>interval '1 day' - interval '1 hour'</literal></entry>
6640 <entry><literal>interval '1 day -01:00:00'</literal></entry>
6644 <entry> <literal>-</literal> </entry>
6645 <entry><literal>timestamp '2001-09-29 03:00' - timestamp '2001-09-27 12:00'</literal></entry>
6646 <entry><literal>interval '1 day 15:00:00'</literal></entry>
6650 <entry> <literal>*</literal> </entry>
6651 <entry><literal>900 * interval '1 second'</literal></entry>
6652 <entry><literal>interval '00:15:00'</literal></entry>
6656 <entry> <literal>*</literal> </entry>
6657 <entry><literal>21 * interval '1 day'</literal></entry>
6658 <entry><literal>interval '21 days'</literal></entry>
6662 <entry> <literal>*</literal> </entry>
6663 <entry><literal>double precision '3.5' * interval '1 hour'</literal></entry>
6664 <entry><literal>interval '03:30:00'</literal></entry>
6668 <entry> <literal>/</literal> </entry>
6669 <entry><literal>interval '1 hour' / double precision '1.5'</literal></entry>
6670 <entry><literal>interval '00:40:00'</literal></entry>
6676 <table id="functions-datetime-table">
6677 <title>Date/Time Functions</title>
6681 <entry>Function</entry>
6682 <entry>Return Type</entry>
6683 <entry>Description</entry>
6684 <entry>Example</entry>
6685 <entry>Result</entry>
6693 <primary>age</primary>
6695 <literal><function>age(<type>timestamp</type>, <type>timestamp</type>)</function></literal>
6697 <entry><type>interval</type></entry>
6698 <entry>Subtract arguments, producing a <quote>symbolic</> result that
6699 uses years and months, rather than just days</entry>
6700 <entry><literal>age(timestamp '2001-04-10', timestamp '1957-06-13')</literal></entry>
6701 <entry><literal>43 years 9 mons 27 days</literal></entry>
6705 <entry><literal><function>age(<type>timestamp</type>)</function></literal></entry>
6706 <entry><type>interval</type></entry>
6707 <entry>Subtract from <function>current_date</function> (at midnight)</entry>
6708 <entry><literal>age(timestamp '1957-06-13')</literal></entry>
6709 <entry><literal>43 years 8 mons 3 days</literal></entry>
6715 <primary>clock_timestamp</primary>
6717 <literal><function>clock_timestamp()</function></literal>
6719 <entry><type>timestamp with time zone</type></entry>
6720 <entry>Current date and time (changes during statement execution);
6721 see <xref linkend="functions-datetime-current">
6730 <primary>current_date</primary>
6732 <literal><function>current_date</function></literal>
6734 <entry><type>date</type></entry>
6735 <entry>Current date;
6736 see <xref linkend="functions-datetime-current">
6745 <primary>current_time</primary>
6747 <literal><function>current_time</function></literal>
6749 <entry><type>time with time zone</type></entry>
6750 <entry>Current time of day;
6751 see <xref linkend="functions-datetime-current">
6760 <primary>current_timestamp</primary>
6762 <literal><function>current_timestamp</function></literal>
6764 <entry><type>timestamp with time zone</type></entry>
6765 <entry>Current date and time (start of current transaction);
6766 see <xref linkend="functions-datetime-current">
6775 <primary>date_part</primary>
6777 <literal><function>date_part(<type>text</type>, <type>timestamp</type>)</function></literal>
6779 <entry><type>double precision</type></entry>
6780 <entry>Get subfield (equivalent to <function>extract</function>);
6781 see <xref linkend="functions-datetime-extract">
6783 <entry><literal>date_part('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
6784 <entry><literal>20</literal></entry>
6788 <entry><literal><function>date_part(<type>text</type>, <type>interval</type>)</function></literal></entry>
6789 <entry><type>double precision</type></entry>
6790 <entry>Get subfield (equivalent to
6791 <function>extract</function>); see <xref linkend="functions-datetime-extract">
6793 <entry><literal>date_part('month', interval '2 years 3 months')</literal></entry>
6794 <entry><literal>3</literal></entry>
6800 <primary>date_trunc</primary>
6802 <literal><function>date_trunc(<type>text</type>, <type>timestamp</type>)</function></literal>
6804 <entry><type>timestamp</type></entry>
6805 <entry>Truncate to specified precision; see also <xref linkend="functions-datetime-trunc">
6807 <entry><literal>date_trunc('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
6808 <entry><literal>2001-02-16 20:00:00</literal></entry>
6812 <entry><literal><function>date_trunc(<type>text</type>, <type>interval</type>)</function></literal></entry>
6813 <entry><type>interval</type></entry>
6814 <entry>Truncate to specified precision; see also <xref linkend="functions-datetime-trunc">
6816 <entry><literal>date_trunc('hour', interval '2 days 3 hours 40 minutes')</literal></entry>
6817 <entry><literal>2 days 03:00:00</literal></entry>
6823 <primary>extract</primary>
6825 <literal><function>extract</function>(<parameter>field</parameter> from
6826 <type>timestamp</type>)</literal>
6828 <entry><type>double precision</type></entry>
6829 <entry>Get subfield; see <xref linkend="functions-datetime-extract">
6831 <entry><literal>extract(hour from timestamp '2001-02-16 20:38:40')</literal></entry>
6832 <entry><literal>20</literal></entry>
6836 <entry><literal><function>extract</function>(<parameter>field</parameter> from
6837 <type>interval</type>)</literal></entry>
6838 <entry><type>double precision</type></entry>
6839 <entry>Get subfield; see <xref linkend="functions-datetime-extract">
6841 <entry><literal>extract(month from interval '2 years 3 months')</literal></entry>
6842 <entry><literal>3</literal></entry>
6848 <primary>isfinite</primary>
6850 <literal><function>isfinite(<type>date</type>)</function></literal>
6852 <entry><type>boolean</type></entry>
6853 <entry>Test for finite date (not +/-infinity)</entry>
6854 <entry><literal>isfinite(date '2001-02-16')</literal></entry>
6855 <entry><literal>true</literal></entry>
6859 <entry><literal><function>isfinite(<type>timestamp</type>)</function></literal></entry>
6860 <entry><type>boolean</type></entry>
6861 <entry>Test for finite time stamp (not +/-infinity)</entry>
6862 <entry><literal>isfinite(timestamp '2001-02-16 21:28:30')</literal></entry>
6863 <entry><literal>true</literal></entry>
6867 <entry><literal><function>isfinite(<type>interval</type>)</function></literal></entry>
6868 <entry><type>boolean</type></entry>
6869 <entry>Test for finite interval</entry>
6870 <entry><literal>isfinite(interval '4 hours')</literal></entry>
6871 <entry><literal>true</literal></entry>
6877 <primary>justify_days</primary>
6879 <literal><function>justify_days(<type>interval</type>)</function></literal>
6881 <entry><type>interval</type></entry>
6882 <entry>Adjust interval so 30-day time periods are represented as months</entry>
6883 <entry><literal>justify_days(interval '35 days')</literal></entry>
6884 <entry><literal>1 mon 5 days</literal></entry>
6890 <primary>justify_hours</primary>
6892 <literal><function>justify_hours(<type>interval</type>)</function></literal>
6894 <entry><type>interval</type></entry>
6895 <entry>Adjust interval so 24-hour time periods are represented as days</entry>
6896 <entry><literal>justify_hours(interval '27 hours')</literal></entry>
6897 <entry><literal>1 day 03:00:00</literal></entry>
6903 <primary>justify_interval</primary>
6905 <literal><function>justify_interval(<type>interval</type>)</function></literal>
6907 <entry><type>interval</type></entry>
6908 <entry>Adjust interval using <function>justify_days</> and <function>justify_hours</>, with additional sign adjustments</entry>
6909 <entry><literal>justify_interval(interval '1 mon -1 hour')</literal></entry>
6910 <entry><literal>29 days 23:00:00</literal></entry>
6916 <primary>localtime</primary>
6918 <literal><function>localtime</function></literal>
6920 <entry><type>time</type></entry>
6921 <entry>Current time of day;
6922 see <xref linkend="functions-datetime-current">
6931 <primary>localtimestamp</primary>
6933 <literal><function>localtimestamp</function></literal>
6935 <entry><type>timestamp</type></entry>
6936 <entry>Current date and time (start of current transaction);
6937 see <xref linkend="functions-datetime-current">
6946 <primary>make_date</primary>
6950 make_date(<parameter>year</parameter> <type>int</type>,
6951 <parameter>month</parameter> <type>int</type>,
6952 <parameter>day</parameter> <type>int</type>)
6956 <entry><type>date</type></entry>
6958 Create date from year, month and day fields
6960 <entry><literal>make_date(2013, 7, 15)</literal></entry>
6961 <entry><literal>2013-07-15</literal></entry>
6967 <primary>make_interval</primary>
6971 make_interval(<parameter>years</parameter> <type>int</type> DEFAULT 0,
6972 <parameter>months</parameter> <type>int</type> DEFAULT 0,
6973 <parameter>weeks</parameter> <type>int</type> DEFAULT 0,
6974 <parameter>days</parameter> <type>int</type> DEFAULT 0,
6975 <parameter>hours</parameter> <type>int</type> DEFAULT 0,
6976 <parameter>mins</parameter> <type>int</type> DEFAULT 0,
6977 <parameter>secs</parameter> <type>double precision</type> DEFAULT 0.0)
6981 <entry><type>interval</type></entry>
6983 Create interval from years, months, weeks, days, hours, minutes and
6986 <entry><literal>make_interval(days => 10)</literal></entry>
6987 <entry><literal>10 days</literal></entry>
6993 <primary>make_time</primary>
6997 make_time(<parameter>hour</parameter> <type>int</type>,
6998 <parameter>min</parameter> <type>int</type>,
6999 <parameter>sec</parameter> <type>double precision</type>)
7003 <entry><type>time</type></entry>
7005 Create time from hour, minute and seconds fields
7007 <entry><literal>make_time(8, 15, 23.5)</literal></entry>
7008 <entry><literal>08:15:23.5</literal></entry>
7014 <primary>make_timestamp</primary>
7018 make_timestamp(<parameter>year</parameter> <type>int</type>,
7019 <parameter>month</parameter> <type>int</type>,
7020 <parameter>day</parameter> <type>int</type>,
7021 <parameter>hour</parameter> <type>int</type>,
7022 <parameter>min</parameter> <type>int</type>,
7023 <parameter>sec</parameter> <type>double precision</type>)
7027 <entry><type>timestamp</type></entry>
7029 Create timestamp from year, month, day, hour, minute and seconds fields
7031 <entry><literal>make_timestamp(2013, 7, 15, 8, 15, 23.5)</literal></entry>
7032 <entry><literal>2013-07-15 08:15:23.5</literal></entry>
7038 <primary>make_timestamptz</primary>
7042 make_timestamptz(<parameter>year</parameter> <type>int</type>,
7043 <parameter>month</parameter> <type>int</type>,
7044 <parameter>day</parameter> <type>int</type>,
7045 <parameter>hour</parameter> <type>int</type>,
7046 <parameter>min</parameter> <type>int</type>,
7047 <parameter>sec</parameter> <type>double precision</type>,
7048 <optional> <parameter>timezone</parameter> <type>text</type> </optional>)
7052 <entry><type>timestamp with time zone</type></entry>
7054 Create timestamp with time zone from year, month, day, hour, minute
7055 and seconds fields; if <parameter>timezone</parameter> is not
7056 specified, the current time zone is used
7058 <entry><literal>make_timestamptz(2013, 7, 15, 8, 15, 23.5)</literal></entry>
7059 <entry><literal>2013-07-15 08:15:23.5+01</literal></entry>
7065 <primary>now</primary>
7067 <literal><function>now()</function></literal>
7069 <entry><type>timestamp with time zone</type></entry>
7070 <entry>Current date and time (start of current transaction);
7071 see <xref linkend="functions-datetime-current">
7080 <primary>statement_timestamp</primary>
7082 <literal><function>statement_timestamp()</function></literal>
7084 <entry><type>timestamp with time zone</type></entry>
7085 <entry>Current date and time (start of current statement);
7086 see <xref linkend="functions-datetime-current">
7095 <primary>timeofday</primary>
7097 <literal><function>timeofday()</function></literal>
7099 <entry><type>text</type></entry>
7100 <entry>Current date and time
7101 (like <function>clock_timestamp</>, but as a <type>text</> string);
7102 see <xref linkend="functions-datetime-current">
7111 <primary>transaction_timestamp</primary>
7113 <literal><function>transaction_timestamp()</function></literal>
7115 <entry><type>timestamp with time zone</type></entry>
7116 <entry>Current date and time (start of current transaction);
7117 see <xref linkend="functions-datetime-current">
7125 <primary>to_timestamp</primary>
7127 <literal><function>to_timestamp(<type>double precision</type>)</function></literal>
7129 <entry><type>timestamp with time zone</type></entry>
7130 <entry>Convert Unix epoch (seconds since 1970-01-01 00:00:00+00) to
7132 <entry><literal>to_timestamp(1284352323)</literal></entry>
7133 <entry><literal>2010-09-13 04:32:03+00</literal></entry>
7141 <primary>OVERLAPS</primary>
7143 In addition to these functions, the SQL <literal>OVERLAPS</> operator is
7146 (<replaceable>start1</replaceable>, <replaceable>end1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>end2</replaceable>)
7147 (<replaceable>start1</replaceable>, <replaceable>length1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>length2</replaceable>)
7149 This expression yields true when two time periods (defined by their
7150 endpoints) overlap, false when they do not overlap. The endpoints
7151 can be specified as pairs of dates, times, or time stamps; or as
7152 a date, time, or time stamp followed by an interval. When a pair
7153 of values is provided, either the start or the end can be written
7154 first; <literal>OVERLAPS</> automatically takes the earlier value
7155 of the pair as the start. Each time period is considered to
7156 represent the half-open interval <replaceable>start</> <literal><=</>
7157 <replaceable>time</> <literal><</> <replaceable>end</>, unless
7158 <replaceable>start</> and <replaceable>end</> are equal in which case it
7159 represents that single time instant. This means for instance that two
7160 time periods with only an endpoint in common do not overlap.
7164 SELECT (DATE '2001-02-16', DATE '2001-12-21') OVERLAPS
7165 (DATE '2001-10-30', DATE '2002-10-30');
7166 <lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
7167 SELECT (DATE '2001-02-16', INTERVAL '100 days') OVERLAPS
7168 (DATE '2001-10-30', DATE '2002-10-30');
7169 <lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
7170 SELECT (DATE '2001-10-29', DATE '2001-10-30') OVERLAPS
7171 (DATE '2001-10-30', DATE '2001-10-31');
7172 <lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
7173 SELECT (DATE '2001-10-30', DATE '2001-10-30') OVERLAPS
7174 (DATE '2001-10-30', DATE '2001-10-31');
7175 <lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
7179 When adding an <type>interval</type> value to (or subtracting an
7180 <type>interval</type> value from) a <type>timestamp with time zone</type>
7181 value, the days component advances or decrements the date of the
7182 <type>timestamp with time zone</type> by the indicated number of days.
7183 Across daylight saving time changes (when the session time zone is set to a
7184 time zone that recognizes DST), this means <literal>interval '1 day'</literal>
7185 does not necessarily equal <literal>interval '24 hours'</literal>.
7186 For example, with the session time zone set to <literal>CST7CDT</literal>,
7187 <literal>timestamp with time zone '2005-04-02 12:00-07' + interval '1 day'</literal>
7188 will produce <literal>timestamp with time zone '2005-04-03 12:00-06'</literal>,
7189 while adding <literal>interval '24 hours'</literal> to the same initial
7190 <type>timestamp with time zone</type> produces
7191 <literal>timestamp with time zone '2005-04-03 13:00-06'</literal>, as there is
7192 a change in daylight saving time at <literal>2005-04-03 02:00</literal> in time zone
7193 <literal>CST7CDT</literal>.
7197 Note there can be ambiguity in the <literal>months</> field returned by
7198 <function>age</> because different months have different numbers of
7199 days. <productname>PostgreSQL</>'s approach uses the month from the
7200 earlier of the two dates when calculating partial months. For example,
7201 <literal>age('2004-06-01', '2004-04-30')</> uses April to yield
7202 <literal>1 mon 1 day</>, while using May would yield <literal>1 mon 2
7203 days</> because May has 31 days, while April has only 30.
7207 Subtraction of dates and timestamps can also be complex. One conceptually
7208 simple way to perform subtraction is to convert each value to a number
7209 of seconds using <literal>EXTRACT(EPOCH FROM ...)</>, then subtract the
7210 results; this produces the
7211 number of <emphasis>seconds</> between the two values. This will adjust
7212 for the number of days in each month, timezone changes, and daylight
7213 saving time adjustments. Subtraction of date or timestamp
7214 values with the <quote><literal>-</></quote> operator
7215 returns the number of days (24-hours) and hours/minutes/seconds
7216 between the values, making the same adjustments. The <function>age</>
7217 function returns years, months, days, and hours/minutes/seconds,
7218 performing field-by-field subtraction and then adjusting for negative
7219 field values. The following queries illustrate the differences in these
7220 approaches. The sample results were produced with <literal>timezone
7221 = 'US/Eastern'</>; there is a daylight saving time change between the
7226 SELECT EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
7227 EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00');
7228 <lineannotation>Result: </lineannotation><computeroutput>10537200</computeroutput>
7229 SELECT (EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
7230 EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00'))
7232 <lineannotation>Result: </lineannotation><computeroutput>121.958333333333</computeroutput>
7233 SELECT timestamptz '2013-07-01 12:00:00' - timestamptz '2013-03-01 12:00:00';
7234 <lineannotation>Result: </lineannotation><computeroutput>121 days 23:00:00</computeroutput>
7235 SELECT age(timestamptz '2013-07-01 12:00:00', timestamptz '2013-03-01 12:00:00');
7236 <lineannotation>Result: </lineannotation><computeroutput>4 mons</computeroutput>
7239 <sect2 id="functions-datetime-extract">
7240 <title><function>EXTRACT</function>, <function>date_part</function></title>
7243 <primary>date_part</primary>
7246 <primary>extract</primary>
7250 EXTRACT(<replaceable>field</replaceable> FROM <replaceable>source</replaceable>)
7254 The <function>extract</function> function retrieves subfields
7255 such as year or hour from date/time values.
7256 <replaceable>source</replaceable> must be a value expression of
7257 type <type>timestamp</type>, <type>time</type>, or <type>interval</type>.
7258 (Expressions of type <type>date</type> are
7259 cast to <type>timestamp</type> and can therefore be used as
7260 well.) <replaceable>field</replaceable> is an identifier or
7261 string that selects what field to extract from the source value.
7262 The <function>extract</function> function returns values of type
7263 <type>double precision</type>.
7264 The following are valid field names:
7266 <!-- alphabetical -->
7269 <term><literal>century</literal></term>
7276 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');
7277 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
7278 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
7279 <lineannotation>Result: </lineannotation><computeroutput>21</computeroutput>
7283 The first century starts at 0001-01-01 00:00:00 AD, although
7284 they did not know it at the time. This definition applies to all
7285 Gregorian calendar countries. There is no century number 0,
7286 you go from -1 century to 1 century.
7288 If you disagree with this, please write your complaint to:
7289 Pope, Cathedral Saint-Peter of Roma, Vatican.
7295 <term><literal>day</literal></term>
7298 For <type>timestamp</type> values, the day (of the month) field
7299 (1 - 31) ; for <type>interval</type> values, the number of days
7303 SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
7304 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
7306 SELECT EXTRACT(DAY FROM INTERVAL '40 days 1 minute');
7307 <lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
7316 <term><literal>decade</literal></term>
7319 The year field divided by 10
7323 SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
7324 <lineannotation>Result: </lineannotation><computeroutput>200</computeroutput>
7330 <term><literal>dow</literal></term>
7333 The day of the week as Sunday (<literal>0</>) to
7334 Saturday (<literal>6</>)
7338 SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
7339 <lineannotation>Result: </lineannotation><computeroutput>5</computeroutput>
7342 Note that <function>extract</function>'s day of the week numbering
7343 differs from that of the <function>to_char(...,
7344 'D')</function> function.
7351 <term><literal>doy</literal></term>
7354 The day of the year (1 - 365/366)
7358 SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
7359 <lineannotation>Result: </lineannotation><computeroutput>47</computeroutput>
7365 <term><literal>epoch</literal></term>
7368 For <type>timestamp with time zone</type> values, the
7369 number of seconds since 1970-01-01 00:00:00 UTC (can be negative);
7370 for <type>date</type> and <type>timestamp</type> values, the
7371 number of seconds since 1970-01-01 00:00:00 local time;
7372 for <type>interval</type> values, the total number
7373 of seconds in the interval
7377 SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');
7378 <lineannotation>Result: </lineannotation><computeroutput>982384720.12</computeroutput>
7380 SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
7381 <lineannotation>Result: </lineannotation><computeroutput>442800</computeroutput>
7385 You can convert an epoch value back to a time stamp
7386 with <function>to_timestamp</>:
7389 SELECT to_timestamp(982384720.12);
7390 <lineannotation>Result: </lineannotation><computeroutput>2001-02-17 04:38:40.12+00</computeroutput>
7396 <term><literal>hour</literal></term>
7399 The hour field (0 - 23)
7403 SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
7404 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
7410 <term><literal>isodow</literal></term>
7413 The day of the week as Monday (<literal>1</>) to
7414 Sunday (<literal>7</>)
7418 SELECT EXTRACT(ISODOW FROM TIMESTAMP '2001-02-18 20:38:40');
7419 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
7422 This is identical to <literal>dow</> except for Sunday. This
7423 matches the <acronym>ISO</> 8601 day of the week numbering.
7430 <term><literal>isoyear</literal></term>
7433 The <acronym>ISO</acronym> 8601 week-numbering year that the date
7434 falls in (not applicable to intervals)
7438 SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-01');
7439 <lineannotation>Result: </lineannotation><computeroutput>2005</computeroutput>
7440 SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-02');
7441 <lineannotation>Result: </lineannotation><computeroutput>2006</computeroutput>
7445 Each <acronym>ISO</acronym> 8601 week-numbering year begins with the
7446 Monday of the week containing the 4th of January, so in early
7447 January or late December the <acronym>ISO</acronym> year may be
7448 different from the Gregorian year. See the <literal>week</literal>
7449 field for more information.
7452 This field is not available in PostgreSQL releases prior to 8.3.
7458 <term><literal>microseconds</literal></term>
7461 The seconds field, including fractional parts, multiplied by 1
7462 000 000; note that this includes full seconds
7466 SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
7467 <lineannotation>Result: </lineannotation><computeroutput>28500000</computeroutput>
7473 <term><literal>millennium</literal></term>
7480 SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
7481 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
7485 Years in the 1900s are in the second millennium.
7486 The third millennium started January 1, 2001.
7492 <term><literal>milliseconds</literal></term>
7495 The seconds field, including fractional parts, multiplied by
7496 1000. Note that this includes full seconds.
7500 SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
7501 <lineannotation>Result: </lineannotation><computeroutput>28500</computeroutput>
7507 <term><literal>minute</literal></term>
7510 The minutes field (0 - 59)
7514 SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
7515 <lineannotation>Result: </lineannotation><computeroutput>38</computeroutput>
7521 <term><literal>month</literal></term>
7524 For <type>timestamp</type> values, the number of the month
7525 within the year (1 - 12) ; for <type>interval</type> values,
7526 the number of months, modulo 12 (0 - 11)
7530 SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
7531 <lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
7533 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
7534 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
7536 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
7537 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
7543 <term><literal>quarter</literal></term>
7546 The quarter of the year (1 - 4) that the date is in
7550 SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
7551 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
7557 <term><literal>second</literal></term>
7560 The seconds field, including fractional parts (0 -
7561 59<footnote><simpara>60 if leap seconds are
7562 implemented by the operating system</simpara></footnote>)
7566 SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
7567 <lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
7569 SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
7570 <lineannotation>Result: </lineannotation><computeroutput>28.5</computeroutput>
7575 <term><literal>timezone</literal></term>
7578 The time zone offset from UTC, measured in seconds. Positive values
7579 correspond to time zones east of UTC, negative values to
7580 zones west of UTC. (Technically,
7581 <productname>PostgreSQL</productname> uses <acronym>UT1</> because
7582 leap seconds are not handled.)
7588 <term><literal>timezone_hour</literal></term>
7591 The hour component of the time zone offset
7597 <term><literal>timezone_minute</literal></term>
7600 The minute component of the time zone offset
7606 <term><literal>week</literal></term>
7609 The number of the <acronym>ISO</acronym> 8601 week-numbering week of
7610 the year. By definition, ISO weeks start on Mondays and the first
7611 week of a year contains January 4 of that year. In other words, the
7612 first Thursday of a year is in week 1 of that year.
7615 In the ISO week-numbering system, it is possible for early-January
7616 dates to be part of the 52nd or 53rd week of the previous year, and for
7617 late-December dates to be part of the first week of the next year.
7618 For example, <literal>2005-01-01</> is part of the 53rd week of year
7619 2004, and <literal>2006-01-01</> is part of the 52nd week of year
7620 2005, while <literal>2012-12-31</> is part of the first week of 2013.
7621 It's recommended to use the <literal>isoyear</> field together with
7622 <literal>week</> to get consistent results.
7626 SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
7627 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
7633 <term><literal>year</literal></term>
7636 The year field. Keep in mind there is no <literal>0 AD</>, so subtracting
7637 <literal>BC</> years from <literal>AD</> years should be done with care.
7641 SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
7642 <lineannotation>Result: </lineannotation><computeroutput>2001</computeroutput>
7652 When the input value is +/-Infinity, <function>extract</> returns
7653 +/-Infinity for monotonically-increasing fields (<literal>epoch</>,
7654 <literal>julian</>, <literal>year</>, <literal>isoyear</>,
7655 <literal>decade</>, <literal>century</>, and <literal>millennium</>).
7656 For other fields, NULL is returned. <productname>PostgreSQL</>
7657 versions before 9.6 returned zero for all cases of infinite input.
7662 The <function>extract</function> function is primarily intended
7663 for computational processing. For formatting date/time values for
7664 display, see <xref linkend="functions-formatting">.
7668 The <function>date_part</function> function is modeled on the traditional
7669 <productname>Ingres</productname> equivalent to the
7670 <acronym>SQL</acronym>-standard function <function>extract</function>:
7672 date_part('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
7674 Note that here the <replaceable>field</replaceable> parameter needs to
7675 be a string value, not a name. The valid field names for
7676 <function>date_part</function> are the same as for
7677 <function>extract</function>.
7681 SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
7682 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
7684 SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
7685 <lineannotation>Result: </lineannotation><computeroutput>4</computeroutput>
7690 <sect2 id="functions-datetime-trunc">
7691 <title><function>date_trunc</function></title>
7694 <primary>date_trunc</primary>
7698 The function <function>date_trunc</function> is conceptually
7699 similar to the <function>trunc</function> function for numbers.
7704 date_trunc('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
7706 <replaceable>source</replaceable> is a value expression of type
7707 <type>timestamp</type> or <type>interval</>.
7708 (Values of type <type>date</type> and
7709 <type>time</type> are cast automatically to <type>timestamp</type> or
7710 <type>interval</>, respectively.)
7711 <replaceable>field</replaceable> selects to which precision to
7712 truncate the input value. The return value is of type
7713 <type>timestamp</type> or <type>interval</>
7714 with all fields that are less significant than the
7715 selected one set to zero (or one, for day and month).
7719 Valid values for <replaceable>field</replaceable> are:
7721 <member><literal>microseconds</literal></member>
7722 <member><literal>milliseconds</literal></member>
7723 <member><literal>second</literal></member>
7724 <member><literal>minute</literal></member>
7725 <member><literal>hour</literal></member>
7726 <member><literal>day</literal></member>
7727 <member><literal>week</literal></member>
7728 <member><literal>month</literal></member>
7729 <member><literal>quarter</literal></member>
7730 <member><literal>year</literal></member>
7731 <member><literal>decade</literal></member>
7732 <member><literal>century</literal></member>
7733 <member><literal>millennium</literal></member>
7740 SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
7741 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 20:00:00</computeroutput>
7743 SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
7744 <lineannotation>Result: </lineannotation><computeroutput>2001-01-01 00:00:00</computeroutput>
7749 <sect2 id="functions-datetime-zoneconvert">
7750 <title><literal>AT TIME ZONE</literal></title>
7753 <primary>time zone</primary>
7754 <secondary>conversion</secondary>
7758 <primary>AT TIME ZONE</primary>
7762 The <literal>AT TIME ZONE</literal> construct allows conversions
7763 of time stamps to different time zones. <xref
7764 linkend="functions-datetime-zoneconvert-table"> shows its
7768 <table id="functions-datetime-zoneconvert-table">
7769 <title><literal>AT TIME ZONE</literal> Variants</title>
7773 <entry>Expression</entry>
7774 <entry>Return Type</entry>
7775 <entry>Description</entry>
7782 <literal><type>timestamp without time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7784 <entry><type>timestamp with time zone</type></entry>
7785 <entry>Treat given time stamp <emphasis>without time zone</> as located in the specified time zone</entry>
7790 <literal><type>timestamp with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7792 <entry><type>timestamp without time zone</type></entry>
7793 <entry>Convert given time stamp <emphasis>with time zone</> to the new time
7794 zone, with no time zone designation</entry>
7799 <literal><type>time with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7801 <entry><type>time with time zone</type></entry>
7802 <entry>Convert given time <emphasis>with time zone</> to the new time zone</entry>
7809 In these expressions, the desired time zone <replaceable>zone</> can be
7810 specified either as a text string (e.g., <literal>'PST'</literal>)
7811 or as an interval (e.g., <literal>INTERVAL '-08:00'</literal>).
7812 In the text case, a time zone name can be specified in any of the ways
7813 described in <xref linkend="datatype-timezones">.
7817 Examples (assuming the local time zone is <literal>PST8PDT</>):
7819 SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'MST';
7820 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 19:38:40-08</computeroutput>
7822 SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'MST';
7823 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 18:38:40</computeroutput>
7825 The first example takes a time stamp without time zone and interprets it as MST time
7826 (UTC-7), which is then converted to PST (UTC-8) for display. The second example takes
7827 a time stamp specified in EST (UTC-5) and converts it to local time in MST (UTC-7).
7831 The function <literal><function>timezone</function>(<replaceable>zone</>,
7832 <replaceable>timestamp</>)</literal> is equivalent to the SQL-conforming construct
7833 <literal><replaceable>timestamp</> AT TIME ZONE
7834 <replaceable>zone</></literal>.
7838 <sect2 id="functions-datetime-current">
7839 <title>Current Date/Time</title>
7842 <primary>date</primary>
7843 <secondary>current</secondary>
7847 <primary>time</primary>
7848 <secondary>current</secondary>
7852 <productname>PostgreSQL</productname> provides a number of functions
7853 that return values related to the current date and time. These
7854 SQL-standard functions all return values based on the start time of
7855 the current transaction:
7860 CURRENT_TIME(<replaceable>precision</replaceable>)
7861 CURRENT_TIMESTAMP(<replaceable>precision</replaceable>)
7864 LOCALTIME(<replaceable>precision</replaceable>)
7865 LOCALTIMESTAMP(<replaceable>precision</replaceable>)
7870 <function>CURRENT_TIME</function> and
7871 <function>CURRENT_TIMESTAMP</function> deliver values with time zone;
7872 <function>LOCALTIME</function> and
7873 <function>LOCALTIMESTAMP</function> deliver values without time zone.
7877 <function>CURRENT_TIME</function>,
7878 <function>CURRENT_TIMESTAMP</function>,
7879 <function>LOCALTIME</function>, and
7880 <function>LOCALTIMESTAMP</function>
7882 a precision parameter, which causes the result to be rounded
7883 to that many fractional digits in the seconds field. Without a precision parameter,
7884 the result is given to the full available precision.
7890 SELECT CURRENT_TIME;
7891 <lineannotation>Result: </lineannotation><computeroutput>14:39:53.662522-05</computeroutput>
7893 SELECT CURRENT_DATE;
7894 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23</computeroutput>
7896 SELECT CURRENT_TIMESTAMP;
7897 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522-05</computeroutput>
7899 SELECT CURRENT_TIMESTAMP(2);
7900 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.66-05</computeroutput>
7902 SELECT LOCALTIMESTAMP;
7903 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522</computeroutput>
7908 Since these functions return
7909 the start time of the current transaction, their values do not
7910 change during the transaction. This is considered a feature:
7911 the intent is to allow a single transaction to have a consistent
7912 notion of the <quote>current</quote> time, so that multiple
7913 modifications within the same transaction bear the same
7919 Other database systems might advance these values more
7925 <productname>PostgreSQL</productname> also provides functions that
7926 return the start time of the current statement, as well as the actual
7927 current time at the instant the function is called. The complete list
7928 of non-SQL-standard time functions is:
7930 transaction_timestamp()
7931 statement_timestamp()
7939 <function>transaction_timestamp()</> is equivalent to
7940 <function>CURRENT_TIMESTAMP</function>, but is named to clearly reflect
7942 <function>statement_timestamp()</> returns the start time of the current
7943 statement (more specifically, the time of receipt of the latest command
7944 message from the client).
7945 <function>statement_timestamp()</> and <function>transaction_timestamp()</>
7946 return the same value during the first command of a transaction, but might
7947 differ during subsequent commands.
7948 <function>clock_timestamp()</> returns the actual current time, and
7949 therefore its value changes even within a single SQL command.
7950 <function>timeofday()</> is a historical
7951 <productname>PostgreSQL</productname> function. Like
7952 <function>clock_timestamp()</>, it returns the actual current time,
7953 but as a formatted <type>text</> string rather than a <type>timestamp
7954 with time zone</> value.
7955 <function>now()</> is a traditional <productname>PostgreSQL</productname>
7956 equivalent to <function>transaction_timestamp()</function>.
7960 All the date/time data types also accept the special literal value
7961 <literal>now</literal> to specify the current date and time (again,
7962 interpreted as the transaction start time). Thus,
7963 the following three all return the same result:
7965 SELECT CURRENT_TIMESTAMP;
7967 SELECT TIMESTAMP 'now'; -- incorrect for use with DEFAULT
7973 You do not want to use the third form when specifying a <literal>DEFAULT</>
7974 clause while creating a table. The system will convert <literal>now</literal>
7975 to a <type>timestamp</type> as soon as the constant is parsed, so that when
7976 the default value is needed,
7977 the time of the table creation would be used! The first two
7978 forms will not be evaluated until the default value is used,
7979 because they are function calls. Thus they will give the desired
7980 behavior of defaulting to the time of row insertion.
7985 <sect2 id="functions-datetime-delay">
7986 <title>Delaying Execution</title>
7989 <primary>pg_sleep</primary>
7992 <primary>pg_sleep_for</primary>
7995 <primary>pg_sleep_until</primary>
7998 <primary>sleep</primary>
8001 <primary>delay</primary>
8005 The following functions are available to delay execution of the server
8008 pg_sleep(<replaceable>seconds</replaceable>)
8009 pg_sleep_for(<type>interval</>)
8010 pg_sleep_until(<type>timestamp with time zone</>)
8013 <function>pg_sleep</function> makes the current session's process
8014 sleep until <replaceable>seconds</replaceable> seconds have
8015 elapsed. <replaceable>seconds</replaceable> is a value of type
8016 <type>double precision</>, so fractional-second delays can be specified.
8017 <function>pg_sleep_for</function> is a convenience function for larger
8018 sleep times specified as an <type>interval</>.
8019 <function>pg_sleep_until</function> is a convenience function for when
8020 a specific wake-up time is desired.
8024 SELECT pg_sleep(1.5);
8025 SELECT pg_sleep_for('5 minutes');
8026 SELECT pg_sleep_until('tomorrow 03:00');
8032 The effective resolution of the sleep interval is platform-specific;
8033 0.01 seconds is a common value. The sleep delay will be at least as long
8034 as specified. It might be longer depending on factors such as server load.
8035 In particular, <function>pg_sleep_until</function> is not guaranteed to
8036 wake up exactly at the specified time, but it will not wake up any earlier.
8042 Make sure that your session does not hold more locks than necessary
8043 when calling <function>pg_sleep</function> or its variants. Otherwise
8044 other sessions might have to wait for your sleeping process, slowing down
8053 <sect1 id="functions-enum">
8054 <title>Enum Support Functions</title>
8057 For enum types (described in <xref linkend="datatype-enum">),
8058 there are several functions that allow cleaner programming without
8059 hard-coding particular values of an enum type.
8060 These are listed in <xref linkend="functions-enum-table">. The examples
8061 assume an enum type created as:
8064 CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'purple');
8069 <table id="functions-enum-table">
8070 <title>Enum Support Functions</title>
8074 <entry>Function</entry>
8075 <entry>Description</entry>
8076 <entry>Example</entry>
8077 <entry>Example Result</entry>
8084 <primary>enum_first</primary>
8086 <literal>enum_first(anyenum)</literal>
8088 <entry>Returns the first value of the input enum type</entry>
8089 <entry><literal>enum_first(null::rainbow)</literal></entry>
8090 <entry><literal>red</literal></entry>
8095 <primary>enum_last</primary>
8097 <literal>enum_last(anyenum)</literal>
8099 <entry>Returns the last value of the input enum type</entry>
8100 <entry><literal>enum_last(null::rainbow)</literal></entry>
8101 <entry><literal>purple</literal></entry>
8106 <primary>enum_range</primary>
8108 <literal>enum_range(anyenum)</literal>
8110 <entry>Returns all values of the input enum type in an ordered array</entry>
8111 <entry><literal>enum_range(null::rainbow)</literal></entry>
8112 <entry><literal>{red,orange,yellow,green,blue,purple}</literal></entry>
8115 <entry morerows="2"><literal>enum_range(anyenum, anyenum)</literal></entry>
8116 <entry morerows="2">
8117 Returns the range between the two given enum values, as an ordered
8118 array. The values must be from the same enum type. If the first
8119 parameter is null, the result will start with the first value of
8121 If the second parameter is null, the result will end with the last
8122 value of the enum type.
8124 <entry><literal>enum_range('orange'::rainbow, 'green'::rainbow)</literal></entry>
8125 <entry><literal>{orange,yellow,green}</literal></entry>
8128 <entry><literal>enum_range(NULL, 'green'::rainbow)</literal></entry>
8129 <entry><literal>{red,orange,yellow,green}</literal></entry>
8132 <entry><literal>enum_range('orange'::rainbow, NULL)</literal></entry>
8133 <entry><literal>{orange,yellow,green,blue,purple}</literal></entry>
8140 Notice that except for the two-argument form of <function>enum_range</>,
8141 these functions disregard the specific value passed to them; they care
8142 only about its declared data type. Either null or a specific value of
8143 the type can be passed, with the same result. It is more common to
8144 apply these functions to a table column or function argument than to
8145 a hardwired type name as suggested by the examples.
8149 <sect1 id="functions-geometry">
8150 <title>Geometric Functions and Operators</title>
8153 The geometric types <type>point</type>, <type>box</type>,
8154 <type>lseg</type>, <type>line</type>, <type>path</type>,
8155 <type>polygon</type>, and <type>circle</type> have a large set of
8156 native support functions and operators, shown in <xref
8157 linkend="functions-geometry-op-table">, <xref
8158 linkend="functions-geometry-func-table">, and <xref
8159 linkend="functions-geometry-conv-table">.
8164 Note that the <quote>same as</> operator, <literal>~=</>, represents
8165 the usual notion of equality for the <type>point</type>,
8166 <type>box</type>, <type>polygon</type>, and <type>circle</type> types.
8167 Some of these types also have an <literal>=</> operator, but
8168 <literal>=</> compares
8169 for equal <emphasis>areas</> only. The other scalar comparison operators
8170 (<literal><=</> and so on) likewise compare areas for these types.
8174 <table id="functions-geometry-op-table">
8175 <title>Geometric Operators</title>
8179 <entry>Operator</entry>
8180 <entry>Description</entry>
8181 <entry>Example</entry>
8186 <entry> <literal>+</literal> </entry>
8187 <entry>Translation</entry>
8188 <entry><literal>box '((0,0),(1,1))' + point '(2.0,0)'</literal></entry>
8191 <entry> <literal>-</literal> </entry>
8192 <entry>Translation</entry>
8193 <entry><literal>box '((0,0),(1,1))' - point '(2.0,0)'</literal></entry>
8196 <entry> <literal>*</literal> </entry>
8197 <entry>Scaling/rotation</entry>
8198 <entry><literal>box '((0,0),(1,1))' * point '(2.0,0)'</literal></entry>
8201 <entry> <literal>/</literal> </entry>
8202 <entry>Scaling/rotation</entry>
8203 <entry><literal>box '((0,0),(2,2))' / point '(2.0,0)'</literal></entry>
8206 <entry> <literal>#</literal> </entry>
8207 <entry>Point or box of intersection</entry>
8208 <entry><literal>'((1,-1),(-1,1))' # '((1,1),(-1,-1))'</literal></entry>
8211 <entry> <literal>#</literal> </entry>
8212 <entry>Number of points in path or polygon</entry>
8213 <entry><literal># '((1,0),(0,1),(-1,0))'</literal></entry>
8216 <entry> <literal>@-@</literal> </entry>
8217 <entry>Length or circumference</entry>
8218 <entry><literal>@-@ path '((0,0),(1,0))'</literal></entry>
8221 <entry> <literal>@@</literal> </entry>
8222 <entry>Center</entry>
8223 <entry><literal>@@ circle '((0,0),10)'</literal></entry>
8226 <entry> <literal>##</literal> </entry>
8227 <entry>Closest point to first operand on second operand</entry>
8228 <entry><literal>point '(0,0)' ## lseg '((2,0),(0,2))'</literal></entry>
8231 <entry> <literal><-></literal> </entry>
8232 <entry>Distance between</entry>
8233 <entry><literal>circle '((0,0),1)' <-> circle '((5,0),1)'</literal></entry>
8236 <entry> <literal>&&</literal> </entry>
8237 <entry>Overlaps? (One point in common makes this true.)</entry>
8238 <entry><literal>box '((0,0),(1,1))' && box '((0,0),(2,2))'</literal></entry>
8241 <entry> <literal><<</literal> </entry>
8242 <entry>Is strictly left of?</entry>
8243 <entry><literal>circle '((0,0),1)' << circle '((5,0),1)'</literal></entry>
8246 <entry> <literal>>></literal> </entry>
8247 <entry>Is strictly right of?</entry>
8248 <entry><literal>circle '((5,0),1)' >> circle '((0,0),1)'</literal></entry>
8251 <entry> <literal>&<</literal> </entry>
8252 <entry>Does not extend to the right of?</entry>
8253 <entry><literal>box '((0,0),(1,1))' &< box '((0,0),(2,2))'</literal></entry>
8256 <entry> <literal>&></literal> </entry>
8257 <entry>Does not extend to the left of?</entry>
8258 <entry><literal>box '((0,0),(3,3))' &> box '((0,0),(2,2))'</literal></entry>
8261 <entry> <literal><<|</literal> </entry>
8262 <entry>Is strictly below?</entry>
8263 <entry><literal>box '((0,0),(3,3))' <<| box '((3,4),(5,5))'</literal></entry>
8266 <entry> <literal>|>></literal> </entry>
8267 <entry>Is strictly above?</entry>
8268 <entry><literal>box '((3,4),(5,5))' |>> box '((0,0),(3,3))'</literal></entry>
8271 <entry> <literal>&<|</literal> </entry>
8272 <entry>Does not extend above?</entry>
8273 <entry><literal>box '((0,0),(1,1))' &<| box '((0,0),(2,2))'</literal></entry>
8276 <entry> <literal>|&></literal> </entry>
8277 <entry>Does not extend below?</entry>
8278 <entry><literal>box '((0,0),(3,3))' |&> box '((0,0),(2,2))'</literal></entry>
8281 <entry> <literal><^</literal> </entry>
8282 <entry>Is below (allows touching)?</entry>
8283 <entry><literal>circle '((0,0),1)' <^ circle '((0,5),1)'</literal></entry>
8286 <entry> <literal>>^</literal> </entry>
8287 <entry>Is above (allows touching)?</entry>
8288 <entry><literal>circle '((0,5),1)' >^ circle '((0,0),1)'</literal></entry>
8291 <entry> <literal>?#</literal> </entry>
8292 <entry>Intersects?</entry>
8293 <entry><literal>lseg '((-1,0),(1,0))' ?# box '((-2,-2),(2,2))'</literal></entry>
8296 <entry> <literal>?-</literal> </entry>
8297 <entry>Is horizontal?</entry>
8298 <entry><literal>?- lseg '((-1,0),(1,0))'</literal></entry>
8301 <entry> <literal>?-</literal> </entry>
8302 <entry>Are horizontally aligned?</entry>
8303 <entry><literal>point '(1,0)' ?- point '(0,0)'</literal></entry>
8306 <entry> <literal>?|</literal> </entry>
8307 <entry>Is vertical?</entry>
8308 <entry><literal>?| lseg '((-1,0),(1,0))'</literal></entry>
8311 <entry> <literal>?|</literal> </entry>
8312 <entry>Are vertically aligned?</entry>
8313 <entry><literal>point '(0,1)' ?| point '(0,0)'</literal></entry>
8316 <entry> <literal>?-|</literal> </entry>
8317 <entry>Is perpendicular?</entry>
8318 <entry><literal>lseg '((0,0),(0,1))' ?-| lseg '((0,0),(1,0))'</literal></entry>
8321 <entry> <literal>?||</literal> </entry>
8322 <entry>Are parallel?</entry>
8323 <entry><literal>lseg '((-1,0),(1,0))' ?|| lseg '((-1,2),(1,2))'</literal></entry>
8326 <entry> <literal>@></literal> </entry>
8327 <entry>Contains?</entry>
8328 <entry><literal>circle '((0,0),2)' @> point '(1,1)'</literal></entry>
8331 <entry> <literal><@</literal> </entry>
8332 <entry>Contained in or on?</entry>
8333 <entry><literal>point '(1,1)' <@ circle '((0,0),2)'</literal></entry>
8336 <entry> <literal>~=</literal> </entry>
8337 <entry>Same as?</entry>
8338 <entry><literal>polygon '((0,0),(1,1))' ~= polygon '((1,1),(0,0))'</literal></entry>
8346 Before <productname>PostgreSQL</productname> 8.2, the containment
8347 operators <literal>@></> and <literal><@</> were respectively
8348 called <literal>~</> and <literal>@</>. These names are still
8349 available, but are deprecated and will eventually be removed.
8354 <primary>area</primary>
8357 <primary>center</primary>
8360 <primary>diameter</primary>
8363 <primary>height</primary>
8366 <primary>isclosed</primary>
8369 <primary>isopen</primary>
8372 <primary>length</primary>
8375 <primary>npoints</primary>
8378 <primary>pclose</primary>
8381 <primary>popen</primary>
8384 <primary>radius</primary>
8387 <primary>width</primary>
8390 <table id="functions-geometry-func-table">
8391 <title>Geometric Functions</title>
8395 <entry>Function</entry>
8396 <entry>Return Type</entry>
8397 <entry>Description</entry>
8398 <entry>Example</entry>
8403 <entry><literal><function>area(<replaceable>object</>)</function></literal></entry>
8404 <entry><type>double precision</type></entry>
8406 <entry><literal>area(box '((0,0),(1,1))')</literal></entry>
8409 <entry><literal><function>center(<replaceable>object</>)</function></literal></entry>
8410 <entry><type>point</type></entry>
8411 <entry>center</entry>
8412 <entry><literal>center(box '((0,0),(1,2))')</literal></entry>
8415 <entry><literal><function>diameter(<type>circle</>)</function></literal></entry>
8416 <entry><type>double precision</type></entry>
8417 <entry>diameter of circle</entry>
8418 <entry><literal>diameter(circle '((0,0),2.0)')</literal></entry>
8421 <entry><literal><function>height(<type>box</>)</function></literal></entry>
8422 <entry><type>double precision</type></entry>
8423 <entry>vertical size of box</entry>
8424 <entry><literal>height(box '((0,0),(1,1))')</literal></entry>
8427 <entry><literal><function>isclosed(<type>path</>)</function></literal></entry>
8428 <entry><type>boolean</type></entry>
8429 <entry>a closed path?</entry>
8430 <entry><literal>isclosed(path '((0,0),(1,1),(2,0))')</literal></entry>
8433 <entry><literal><function>isopen(<type>path</>)</function></literal></entry>
8434 <entry><type>boolean</type></entry>
8435 <entry>an open path?</entry>
8436 <entry><literal>isopen(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8439 <entry><literal><function>length(<replaceable>object</>)</function></literal></entry>
8440 <entry><type>double precision</type></entry>
8441 <entry>length</entry>
8442 <entry><literal>length(path '((-1,0),(1,0))')</literal></entry>
8445 <entry><literal><function>npoints(<type>path</>)</function></literal></entry>
8446 <entry><type>int</type></entry>
8447 <entry>number of points</entry>
8448 <entry><literal>npoints(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8451 <entry><literal><function>npoints(<type>polygon</>)</function></literal></entry>
8452 <entry><type>int</type></entry>
8453 <entry>number of points</entry>
8454 <entry><literal>npoints(polygon '((1,1),(0,0))')</literal></entry>
8457 <entry><literal><function>pclose(<type>path</>)</function></literal></entry>
8458 <entry><type>path</type></entry>
8459 <entry>convert path to closed</entry>
8460 <entry><literal>pclose(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8463 <!-- Not defined by this name. Implements the intersection operator '#' -->
8465 <entry><literal><function>point(<type>lseg</>, <type>lseg</>)</function></literal></entry>
8466 <entry><type>point</type></entry>
8467 <entry>intersection</entry>
8468 <entry><literal>point(lseg '((-1,0),(1,0))',lseg '((-2,-2),(2,2))')</literal></entry>
8472 <entry><literal><function>popen(<type>path</>)</function></literal></entry>
8473 <entry><type>path</type></entry>
8474 <entry>convert path to open</entry>
8475 <entry><literal>popen(path '((0,0),(1,1),(2,0))')</literal></entry>
8478 <entry><literal><function>radius(<type>circle</type>)</function></literal></entry>
8479 <entry><type>double precision</type></entry>
8480 <entry>radius of circle</entry>
8481 <entry><literal>radius(circle '((0,0),2.0)')</literal></entry>
8484 <entry><literal><function>width(<type>box</>)</function></literal></entry>
8485 <entry><type>double precision</type></entry>
8486 <entry>horizontal size of box</entry>
8487 <entry><literal>width(box '((0,0),(1,1))')</literal></entry>
8493 <table id="functions-geometry-conv-table">
8494 <title>Geometric Type Conversion Functions</title>
8498 <entry>Function</entry>
8499 <entry>Return Type</entry>
8500 <entry>Description</entry>
8501 <entry>Example</entry>
8508 <primary>box</primary>
8510 <literal><function>box(<type>circle</type>)</function></literal>
8512 <entry><type>box</type></entry>
8513 <entry>circle to box</entry>
8514 <entry><literal>box(circle '((0,0),2.0)')</literal></entry>
8517 <entry><literal><function>box(<type>point</type>)</function></literal></entry>
8518 <entry><type>box</type></entry>
8519 <entry>point to empty box</entry>
8520 <entry><literal>box(point '(0,0)')</literal></entry>
8523 <entry><literal><function>box(<type>point</type>, <type>point</type>)</function></literal></entry>
8524 <entry><type>box</type></entry>
8525 <entry>points to box</entry>
8526 <entry><literal>box(point '(0,0)', point '(1,1)')</literal></entry>
8529 <entry><literal><function>box(<type>polygon</type>)</function></literal></entry>
8530 <entry><type>box</type></entry>
8531 <entry>polygon to box</entry>
8532 <entry><literal>box(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8535 <entry><literal><function>bound_box(<type>box</type>, <type>box</type>)</function></literal></entry>
8536 <entry><type>box</type></entry>
8537 <entry>boxes to bounding box</entry>
8538 <entry><literal>bound_box(box '((0,0),(1,1))', box '((3,3),(4,4))')</literal></entry>
8543 <primary>circle</primary>
8545 <literal><function>circle(<type>box</type>)</function></literal>
8547 <entry><type>circle</type></entry>
8548 <entry>box to circle</entry>
8549 <entry><literal>circle(box '((0,0),(1,1))')</literal></entry>
8552 <entry><literal><function>circle(<type>point</type>, <type>double precision</type>)</function></literal></entry>
8553 <entry><type>circle</type></entry>
8554 <entry>center and radius to circle</entry>
8555 <entry><literal>circle(point '(0,0)', 2.0)</literal></entry>
8558 <entry><literal><function>circle(<type>polygon</type>)</function></literal></entry>
8559 <entry><type>circle</type></entry>
8560 <entry>polygon to circle</entry>
8561 <entry><literal>circle(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8564 <entry><literal><function>line(<type>point</type>, <type>point</type>)</function></literal></entry>
8565 <entry><type>line</type></entry>
8566 <entry>points to line</entry>
8567 <entry><literal>line(point '(-1,0)', point '(1,0)')</literal></entry>
8572 <primary>lseg</primary>
8574 <literal><function>lseg(<type>box</type>)</function></literal>
8576 <entry><type>lseg</type></entry>
8577 <entry>box diagonal to line segment</entry>
8578 <entry><literal>lseg(box '((-1,0),(1,0))')</literal></entry>
8581 <entry><literal><function>lseg(<type>point</type>, <type>point</type>)</function></literal></entry>
8582 <entry><type>lseg</type></entry>
8583 <entry>points to line segment</entry>
8584 <entry><literal>lseg(point '(-1,0)', point '(1,0)')</literal></entry>
8589 <primary>path</primary>
8591 <literal><function>path(<type>polygon</type>)</function></literal>
8593 <entry><type>path</type></entry>
8594 <entry>polygon to path</entry>
8595 <entry><literal>path(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8600 <primary>point</primary>
8602 <literal><function>point</function>(<type>double
8603 precision</type>, <type>double precision</type>)</literal>
8605 <entry><type>point</type></entry>
8606 <entry>construct point</entry>
8607 <entry><literal>point(23.4, -44.5)</literal></entry>
8610 <entry><literal><function>point(<type>box</type>)</function></literal></entry>
8611 <entry><type>point</type></entry>
8612 <entry>center of box</entry>
8613 <entry><literal>point(box '((-1,0),(1,0))')</literal></entry>
8616 <entry><literal><function>point(<type>circle</type>)</function></literal></entry>
8617 <entry><type>point</type></entry>
8618 <entry>center of circle</entry>
8619 <entry><literal>point(circle '((0,0),2.0)')</literal></entry>
8622 <entry><literal><function>point(<type>lseg</type>)</function></literal></entry>
8623 <entry><type>point</type></entry>
8624 <entry>center of line segment</entry>
8625 <entry><literal>point(lseg '((-1,0),(1,0))')</literal></entry>
8628 <entry><literal><function>point(<type>polygon</type>)</function></literal></entry>
8629 <entry><type>point</type></entry>
8630 <entry>center of polygon</entry>
8631 <entry><literal>point(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8636 <primary>polygon</primary>
8638 <literal><function>polygon(<type>box</type>)</function></literal>
8640 <entry><type>polygon</type></entry>
8641 <entry>box to 4-point polygon</entry>
8642 <entry><literal>polygon(box '((0,0),(1,1))')</literal></entry>
8645 <entry><literal><function>polygon(<type>circle</type>)</function></literal></entry>
8646 <entry><type>polygon</type></entry>
8647 <entry>circle to 12-point polygon</entry>
8648 <entry><literal>polygon(circle '((0,0),2.0)')</literal></entry>
8651 <entry><literal><function>polygon(<replaceable class="parameter">npts</replaceable>, <type>circle</type>)</function></literal></entry>
8652 <entry><type>polygon</type></entry>
8653 <entry>circle to <replaceable class="parameter">npts</replaceable>-point polygon</entry>
8654 <entry><literal>polygon(12, circle '((0,0),2.0)')</literal></entry>
8657 <entry><literal><function>polygon(<type>path</type>)</function></literal></entry>
8658 <entry><type>polygon</type></entry>
8659 <entry>path to polygon</entry>
8660 <entry><literal>polygon(path '((0,0),(1,1),(2,0))')</literal></entry>
8667 It is possible to access the two component numbers of a <type>point</>
8668 as though the point were an array with indexes 0 and 1. For example, if
8669 <literal>t.p</> is a <type>point</> column then
8670 <literal>SELECT p[0] FROM t</> retrieves the X coordinate and
8671 <literal>UPDATE t SET p[1] = ...</> changes the Y coordinate.
8672 In the same way, a value of type <type>box</> or <type>lseg</> can be treated
8673 as an array of two <type>point</> values.
8677 The <function>area</function> function works for the types
8678 <type>box</type>, <type>circle</type>, and <type>path</type>.
8679 The <function>area</function> function only works on the
8680 <type>path</type> data type if the points in the
8681 <type>path</type> are non-intersecting. For example, the
8683 <literal>'((0,0),(0,1),(2,1),(2,2),(1,2),(1,0),(0,0))'::PATH</literal>
8684 will not work; however, the following visually identical
8686 <literal>'((0,0),(0,1),(1,1),(1,2),(2,2),(2,1),(1,1),(1,0),(0,0))'::PATH</literal>
8687 will work. If the concept of an intersecting versus
8688 non-intersecting <type>path</type> is confusing, draw both of the
8689 above <type>path</type>s side by side on a piece of graph paper.
8695 <sect1 id="functions-net">
8696 <title>Network Address Functions and Operators</title>
8699 <xref linkend="cidr-inet-operators-table"> shows the operators
8700 available for the <type>cidr</type> and <type>inet</type> types.
8701 The operators <literal><<</literal>,
8702 <literal><<=</literal>, <literal>>></literal>,
8703 <literal>>>=</literal>, and <literal>&&</literal>
8704 test for subnet inclusion. They
8705 consider only the network parts of the two addresses (ignoring any
8706 host part) and determine whether one network is identical to
8707 or a subnet of the other.
8710 <table id="cidr-inet-operators-table">
8711 <title><type>cidr</type> and <type>inet</type> Operators</title>
8715 <entry>Operator</entry>
8716 <entry>Description</entry>
8717 <entry>Example</entry>
8722 <entry> <literal><</literal> </entry>
8723 <entry>is less than</entry>
8724 <entry><literal>inet '192.168.1.5' < inet '192.168.1.6'</literal></entry>
8727 <entry> <literal><=</literal> </entry>
8728 <entry>is less than or equal</entry>
8729 <entry><literal>inet '192.168.1.5' <= inet '192.168.1.5'</literal></entry>
8732 <entry> <literal>=</literal> </entry>
8733 <entry>equals</entry>
8734 <entry><literal>inet '192.168.1.5' = inet '192.168.1.5'</literal></entry>
8737 <entry> <literal>>=</literal> </entry>
8738 <entry>is greater or equal</entry>
8739 <entry><literal>inet '192.168.1.5' >= inet '192.168.1.5'</literal></entry>
8742 <entry> <literal>></literal> </entry>
8743 <entry>is greater than</entry>
8744 <entry><literal>inet '192.168.1.5' > inet '192.168.1.4'</literal></entry>
8747 <entry> <literal><></literal> </entry>
8748 <entry>is not equal</entry>
8749 <entry><literal>inet '192.168.1.5' <> inet '192.168.1.4'</literal></entry>
8752 <entry> <literal><<</literal> </entry>
8753 <entry>is contained by</entry>
8754 <entry><literal>inet '192.168.1.5' << inet '192.168.1/24'</literal></entry>
8757 <entry> <literal><<=</literal> </entry>
8758 <entry>is contained by or equals</entry>
8759 <entry><literal>inet '192.168.1/24' <<= inet '192.168.1/24'</literal></entry>
8762 <entry> <literal>>></literal> </entry>
8763 <entry>contains</entry>
8764 <entry><literal>inet '192.168.1/24' >> inet '192.168.1.5'</literal></entry>
8767 <entry> <literal>>>=</literal> </entry>
8768 <entry>contains or equals</entry>
8769 <entry><literal>inet '192.168.1/24' >>= inet '192.168.1/24'</literal></entry>
8772 <entry> <literal>&&</literal> </entry>
8773 <entry>contains or is contained by</entry>
8774 <entry><literal>inet '192.168.1/24' && inet '192.168.1.80/28'</literal></entry>
8777 <entry> <literal>~</literal> </entry>
8778 <entry>bitwise NOT</entry>
8779 <entry><literal>~ inet '192.168.1.6'</literal></entry>
8782 <entry> <literal>&</literal> </entry>
8783 <entry>bitwise AND</entry>
8784 <entry><literal>inet '192.168.1.6' & inet '0.0.0.255'</literal></entry>
8787 <entry> <literal>|</literal> </entry>
8788 <entry>bitwise OR</entry>
8789 <entry><literal>inet '192.168.1.6' | inet '0.0.0.255'</literal></entry>
8792 <entry> <literal>+</literal> </entry>
8793 <entry>addition</entry>
8794 <entry><literal>inet '192.168.1.6' + 25</literal></entry>
8797 <entry> <literal>-</literal> </entry>
8798 <entry>subtraction</entry>
8799 <entry><literal>inet '192.168.1.43' - 36</literal></entry>
8802 <entry> <literal>-</literal> </entry>
8803 <entry>subtraction</entry>
8804 <entry><literal>inet '192.168.1.43' - inet '192.168.1.19'</literal></entry>
8811 <xref linkend="cidr-inet-functions-table"> shows the functions
8812 available for use with the <type>cidr</type> and <type>inet</type>
8813 types. The <function>abbrev</function>, <function>host</function>,
8814 and <function>text</function>
8815 functions are primarily intended to offer alternative display
8819 <table id="cidr-inet-functions-table">
8820 <title><type>cidr</type> and <type>inet</type> Functions</title>
8824 <entry>Function</entry>
8825 <entry>Return Type</entry>
8826 <entry>Description</entry>
8827 <entry>Example</entry>
8828 <entry>Result</entry>
8835 <primary>abbrev</primary>
8837 <literal><function>abbrev(<type>inet</type>)</function></literal>
8839 <entry><type>text</type></entry>
8840 <entry>abbreviated display format as text</entry>
8841 <entry><literal>abbrev(inet '10.1.0.0/16')</literal></entry>
8842 <entry><literal>10.1.0.0/16</literal></entry>
8845 <entry><literal><function>abbrev(<type>cidr</type>)</function></literal></entry>
8846 <entry><type>text</type></entry>
8847 <entry>abbreviated display format as text</entry>
8848 <entry><literal>abbrev(cidr '10.1.0.0/16')</literal></entry>
8849 <entry><literal>10.1/16</literal></entry>
8854 <primary>broadcast</primary>
8856 <literal><function>broadcast(<type>inet</type>)</function></literal>
8858 <entry><type>inet</type></entry>
8859 <entry>broadcast address for network</entry>
8860 <entry><literal>broadcast('192.168.1.5/24')</literal></entry>
8861 <entry><literal>192.168.1.255/24</literal></entry>
8866 <primary>family</primary>
8868 <literal><function>family(<type>inet</type>)</function></literal>
8870 <entry><type>int</type></entry>
8871 <entry>extract family of address; <literal>4</literal> for IPv4,
8872 <literal>6</literal> for IPv6</entry>
8873 <entry><literal>family('::1')</literal></entry>
8874 <entry><literal>6</literal></entry>
8879 <primary>host</primary>
8881 <literal><function>host(<type>inet</type>)</function></literal>
8883 <entry><type>text</type></entry>
8884 <entry>extract IP address as text</entry>
8885 <entry><literal>host('192.168.1.5/24')</literal></entry>
8886 <entry><literal>192.168.1.5</literal></entry>
8891 <primary>hostmask</primary>
8893 <literal><function>hostmask(<type>inet</type>)</function></literal>
8895 <entry><type>inet</type></entry>
8896 <entry>construct host mask for network</entry>
8897 <entry><literal>hostmask('192.168.23.20/30')</literal></entry>
8898 <entry><literal>0.0.0.3</literal></entry>
8903 <primary>masklen</primary>
8905 <literal><function>masklen(<type>inet</type>)</function></literal>
8907 <entry><type>int</type></entry>
8908 <entry>extract netmask length</entry>
8909 <entry><literal>masklen('192.168.1.5/24')</literal></entry>
8910 <entry><literal>24</literal></entry>
8915 <primary>netmask</primary>
8917 <literal><function>netmask(<type>inet</type>)</function></literal>
8919 <entry><type>inet</type></entry>
8920 <entry>construct netmask for network</entry>
8921 <entry><literal>netmask('192.168.1.5/24')</literal></entry>
8922 <entry><literal>255.255.255.0</literal></entry>
8927 <primary>network</primary>
8929 <literal><function>network(<type>inet</type>)</function></literal>
8931 <entry><type>cidr</type></entry>
8932 <entry>extract network part of address</entry>
8933 <entry><literal>network('192.168.1.5/24')</literal></entry>
8934 <entry><literal>192.168.1.0/24</literal></entry>
8939 <primary>set_masklen</primary>
8941 <literal><function>set_masklen(<type>inet</type>, <type>int</type>)</function></literal>
8943 <entry><type>inet</type></entry>
8944 <entry>set netmask length for <type>inet</type> value</entry>
8945 <entry><literal>set_masklen('192.168.1.5/24', 16)</literal></entry>
8946 <entry><literal>192.168.1.5/16</literal></entry>
8949 <entry><literal><function>set_masklen(<type>cidr</type>, <type>int</type>)</function></literal></entry>
8950 <entry><type>cidr</type></entry>
8951 <entry>set netmask length for <type>cidr</type> value</entry>
8952 <entry><literal>set_masklen('192.168.1.0/24'::cidr, 16)</literal></entry>
8953 <entry><literal>192.168.0.0/16</literal></entry>
8958 <primary>text</primary>
8960 <literal><function>text(<type>inet</type>)</function></literal>
8962 <entry><type>text</type></entry>
8963 <entry>extract IP address and netmask length as text</entry>
8964 <entry><literal>text(inet '192.168.1.5')</literal></entry>
8965 <entry><literal>192.168.1.5/32</literal></entry>
8970 <primary>inet_same_family</primary>
8972 <literal><function>inet_same_family(<type>inet</type>, <type>inet</type>)</function></literal>
8974 <entry><type>boolean</type></entry>
8975 <entry>are the addresses from the same family?</entry>
8976 <entry><literal>inet_same_family('192.168.1.5/24', '::1')</literal></entry>
8977 <entry><literal>false</literal></entry>
8982 <primary>inet_merge</primary>
8984 <literal><function>inet_merge(<type>inet</type>, <type>inet</type>)</function></literal>
8986 <entry><type>cidr</type></entry>
8987 <entry>the smallest network which includes both of the given networks</entry>
8988 <entry><literal>inet_merge('192.168.1.5/24', '192.168.2.5/24')</literal></entry>
8989 <entry><literal>192.168.0.0/22</literal></entry>
8996 Any <type>cidr</> value can be cast to <type>inet</> implicitly
8997 or explicitly; therefore, the functions shown above as operating on
8998 <type>inet</> also work on <type>cidr</> values. (Where there are
8999 separate functions for <type>inet</> and <type>cidr</>, it is because
9000 the behavior should be different for the two cases.)
9001 Also, it is permitted to cast an <type>inet</> value to <type>cidr</>.
9002 When this is done, any bits to the right of the netmask are silently zeroed
9003 to create a valid <type>cidr</> value.
9005 you can cast a text value to <type>inet</> or <type>cidr</>
9006 using normal casting syntax: for example,
9007 <literal>inet(<replaceable>expression</>)</literal> or
9008 <literal><replaceable>colname</>::cidr</literal>.
9012 <xref linkend="macaddr-functions-table"> shows the functions
9013 available for use with the <type>macaddr</type> type. The function
9014 <literal><function>trunc(<type>macaddr</type>)</function></literal> returns a MAC
9015 address with the last 3 bytes set to zero. This can be used to
9016 associate the remaining prefix with a manufacturer.
9019 <table id="macaddr-functions-table">
9020 <title><type>macaddr</type> Functions</title>
9024 <entry>Function</entry>
9025 <entry>Return Type</entry>
9026 <entry>Description</entry>
9027 <entry>Example</entry>
9028 <entry>Result</entry>
9035 <primary>trunc</primary>
9037 <literal><function>trunc(<type>macaddr</type>)</function></literal>
9039 <entry><type>macaddr</type></entry>
9040 <entry>set last 3 bytes to zero</entry>
9041 <entry><literal>trunc(macaddr '12:34:56:78:90:ab')</literal></entry>
9042 <entry><literal>12:34:56:00:00:00</literal></entry>
9049 The <type>macaddr</type> type also supports the standard relational
9050 operators (<literal>></literal>, <literal><=</literal>, etc.) for
9051 lexicographical ordering, and the bitwise arithmetic operators
9052 (<literal>~</literal>, <literal>&</literal> and <literal>|</literal>)
9053 for NOT, AND and OR.
9059 <sect1 id="functions-textsearch">
9060 <title>Text Search Functions and Operators</title>
9062 <indexterm zone="datatype-textsearch">
9063 <primary>full text search</primary>
9064 <secondary>functions and operators</secondary>
9067 <indexterm zone="datatype-textsearch">
9068 <primary>text search</primary>
9069 <secondary>functions and operators</secondary>
9073 <xref linkend="textsearch-operators-table">,
9074 <xref linkend="textsearch-functions-table"> and
9075 <xref linkend="textsearch-functions-debug-table">
9076 summarize the functions and operators that are provided
9077 for full text searching. See <xref linkend="textsearch"> for a detailed
9078 explanation of <productname>PostgreSQL</productname>'s text search
9082 <table id="textsearch-operators-table">
9083 <title>Text Search Operators</title>
9087 <entry>Operator</entry>
9088 <entry>Return Type</entry>
9089 <entry>Description</entry>
9090 <entry>Example</entry>
9091 <entry>Result</entry>
9096 <entry> <literal>@@</literal> </entry>
9097 <entry><type>boolean</></entry>
9098 <entry><type>tsvector</> matches <type>tsquery</> ?</entry>
9099 <entry><literal>to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat')</literal></entry>
9100 <entry><literal>t</literal></entry>
9103 <entry> <literal>@@@</literal> </entry>
9104 <entry><type>boolean</></entry>
9105 <entry>deprecated synonym for <literal>@@</></entry>
9106 <entry><literal>to_tsvector('fat cats ate rats') @@@ to_tsquery('cat & rat')</literal></entry>
9107 <entry><literal>t</literal></entry>
9110 <entry> <literal>||</literal> </entry>
9111 <entry><type>tsvector</></entry>
9112 <entry>concatenate <type>tsvector</>s</entry>
9113 <entry><literal>'a:1 b:2'::tsvector || 'c:1 d:2 b:3'::tsvector</literal></entry>
9114 <entry><literal>'a':1 'b':2,5 'c':3 'd':4</literal></entry>
9117 <entry> <literal>&&</literal> </entry>
9118 <entry><type>tsquery</></entry>
9119 <entry>AND <type>tsquery</>s together</entry>
9120 <entry><literal>'fat | rat'::tsquery && 'cat'::tsquery</literal></entry>
9121 <entry><literal>( 'fat' | 'rat' ) & 'cat'</literal></entry>
9124 <entry> <literal>||</literal> </entry>
9125 <entry><type>tsquery</></entry>
9126 <entry>OR <type>tsquery</>s together</entry>
9127 <entry><literal>'fat | rat'::tsquery || 'cat'::tsquery</literal></entry>
9128 <entry><literal>( 'fat' | 'rat' ) | 'cat'</literal></entry>
9131 <entry> <literal>!!</literal> </entry>
9132 <entry><type>tsquery</></entry>
9133 <entry>negate a <type>tsquery</></entry>
9134 <entry><literal>!! 'cat'::tsquery</literal></entry>
9135 <entry><literal>!'cat'</literal></entry>
9138 <entry> <literal><-></literal> </entry>
9139 <entry><type>tsquery</></entry>
9140 <entry><type>tsquery</> followed by <type>tsquery</></entry>
9141 <entry><literal>to_tsquery('fat') <-> to_tsquery('rat')</literal></entry>
9142 <entry><literal>'fat' <-> 'rat'</literal></entry>
9145 <entry> <literal>@></literal> </entry>
9146 <entry><type>boolean</></entry>
9147 <entry><type>tsquery</> contains another ?</entry>
9148 <entry><literal>'cat'::tsquery @> 'cat & rat'::tsquery</literal></entry>
9149 <entry><literal>f</literal></entry>
9152 <entry> <literal><@</literal> </entry>
9153 <entry><type>boolean</></entry>
9154 <entry><type>tsquery</> is contained in ?</entry>
9155 <entry><literal>'cat'::tsquery <@ 'cat & rat'::tsquery</literal></entry>
9156 <entry><literal>t</literal></entry>
9164 The <type>tsquery</> containment operators consider only the lexemes
9165 listed in the two queries, ignoring the combining operators.
9170 In addition to the operators shown in the table, the ordinary B-tree
9171 comparison operators (<literal>=</>, <literal><</>, etc) are defined
9172 for types <type>tsvector</> and <type>tsquery</>. These are not very
9173 useful for text searching but allow, for example, unique indexes to be
9174 built on columns of these types.
9177 <table id="textsearch-functions-table">
9178 <title>Text Search Functions</title>
9182 <entry>Function</entry>
9183 <entry>Return Type</entry>
9184 <entry>Description</entry>
9185 <entry>Example</entry>
9186 <entry>Result</entry>
9193 <primary>array_to_tsvector</primary>
9195 <literal><function>array_to_tsvector(<type>text[]</>)</function></literal>
9197 <entry><type>tsvector</type></entry>
9198 <entry>convert array of lexemes to <type>tsvector</type></entry>
9199 <entry><literal>array_to_tsvector('{fat,cat,rat}'::text[])</literal></entry>
9200 <entry><literal>'fat' 'cat' 'rat'</literal></entry>
9205 <primary>get_current_ts_config</primary>
9207 <literal><function>get_current_ts_config()</function></literal>
9209 <entry><type>regconfig</type></entry>
9210 <entry>get default text search configuration</entry>
9211 <entry><literal>get_current_ts_config()</literal></entry>
9212 <entry><literal>english</literal></entry>
9217 <primary>length</primary>
9219 <literal><function>length(<type>tsvector</>)</function></literal>
9221 <entry><type>integer</type></entry>
9222 <entry>number of lexemes in <type>tsvector</></entry>
9223 <entry><literal>length('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9224 <entry><literal>3</literal></entry>
9229 <primary>numnode</primary>
9231 <literal><function>numnode(<type>tsquery</>)</function></literal>
9233 <entry><type>integer</type></entry>
9234 <entry>number of lexemes plus operators in <type>tsquery</></entry>
9235 <entry><literal> numnode('(fat & rat) | cat'::tsquery)</literal></entry>
9236 <entry><literal>5</literal></entry>
9241 <primary>plainto_tsquery</primary>
9243 <literal><function>plainto_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
9245 <entry><type>tsquery</type></entry>
9246 <entry>produce <type>tsquery</> ignoring punctuation</entry>
9247 <entry><literal>plainto_tsquery('english', 'The Fat Rats')</literal></entry>
9248 <entry><literal>'fat' & 'rat'</literal></entry>
9253 <primary>phraseto_tsquery</primary>
9255 <literal><function>phraseto_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
9257 <entry><type>tsquery</type></entry>
9258 <entry>produce <type>tsquery</> that searches for a phrase,
9259 ignoring punctuation</entry>
9260 <entry><literal>phraseto_tsquery('english', 'The Fat Rats')</literal></entry>
9261 <entry><literal>'fat' <-> 'rat'</literal></entry>
9266 <primary>querytree</primary>
9268 <literal><function>querytree(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>)</function></literal>
9270 <entry><type>text</type></entry>
9271 <entry>get indexable part of a <type>tsquery</></entry>
9272 <entry><literal>querytree('foo & ! bar'::tsquery)</literal></entry>
9273 <entry><literal>'foo'</literal></entry>
9278 <primary>setweight</primary>
9280 <literal><function>setweight(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">weight</replaceable> <type>"char"</>)</function></literal>
9282 <entry><type>tsvector</type></entry>
9283 <entry>assign <replaceable class="PARAMETER">weight</replaceable> to each element of <replaceable class="PARAMETER">vector</replaceable></entry>
9284 <entry><literal>setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A')</literal></entry>
9285 <entry><literal>'cat':3A 'fat':2A,4A 'rat':5A</literal></entry>
9290 <primary>setweight</primary>
9291 <secondary>setweight for specific lexeme(s)</secondary>
9293 <literal><function>setweight(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">weight</replaceable> <type>"char"</>, <replaceable class="PARAMETER">lexemes</replaceable> <type>text[]</>)</function></literal>
9295 <entry><type>tsvector</type></entry>
9296 <entry>assign <replaceable class="PARAMETER">weight</replaceable> to elements of <replaceable class="PARAMETER">vector</replaceable> that are listed in <replaceable class="PARAMETER">lexemes</replaceable></entry>
9297 <entry><literal>setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A', '{cat,rat}')</literal></entry>
9298 <entry><literal>'cat':3A 'fat':2,4 'rat':5A</literal></entry>
9303 <primary>strip</primary>
9305 <literal><function>strip(<type>tsvector</>)</function></literal>
9307 <entry><type>tsvector</type></entry>
9308 <entry>remove positions and weights from <type>tsvector</></entry>
9309 <entry><literal>strip('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9310 <entry><literal>'cat' 'fat' 'rat'</literal></entry>
9315 <primary>to_tsquery</primary>
9317 <literal><function>to_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
9319 <entry><type>tsquery</type></entry>
9320 <entry>normalize words and convert to <type>tsquery</></entry>
9321 <entry><literal>to_tsquery('english', 'The & Fat & Rats')</literal></entry>
9322 <entry><literal>'fat' & 'rat'</literal></entry>
9327 <primary>to_tsvector</primary>
9329 <literal><function>to_tsvector(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">document</> <type>text</type>)</function></literal>
9331 <entry><type>tsvector</type></entry>
9332 <entry>reduce document text to <type>tsvector</></entry>
9333 <entry><literal>to_tsvector('english', 'The Fat Rats')</literal></entry>
9334 <entry><literal>'fat':2 'rat':3</literal></entry>
9339 <primary>ts_delete</primary>
9341 <literal><function>ts_delete(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">lexeme</replaceable> <type>text</>)</function></literal>
9343 <entry><type>tsvector</type></entry>
9344 <entry>remove given <replaceable class="PARAMETER">lexeme</replaceable> from <replaceable class="PARAMETER">vector</replaceable></entry>
9345 <entry><literal>ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, 'fat')</literal></entry>
9346 <entry><literal>'cat':3 'rat':5A</literal></entry>
9350 <!-- previous indexterm entry covers this too -->
9351 <literal><function>ts_delete(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">lexemes</replaceable> <type>text[]</>)</function></literal>
9353 <entry><type>tsvector</type></entry>
9354 <entry>remove any occurrence of lexemes in <replaceable class="PARAMETER">lexemes</replaceable> from <replaceable class="PARAMETER">vector</replaceable></entry>
9355 <entry><literal>ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, ARRAY['fat','rat'])</literal></entry>
9356 <entry><literal>'cat':3</literal></entry>
9361 <primary>ts_filter</primary>
9363 <literal><function>ts_filter(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">weights</replaceable> <type>"char"[]</>)</function></literal>
9365 <entry><type>tsvector</type></entry>
9366 <entry>Select only elements with given <replaceable class="PARAMETER">weights</replaceable> from <replaceable class="PARAMETER">vector</replaceable></entry>
9367 <entry><literal>ts_filter('fat:2,4 cat:3b rat:5A'::tsvector, '{a,b}')</literal></entry>
9368 <entry><literal>'cat':3B 'rat':5A</literal></entry>
9373 <primary>ts_headline</primary>
9375 <literal><function>ts_headline(<optional> <replaceable class="PARAMETER">config</replaceable> <type>regconfig</>, </optional> <replaceable class="PARAMETER">document</replaceable> <type>text</>, <replaceable class="PARAMETER">query</replaceable> <type>tsquery</> <optional>, <replaceable class="PARAMETER">options</replaceable> <type>text</> </optional>)</function></literal>
9377 <entry><type>text</type></entry>
9378 <entry>display a query match</entry>
9379 <entry><literal>ts_headline('x y z', 'z'::tsquery)</literal></entry>
9380 <entry><literal>x y <b>z</b></literal></entry>
9385 <primary>ts_rank</primary>
9387 <literal><function>ts_rank(<optional> <replaceable class="PARAMETER">weights</replaceable> <type>float4[]</>, </optional> <replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">query</replaceable> <type>tsquery</> <optional>, <replaceable class="PARAMETER">normalization</replaceable> <type>integer</> </optional>)</function></literal>
9389 <entry><type>float4</type></entry>
9390 <entry>rank document for query</entry>
9391 <entry><literal>ts_rank(textsearch, query)</literal></entry>
9392 <entry><literal>0.818</literal></entry>
9397 <primary>ts_rank_cd</primary>
9399 <literal><function>ts_rank_cd(<optional> <replaceable class="PARAMETER">weights</replaceable> <type>float4[]</>, </optional> <replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">query</replaceable> <type>tsquery</> <optional>, <replaceable class="PARAMETER">normalization</replaceable> <type>integer</> </optional>)</function></literal>
9401 <entry><type>float4</type></entry>
9402 <entry>rank document for query using cover density</entry>
9403 <entry><literal>ts_rank_cd('{0.1, 0.2, 0.4, 1.0}', textsearch, query)</literal></entry>
9404 <entry><literal>2.01317</literal></entry>
9409 <primary>ts_rewrite</primary>
9411 <literal><function>ts_rewrite(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">target</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">substitute</replaceable> <type>tsquery</>)</function></literal>
9413 <entry><type>tsquery</type></entry>
9414 <entry>replace <replaceable>target</> with <replaceable>substitute</>
9415 within query</entry>
9416 <entry><literal>ts_rewrite('a & b'::tsquery, 'a'::tsquery, 'foo|bar'::tsquery)</literal></entry>
9417 <entry><literal>'b' & ( 'foo' | 'bar' )</literal></entry>
9420 <entry><literal><function>ts_rewrite(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">select</replaceable> <type>text</>)</function></literal></entry>
9421 <entry><type>tsquery</type></entry>
9422 <entry>replace using targets and substitutes from a <command>SELECT</> command</entry>
9423 <entry><literal>SELECT ts_rewrite('a & b'::tsquery, 'SELECT t,s FROM aliases')</literal></entry>
9424 <entry><literal>'b' & ( 'foo' | 'bar' )</literal></entry>
9429 <primary>tsquery_phrase</primary>
9431 <literal><function>tsquery_phrase(<replaceable class="PARAMETER">query1</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">query2</replaceable> <type>tsquery</>)</function></literal>
9433 <entry><type>tsquery</type></entry>
9434 <entry>make query that searches for <replaceable>query1</> followed
9435 by <replaceable>query2</> (same as <literal><-></>
9437 <entry><literal>tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'))</literal></entry>
9438 <entry><literal>'fat' <-> 'cat'</literal></entry>
9442 <literal><function>tsquery_phrase(<replaceable class="PARAMETER">query1</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">query2</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">distance</replaceable> <type>integer</>)</function></literal>
9444 <entry><type>tsquery</type></entry>
9445 <entry>make query that searches for <replaceable>query1</> followed by
9446 <replaceable>query2</> at maximum distance <replaceable>distance</></entry>
9447 <entry><literal>tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'), 10)</literal></entry>
9448 <entry><literal>'fat' <10> 'cat'</literal></entry>
9453 <primary>tsvector_to_array</primary>
9455 <literal><function>tsvector_to_array(<type>tsvector</>)</function></literal>
9457 <entry><type>text[]</type></entry>
9458 <entry>convert <type>tsvector</> to array of lexemes</entry>
9459 <entry><literal>tsvector_to_array('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9460 <entry><literal>{cat,fat,rat}</literal></entry>
9465 <primary>tsvector_update_trigger</primary>
9467 <literal><function>tsvector_update_trigger()</function></literal>
9469 <entry><type>trigger</type></entry>
9470 <entry>trigger function for automatic <type>tsvector</> column update</entry>
9471 <entry><literal>CREATE TRIGGER ... tsvector_update_trigger(tsvcol, 'pg_catalog.swedish', title, body)</literal></entry>
9472 <entry><literal></literal></entry>
9477 <primary>tsvector_update_trigger_column</primary>
9479 <literal><function>tsvector_update_trigger_column()</function></literal>
9481 <entry><type>trigger</type></entry>
9482 <entry>trigger function for automatic <type>tsvector</> column update</entry>
9483 <entry><literal>CREATE TRIGGER ... tsvector_update_trigger_column(tsvcol, configcol, title, body)</literal></entry>
9484 <entry><literal></literal></entry>
9489 <primary>unnest</primary>
9490 <secondary>for tsvector</secondary>
9492 <literal><function>unnest(<type>tsvector</>, OUT <replaceable class="PARAMETER">lexeme</> <type>text</>, OUT <replaceable class="PARAMETER">positions</> <type>smallint[]</>, OUT <replaceable class="PARAMETER">weights</> <type>text</>)</function></literal>
9494 <entry><type>setof record</type></entry>
9495 <entry>expand a tsvector to a set of rows</entry>
9496 <entry><literal>unnest('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9497 <entry><literal>(cat,{3},{D}) ...</literal></entry>
9505 All the text search functions that accept an optional <type>regconfig</>
9506 argument will use the configuration specified by
9507 <xref linkend="guc-default-text-search-config">
9508 when that argument is omitted.
9514 <xref linkend="textsearch-functions-debug-table">
9515 are listed separately because they are not usually used in everyday text
9516 searching operations. They are helpful for development and debugging
9517 of new text search configurations.
9520 <table id="textsearch-functions-debug-table">
9521 <title>Text Search Debugging Functions</title>
9525 <entry>Function</entry>
9526 <entry>Return Type</entry>
9527 <entry>Description</entry>
9528 <entry>Example</entry>
9529 <entry>Result</entry>
9536 <primary>ts_debug</primary>
9538 <literal><function>ts_debug(<optional> <replaceable class="PARAMETER">config</replaceable> <type>regconfig</>, </optional> <replaceable class="PARAMETER">document</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">alias</> <type>text</>, OUT <replaceable class="PARAMETER">description</> <type>text</>, OUT <replaceable class="PARAMETER">token</> <type>text</>, OUT <replaceable class="PARAMETER">dictionaries</> <type>regdictionary[]</>, OUT <replaceable class="PARAMETER">dictionary</> <type>regdictionary</>, OUT <replaceable class="PARAMETER">lexemes</> <type>text[]</>)</function></literal>
9540 <entry><type>setof record</type></entry>
9541 <entry>test a configuration</entry>
9542 <entry><literal>ts_debug('english', 'The Brightest supernovaes')</literal></entry>
9543 <entry><literal>(asciiword,"Word, all ASCII",The,{english_stem},english_stem,{}) ...</literal></entry>
9548 <primary>ts_lexize</primary>
9550 <literal><function>ts_lexize(<replaceable class="PARAMETER">dict</replaceable> <type>regdictionary</>, <replaceable class="PARAMETER">token</replaceable> <type>text</>)</function></literal>
9552 <entry><type>text[]</type></entry>
9553 <entry>test a dictionary</entry>
9554 <entry><literal>ts_lexize('english_stem', 'stars')</literal></entry>
9555 <entry><literal>{star}</literal></entry>
9560 <primary>ts_parse</primary>
9562 <literal><function>ts_parse(<replaceable class="PARAMETER">parser_name</replaceable> <type>text</>, <replaceable class="PARAMETER">document</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">token</> <type>text</>)</function></literal>
9564 <entry><type>setof record</type></entry>
9565 <entry>test a parser</entry>
9566 <entry><literal>ts_parse('default', 'foo - bar')</literal></entry>
9567 <entry><literal>(1,foo) ...</literal></entry>
9570 <entry><literal><function>ts_parse(<replaceable class="PARAMETER">parser_oid</replaceable> <type>oid</>, <replaceable class="PARAMETER">document</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">token</> <type>text</>)</function></literal></entry>
9571 <entry><type>setof record</type></entry>
9572 <entry>test a parser</entry>
9573 <entry><literal>ts_parse(3722, 'foo - bar')</literal></entry>
9574 <entry><literal>(1,foo) ...</literal></entry>
9579 <primary>ts_token_type</primary>
9581 <literal><function>ts_token_type(<replaceable class="PARAMETER">parser_name</> <type>text</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">alias</> <type>text</>, OUT <replaceable class="PARAMETER">description</> <type>text</>)</function></literal>
9583 <entry><type>setof record</type></entry>
9584 <entry>get token types defined by parser</entry>
9585 <entry><literal>ts_token_type('default')</literal></entry>
9586 <entry><literal>(1,asciiword,"Word, all ASCII") ...</literal></entry>
9589 <entry><literal><function>ts_token_type(<replaceable class="PARAMETER">parser_oid</> <type>oid</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">alias</> <type>text</>, OUT <replaceable class="PARAMETER">description</> <type>text</>)</function></literal></entry>
9590 <entry><type>setof record</type></entry>
9591 <entry>get token types defined by parser</entry>
9592 <entry><literal>ts_token_type(3722)</literal></entry>
9593 <entry><literal>(1,asciiword,"Word, all ASCII") ...</literal></entry>
9598 <primary>ts_stat</primary>
9600 <literal><function>ts_stat(<replaceable class="PARAMETER">sqlquery</replaceable> <type>text</>, <optional> <replaceable class="PARAMETER">weights</replaceable> <type>text</>, </optional> OUT <replaceable class="PARAMETER">word</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">ndoc</replaceable> <type>integer</>, OUT <replaceable class="PARAMETER">nentry</replaceable> <type>integer</>)</function></literal>
9602 <entry><type>setof record</type></entry>
9603 <entry>get statistics of a <type>tsvector</> column</entry>
9604 <entry><literal>ts_stat('SELECT vector from apod')</literal></entry>
9605 <entry><literal>(foo,10,15) ...</literal></entry>
9614 <sect1 id="functions-xml">
9615 <title>XML Functions</title>
9618 The functions and function-like expressions described in this
9619 section operate on values of type <type>xml</type>. Check <xref
9620 linkend="datatype-xml"> for information about the <type>xml</type>
9621 type. The function-like expressions <function>xmlparse</function>
9622 and <function>xmlserialize</function> for converting to and from
9623 type <type>xml</type> are not repeated here. Use of most of these
9624 functions requires the installation to have been built
9625 with <command>configure --with-libxml</>.
9628 <sect2 id="functions-producing-xml">
9629 <title>Producing XML Content</title>
9632 A set of functions and function-like expressions are available for
9633 producing XML content from SQL data. As such, they are
9634 particularly suitable for formatting query results into XML
9635 documents for processing in client applications.
9639 <title><literal>xmlcomment</literal></title>
9642 <primary>xmlcomment</primary>
9646 <function>xmlcomment</function>(<replaceable>text</replaceable>)
9650 The function <function>xmlcomment</function> creates an XML value
9651 containing an XML comment with the specified text as content.
9652 The text cannot contain <quote><literal>--</literal></quote> or end with a
9653 <quote><literal>-</literal></quote> so that the resulting construct is a valid
9654 XML comment. If the argument is null, the result is null.
9660 SELECT xmlcomment('hello');
9670 <title><literal>xmlconcat</literal></title>
9673 <primary>xmlconcat</primary>
9677 <function>xmlconcat</function>(<replaceable>xml</replaceable><optional>, ...</optional>)
9681 The function <function>xmlconcat</function> concatenates a list
9682 of individual XML values to create a single value containing an
9683 XML content fragment. Null values are omitted; the result is
9684 only null if there are no nonnull arguments.
9690 SELECT xmlconcat('<abc/>', '<bar>foo</bar>');
9693 ----------------------
9694 <abc/><bar>foo</bar>
9699 XML declarations, if present, are combined as follows. If all
9700 argument values have the same XML version declaration, that
9701 version is used in the result, else no version is used. If all
9702 argument values have the standalone declaration value
9703 <quote>yes</quote>, then that value is used in the result. If
9704 all argument values have a standalone declaration value and at
9705 least one is <quote>no</quote>, then that is used in the result.
9706 Else the result will have no standalone declaration. If the
9707 result is determined to require a standalone declaration but no
9708 version declaration, a version declaration with version 1.0 will
9709 be used because XML requires an XML declaration to contain a
9710 version declaration. Encoding declarations are ignored and
9711 removed in all cases.
9717 SELECT xmlconcat('<?xml version="1.1"?><foo/>', '<?xml version="1.1" standalone="no"?><bar/>');
9720 -----------------------------------
9721 <?xml version="1.1"?><foo/><bar/>
9727 <title><literal>xmlelement</literal></title>
9730 <primary>xmlelement</primary>
9734 <function>xmlelement</function>(name <replaceable>name</replaceable> <optional>, xmlattributes(<replaceable>value</replaceable> <optional>AS <replaceable>attname</replaceable></optional> <optional>, ... </optional>)</optional> <optional><replaceable>, content, ...</replaceable></optional>)
9738 The <function>xmlelement</function> expression produces an XML
9739 element with the given name, attributes, and content.
9745 SELECT xmlelement(name foo);
9751 SELECT xmlelement(name foo, xmlattributes('xyz' as bar));
9757 SELECT xmlelement(name foo, xmlattributes(current_date as bar), 'cont', 'ent');
9760 -------------------------------------
9761 <foo bar="2007-01-26">content</foo>
9766 Element and attribute names that are not valid XML names are
9767 escaped by replacing the offending characters by the sequence
9768 <literal>_x<replaceable>HHHH</replaceable>_</literal>, where
9769 <replaceable>HHHH</replaceable> is the character's Unicode
9770 codepoint in hexadecimal notation. For example:
9772 SELECT xmlelement(name "foo$bar", xmlattributes('xyz' as "a&b"));
9775 ----------------------------------
9776 <foo_x0024_bar a_x0026_b="xyz"/>
9781 An explicit attribute name need not be specified if the attribute
9782 value is a column reference, in which case the column's name will
9783 be used as the attribute name by default. In other cases, the
9784 attribute must be given an explicit name. So this example is
9787 CREATE TABLE test (a xml, b xml);
9788 SELECT xmlelement(name test, xmlattributes(a, b)) FROM test;
9792 SELECT xmlelement(name test, xmlattributes('constant'), a, b) FROM test;
9793 SELECT xmlelement(name test, xmlattributes(func(a, b))) FROM test;
9798 Element content, if specified, will be formatted according to
9799 its data type. If the content is itself of type <type>xml</type>,
9800 complex XML documents can be constructed. For example:
9802 SELECT xmlelement(name foo, xmlattributes('xyz' as bar),
9803 xmlelement(name abc),
9805 xmlelement(name xyz));
9808 ----------------------------------------------
9809 <foo bar="xyz"><abc/><!--test--><xyz/></foo>
9812 Content of other types will be formatted into valid XML character
9813 data. This means in particular that the characters <, >,
9814 and & will be converted to entities. Binary data (data type
9815 <type>bytea</type>) will be represented in base64 or hex
9816 encoding, depending on the setting of the configuration parameter
9817 <xref linkend="guc-xmlbinary">. The particular behavior for
9818 individual data types is expected to evolve in order to align the
9819 SQL and PostgreSQL data types with the XML Schema specification,
9820 at which point a more precise description will appear.
9825 <title><literal>xmlforest</literal></title>
9828 <primary>xmlforest</primary>
9832 <function>xmlforest</function>(<replaceable>content</replaceable> <optional>AS <replaceable>name</replaceable></optional> <optional>, ...</optional>)
9836 The <function>xmlforest</function> expression produces an XML
9837 forest (sequence) of elements using the given names and content.
9843 SELECT xmlforest('abc' AS foo, 123 AS bar);
9846 ------------------------------
9847 <foo>abc</foo><bar>123</bar>
9850 SELECT xmlforest(table_name, column_name)
9851 FROM information_schema.columns
9852 WHERE table_schema = 'pg_catalog';
9855 -------------------------------------------------------------------------------------------
9856 <table_name>pg_authid</table_name><column_name>rolname</column_name>
9857 <table_name>pg_authid</table_name><column_name>rolsuper</column_name>
9861 As seen in the second example, the element name can be omitted if
9862 the content value is a column reference, in which case the column
9863 name is used by default. Otherwise, a name must be specified.
9867 Element names that are not valid XML names are escaped as shown
9868 for <function>xmlelement</function> above. Similarly, content
9869 data is escaped to make valid XML content, unless it is already
9870 of type <type>xml</type>.
9874 Note that XML forests are not valid XML documents if they consist
9875 of more than one element, so it might be useful to wrap
9876 <function>xmlforest</function> expressions in
9877 <function>xmlelement</function>.
9882 <title><literal>xmlpi</literal></title>
9885 <primary>xmlpi</primary>
9889 <function>xmlpi</function>(name <replaceable>target</replaceable> <optional>, <replaceable>content</replaceable></optional>)
9893 The <function>xmlpi</function> expression creates an XML
9894 processing instruction. The content, if present, must not
9895 contain the character sequence <literal>?></literal>.
9901 SELECT xmlpi(name php, 'echo "hello world";');
9904 -----------------------------
9905 <?php echo "hello world";?>
9911 <title><literal>xmlroot</literal></title>
9914 <primary>xmlroot</primary>
9918 <function>xmlroot</function>(<replaceable>xml</replaceable>, version <replaceable>text</replaceable> | no value <optional>, standalone yes|no|no value</optional>)
9922 The <function>xmlroot</function> expression alters the properties
9923 of the root node of an XML value. If a version is specified,
9924 it replaces the value in the root node's version declaration; if a
9925 standalone setting is specified, it replaces the value in the
9926 root node's standalone declaration.
9931 SELECT xmlroot(xmlparse(document '<?xml version="1.1"?><content>abc</content>'),
9932 version '1.0', standalone yes);
9935 ----------------------------------------
9936 <?xml version="1.0" standalone="yes"?>
9937 <content>abc</content>
9942 <sect3 id="functions-xml-xmlagg">
9943 <title><literal>xmlagg</literal></title>
9946 <primary>xmlagg</primary>
9950 <function>xmlagg</function>(<replaceable>xml</replaceable>)
9954 The function <function>xmlagg</function> is, unlike the other
9955 functions described here, an aggregate function. It concatenates the
9956 input values to the aggregate function call,
9957 much like <function>xmlconcat</function> does, except that concatenation
9958 occurs across rows rather than across expressions in a single row.
9959 See <xref linkend="functions-aggregate"> for additional information
9960 about aggregate functions.
9966 CREATE TABLE test (y int, x xml);
9967 INSERT INTO test VALUES (1, '<foo>abc</foo>');
9968 INSERT INTO test VALUES (2, '<bar/>');
9969 SELECT xmlagg(x) FROM test;
9971 ----------------------
9972 <foo>abc</foo><bar/>
9977 To determine the order of the concatenation, an <literal>ORDER BY</>
9978 clause may be added to the aggregate call as described in
9979 <xref linkend="syntax-aggregates">. For example:
9982 SELECT xmlagg(x ORDER BY y DESC) FROM test;
9984 ----------------------
9985 <bar/><foo>abc</foo>
9990 The following non-standard approach used to be recommended
9991 in previous versions, and may still be useful in specific
9995 SELECT xmlagg(x) FROM (SELECT * FROM test ORDER BY y DESC) AS tab;
9997 ----------------------
9998 <bar/><foo>abc</foo>
10004 <sect2 id="functions-xml-predicates">
10005 <title>XML Predicates</title>
10008 The expressions described in this section check properties
10009 of <type>xml</type> values.
10013 <title><literal>IS DOCUMENT</literal></title>
10016 <primary>IS DOCUMENT</primary>
10020 <replaceable>xml</replaceable> IS DOCUMENT
10024 The expression <literal>IS DOCUMENT</literal> returns true if the
10025 argument XML value is a proper XML document, false if it is not
10026 (that is, it is a content fragment), or null if the argument is
10027 null. See <xref linkend="datatype-xml"> about the difference
10028 between documents and content fragments.
10032 <sect3 id="xml-exists">
10033 <title><literal>XMLEXISTS</literal></title>
10036 <primary>XMLEXISTS</primary>
10040 <function>XMLEXISTS</function>(<replaceable>text</replaceable> PASSING <optional>BY REF</optional> <replaceable>xml</replaceable> <optional>BY REF</optional>)
10044 The function <function>xmlexists</function> returns true if the
10045 XPath expression in the first argument returns any nodes, and
10046 false otherwise. (If either argument is null, the result is
10053 SELECT xmlexists('//town[text() = ''Toronto'']' PASSING BY REF '<towns><town>Toronto</town><town>Ottawa</town></towns>');
10063 The <literal>BY REF</literal> clauses have no effect in
10064 PostgreSQL, but are allowed for SQL conformance and compatibility
10065 with other implementations. Per SQL standard, the
10066 first <literal>BY REF</literal> is required, the second is
10067 optional. Also note that the SQL standard specifies
10068 the <function>xmlexists</function> construct to take an XQuery
10069 expression as first argument, but PostgreSQL currently only
10070 supports XPath, which is a subset of XQuery.
10074 <sect3 id="xml-is-well-formed">
10075 <title><literal>xml_is_well_formed</literal></title>
10078 <primary>xml_is_well_formed</primary>
10082 <primary>xml_is_well_formed_document</primary>
10086 <primary>xml_is_well_formed_content</primary>
10090 <function>xml_is_well_formed</function>(<replaceable>text</replaceable>)
10091 <function>xml_is_well_formed_document</function>(<replaceable>text</replaceable>)
10092 <function>xml_is_well_formed_content</function>(<replaceable>text</replaceable>)
10096 These functions check whether a <type>text</> string is well-formed XML,
10097 returning a Boolean result.
10098 <function>xml_is_well_formed_document</function> checks for a well-formed
10099 document, while <function>xml_is_well_formed_content</function> checks
10100 for well-formed content. <function>xml_is_well_formed</function> does
10101 the former if the <xref linkend="guc-xmloption"> configuration
10102 parameter is set to <literal>DOCUMENT</>, or the latter if it is set to
10103 <literal>CONTENT</>. This means that
10104 <function>xml_is_well_formed</function> is useful for seeing whether
10105 a simple cast to type <type>xml</> will succeed, whereas the other two
10106 functions are useful for seeing whether the corresponding variants of
10107 <function>XMLPARSE</> will succeed.
10114 SET xmloption TO DOCUMENT;
10115 SELECT xml_is_well_formed('<>');
10117 --------------------
10121 SELECT xml_is_well_formed('<abc/>');
10123 --------------------
10127 SET xmloption TO CONTENT;
10128 SELECT xml_is_well_formed('abc');
10130 --------------------
10134 SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</pg:foo>');
10135 xml_is_well_formed_document
10136 -----------------------------
10140 SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</my:foo>');
10141 xml_is_well_formed_document
10142 -----------------------------
10147 The last example shows that the checks include whether
10148 namespaces are correctly matched.
10153 <sect2 id="functions-xml-processing">
10154 <title>Processing XML</title>
10157 <primary>XPath</primary>
10161 To process values of data type <type>xml</type>, PostgreSQL offers
10162 the functions <function>xpath</function> and
10163 <function>xpath_exists</function>, which evaluate XPath 1.0
10168 <function>xpath</function>(<replaceable>xpath</replaceable>, <replaceable>xml</replaceable> <optional>, <replaceable>nsarray</replaceable></optional>)
10172 The function <function>xpath</function> evaluates the XPath
10173 expression <replaceable>xpath</replaceable> (a <type>text</> value)
10174 against the XML value
10175 <replaceable>xml</replaceable>. It returns an array of XML values
10176 corresponding to the node set produced by the XPath expression.
10177 If the XPath expression returns a scalar value rather than a node set,
10178 a single-element array is returned.
10182 The second argument must be a well formed XML document. In particular,
10183 it must have a single root node element.
10187 The optional third argument of the function is an array of namespace
10188 mappings. This array should be a two-dimensional <type>text</> array with
10189 the length of the second axis being equal to 2 (i.e., it should be an
10190 array of arrays, each of which consists of exactly 2 elements).
10191 The first element of each array entry is the namespace name (alias), the
10192 second the namespace URI. It is not required that aliases provided in
10193 this array be the same as those being used in the XML document itself (in
10194 other words, both in the XML document and in the <function>xpath</function>
10195 function context, aliases are <emphasis>local</>).
10201 SELECT xpath('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
10202 ARRAY[ARRAY['my', 'http://example.com']]);
10212 To deal with default (anonymous) namespaces, do something like this:
10214 SELECT xpath('//mydefns:b/text()', '<a xmlns="http://example.com"><b>test</b></a>',
10215 ARRAY[ARRAY['mydefns', 'http://example.com']]);
10225 <primary>xpath_exists</primary>
10229 <function>xpath_exists</function>(<replaceable>xpath</replaceable>, <replaceable>xml</replaceable> <optional>, <replaceable>nsarray</replaceable></optional>)
10233 The function <function>xpath_exists</function> is a specialized form
10234 of the <function>xpath</function> function. Instead of returning the
10235 individual XML values that satisfy the XPath, this function returns a
10236 Boolean indicating whether the query was satisfied or not. This
10237 function is equivalent to the standard <literal>XMLEXISTS</> predicate,
10238 except that it also offers support for a namespace mapping argument.
10244 SELECT xpath_exists('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
10245 ARRAY[ARRAY['my', 'http://example.com']]);
10255 <sect2 id="functions-xml-mapping">
10256 <title>Mapping Tables to XML</title>
10258 <indexterm zone="functions-xml-mapping">
10259 <primary>XML export</primary>
10263 The following functions map the contents of relational tables to
10264 XML values. They can be thought of as XML export functionality:
10266 table_to_xml(tbl regclass, nulls boolean, tableforest boolean, targetns text)
10267 query_to_xml(query text, nulls boolean, tableforest boolean, targetns text)
10268 cursor_to_xml(cursor refcursor, count int, nulls boolean,
10269 tableforest boolean, targetns text)
10271 The return type of each function is <type>xml</type>.
10275 <function>table_to_xml</function> maps the content of the named
10276 table, passed as parameter <parameter>tbl</parameter>. The
10277 <type>regclass</type> type accepts strings identifying tables using the
10278 usual notation, including optional schema qualifications and
10279 double quotes. <function>query_to_xml</function> executes the
10280 query whose text is passed as parameter
10281 <parameter>query</parameter> and maps the result set.
10282 <function>cursor_to_xml</function> fetches the indicated number of
10283 rows from the cursor specified by the parameter
10284 <parameter>cursor</parameter>. This variant is recommended if
10285 large tables have to be mapped, because the result value is built
10286 up in memory by each function.
10290 If <parameter>tableforest</parameter> is false, then the resulting
10291 XML document looks like this:
10295 <columnname1>data</columnname1>
10296 <columnname2>data</columnname2>
10307 If <parameter>tableforest</parameter> is true, the result is an
10308 XML content fragment that looks like this:
10311 <columnname1>data</columnname1>
10312 <columnname2>data</columnname2>
10322 If no table name is available, that is, when mapping a query or a
10323 cursor, the string <literal>table</literal> is used in the first
10324 format, <literal>row</literal> in the second format.
10328 The choice between these formats is up to the user. The first
10329 format is a proper XML document, which will be important in many
10330 applications. The second format tends to be more useful in the
10331 <function>cursor_to_xml</function> function if the result values are to be
10332 reassembled into one document later on. The functions for
10333 producing XML content discussed above, in particular
10334 <function>xmlelement</function>, can be used to alter the results
10339 The data values are mapped in the same way as described for the
10340 function <function>xmlelement</function> above.
10344 The parameter <parameter>nulls</parameter> determines whether null
10345 values should be included in the output. If true, null values in
10346 columns are represented as:
10348 <columnname xsi:nil="true"/>
10350 where <literal>xsi</literal> is the XML namespace prefix for XML
10351 Schema Instance. An appropriate namespace declaration will be
10352 added to the result value. If false, columns containing null
10353 values are simply omitted from the output.
10357 The parameter <parameter>targetns</parameter> specifies the
10358 desired XML namespace of the result. If no particular namespace
10359 is wanted, an empty string should be passed.
10363 The following functions return XML Schema documents describing the
10364 mappings performed by the corresponding functions above:
10366 table_to_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text)
10367 query_to_xmlschema(query text, nulls boolean, tableforest boolean, targetns text)
10368 cursor_to_xmlschema(cursor refcursor, nulls boolean, tableforest boolean, targetns text)
10370 It is essential that the same parameters are passed in order to
10371 obtain matching XML data mappings and XML Schema documents.
10375 The following functions produce XML data mappings and the
10376 corresponding XML Schema in one document (or forest), linked
10377 together. They can be useful where self-contained and
10378 self-describing results are wanted:
10380 table_to_xml_and_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text)
10381 query_to_xml_and_xmlschema(query text, nulls boolean, tableforest boolean, targetns text)
10386 In addition, the following functions are available to produce
10387 analogous mappings of entire schemas or the entire current
10390 schema_to_xml(schema name, nulls boolean, tableforest boolean, targetns text)
10391 schema_to_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text)
10392 schema_to_xml_and_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text)
10394 database_to_xml(nulls boolean, tableforest boolean, targetns text)
10395 database_to_xmlschema(nulls boolean, tableforest boolean, targetns text)
10396 database_to_xml_and_xmlschema(nulls boolean, tableforest boolean, targetns text)
10399 Note that these potentially produce a lot of data, which needs to
10400 be built up in memory. When requesting content mappings of large
10401 schemas or databases, it might be worthwhile to consider mapping the
10402 tables separately instead, possibly even through a cursor.
10406 The result of a schema content mapping looks like this:
10417 </schemaname>]]></screen>
10419 where the format of a table mapping depends on the
10420 <parameter>tableforest</parameter> parameter as explained above.
10424 The result of a database content mapping looks like this:
10439 </dbname>]]></screen>
10441 where the schema mapping is as above.
10445 As an example of using the output produced by these functions,
10446 <xref linkend="xslt-xml-html"> shows an XSLT stylesheet that
10447 converts the output of
10448 <function>table_to_xml_and_xmlschema</function> to an HTML
10449 document containing a tabular rendition of the table data. In a
10450 similar manner, the results from these functions can be
10451 converted into other XML-based formats.
10454 <figure id="xslt-xml-html">
10455 <title>XSLT Stylesheet for Converting SQL/XML Output to HTML</title>
10456 <programlisting><![CDATA[
10457 <?xml version="1.0"?>
10458 <xsl:stylesheet version="1.0"
10459 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
10460 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
10461 xmlns="http://www.w3.org/1999/xhtml"
10464 <xsl:output method="xml"
10465 doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
10466 doctype-public="-//W3C/DTD XHTML 1.0 Strict//EN"
10469 <xsl:template match="/*">
10470 <xsl:variable name="schema" select="//xsd:schema"/>
10471 <xsl:variable name="tabletypename"
10472 select="$schema/xsd:element[@name=name(current())]/@type"/>
10473 <xsl:variable name="rowtypename"
10474 select="$schema/xsd:complexType[@name=$tabletypename]/xsd:sequence/xsd:element[@name='row']/@type"/>
10478 <title><xsl:value-of select="name(current())"/></title>
10483 <xsl:for-each select="$schema/xsd:complexType[@name=$rowtypename]/xsd:sequence/xsd:element/@name">
10484 <th><xsl:value-of select="."/></th>
10488 <xsl:for-each select="row">
10490 <xsl:for-each select="*">
10491 <td><xsl:value-of select="."/></td>
10501 ]]></programlisting>
10506 <sect1 id="functions-json">
10507 <title>JSON Functions and Operators</title>
10509 <indexterm zone="functions-json">
10510 <primary>JSON</primary>
10511 <secondary>functions and operators</secondary>
10515 <xref linkend="functions-json-op-table"> shows the operators that
10516 are available for use with the two JSON data types (see <xref
10517 linkend="datatype-json">).
10520 <table id="functions-json-op-table">
10521 <title><type>json</> and <type>jsonb</> Operators</title>
10525 <entry>Operator</entry>
10526 <entry>Right Operand Type</entry>
10527 <entry>Description</entry>
10528 <entry>Example</entry>
10529 <entry>Example Result</entry>
10534 <entry><literal>-></literal></entry>
10535 <entry><type>int</type></entry>
10536 <entry>Get JSON array element (indexed from zero, negative
10537 integers count from the end)</entry>
10538 <entry><literal>'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json->2</literal></entry>
10539 <entry><literal>{"c":"baz"}</literal></entry>
10542 <entry><literal>-></literal></entry>
10543 <entry><type>text</type></entry>
10544 <entry>Get JSON object field by key</entry>
10545 <entry><literal>'{"a": {"b":"foo"}}'::json->'a'</literal></entry>
10546 <entry><literal>{"b":"foo"}</literal></entry>
10549 <entry><literal>->></literal></entry>
10550 <entry><type>int</type></entry>
10551 <entry>Get JSON array element as <type>text</></entry>
10552 <entry><literal>'[1,2,3]'::json->>2</literal></entry>
10553 <entry><literal>3</literal></entry>
10556 <entry><literal>->></literal></entry>
10557 <entry><type>text</type></entry>
10558 <entry>Get JSON object field as <type>text</></entry>
10559 <entry><literal>'{"a":1,"b":2}'::json->>'b'</literal></entry>
10560 <entry><literal>2</literal></entry>
10563 <entry><literal>#></literal></entry>
10564 <entry><type>text[]</type></entry>
10565 <entry>Get JSON object at specified path</entry>
10566 <entry><literal>'{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}'</literal></entry>
10567 <entry><literal>{"c": "foo"}</literal></entry>
10570 <entry><literal>#>></literal></entry>
10571 <entry><type>text[]</type></entry>
10572 <entry>Get JSON object at specified path as <type>text</></entry>
10573 <entry><literal>'{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'</literal></entry>
10574 <entry><literal>3</literal></entry>
10582 There are parallel variants of these operators for both the
10583 <type>json</type> and <type>jsonb</type> types.
10584 The field/element/path extraction operators
10585 return the same type as their left-hand input (either <type>json</type>
10586 or <type>jsonb</type>), except for those specified as
10587 returning <type>text</>, which coerce the value to text.
10588 The field/element/path extraction operators return NULL, rather than
10589 failing, if the JSON input does not have the right structure to match
10590 the request; for example if no such element exists. The
10591 field/element/path extraction operators that accept integer JSON
10592 array subscripts all support negative subscripting from the end of
10597 The standard comparison operators shown in <xref
10598 linkend="functions-comparison-op-table"> are available for
10599 <type>jsonb</type>, but not for <type>json</type>. They follow the
10600 ordering rules for B-tree operations outlined at <xref
10601 linkend="json-indexing">.
10604 Some further operators also exist only for <type>jsonb</type>, as shown
10605 in <xref linkend="functions-jsonb-op-table">.
10606 Many of these operators can be indexed by
10607 <type>jsonb</> operator classes. For a full description of
10608 <type>jsonb</> containment and existence semantics, see <xref
10609 linkend="json-containment">. <xref linkend="json-indexing">
10610 describes how these operators can be used to effectively index
10611 <type>jsonb</> data.
10613 <table id="functions-jsonb-op-table">
10614 <title>Additional <type>jsonb</> Operators</title>
10618 <entry>Operator</entry>
10619 <entry>Right Operand Type</entry>
10620 <entry>Description</entry>
10621 <entry>Example</entry>
10626 <entry><literal>@></literal></entry>
10627 <entry><type>jsonb</type></entry>
10628 <entry>Does the left JSON value contain the right JSON
10629 path/value entries at the top level?</entry>
10630 <entry><literal>'{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonb</literal></entry>
10633 <entry><literal><@</literal></entry>
10634 <entry><type>jsonb</type></entry>
10635 <entry>Are the left JSON path/value entries contained at the top level within
10636 the right JSON value?</entry>
10637 <entry><literal>'{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb</literal></entry>
10640 <entry><literal>?</literal></entry>
10641 <entry><type>text</type></entry>
10642 <entry>Does the <emphasis>string</emphasis> exist as a top-level
10643 key within the JSON value?</entry>
10644 <entry><literal>'{"a":1, "b":2}'::jsonb ? 'b'</literal></entry>
10647 <entry><literal>?|</literal></entry>
10648 <entry><type>text[]</type></entry>
10649 <entry>Do any of these array <emphasis>strings</emphasis>
10650 exist as top-level keys?</entry>
10651 <entry><literal>'{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']</literal></entry>
10654 <entry><literal>?&</literal></entry>
10655 <entry><type>text[]</type></entry>
10656 <entry>Do all of these array <emphasis>strings</emphasis> exist
10657 as top-level keys?</entry>
10658 <entry><literal>'["a", "b"]'::jsonb ?& array['a', 'b']</literal></entry>
10661 <entry><literal>||</literal></entry>
10662 <entry><type>jsonb</type></entry>
10663 <entry>Concatenate two <type>jsonb</type> values into a new <type>jsonb</type> value</entry>
10664 <entry><literal>'["a", "b"]'::jsonb || '["c", "d"]'::jsonb</literal></entry>
10667 <entry><literal>-</literal></entry>
10668 <entry><type>text</type></entry>
10669 <entry>Delete key/value pair or <emphasis>string</emphasis>
10670 element from left operand. Key/value pairs are matched based
10671 on their key value.</entry>
10672 <entry><literal>'{"a": "b"}'::jsonb - 'a' </literal></entry>
10675 <entry><literal>-</literal></entry>
10676 <entry><type>integer</type></entry>
10677 <entry>Delete the array element with specified index (Negative
10678 integers count from the end). Throws an error if top level
10679 container is not an array.</entry>
10680 <entry><literal>'["a", "b"]'::jsonb - 1 </literal></entry>
10683 <entry><literal>#-</literal></entry>
10684 <entry><type>text[]</type></entry>
10685 <entry>Delete the field or element with specified path (for
10686 JSON arrays, negative integers count from the end)</entry>
10687 <entry><literal>'["a", {"b":1}]'::jsonb #- '{1,b}'</literal></entry>
10695 The <literal>||</> operator concatenates the elements at the top level of
10696 each of its operands. It does not operate recursively. For example, if
10697 both operands are objects with a common key field name, the value of the
10698 field in the result will just be the value from the right hand operand.
10703 <xref linkend="functions-json-creation-table"> shows the functions that are
10704 available for creating <type>json</type> and <type>jsonb</type> values.
10705 (There are no equivalent functions for <type>jsonb</>, of the <literal>row_to_json</>
10706 and <literal>array_to_json</> functions. However, the <literal>to_jsonb</>
10707 function supplies much the same functionality as these functions would.)
10711 <primary>to_json</primary>
10714 <primary>array_to_json</primary>
10717 <primary>row_to_json</primary>
10720 <primary>json_build_array</primary>
10723 <primary>json_build_object</primary>
10726 <primary>json_object</primary>
10729 <primary>to_jsonb</primary>
10732 <primary>jsonb_build_array</primary>
10735 <primary>jsonb_build_object</primary>
10738 <primary>jsonb_object</primary>
10741 <table id="functions-json-creation-table">
10742 <title>JSON Creation Functions</title>
10746 <entry>Function</entry>
10747 <entry>Description</entry>
10748 <entry>Example</entry>
10749 <entry>Example Result</entry>
10754 <entry><para><literal>to_json(anyelement)</literal>
10755 </para><para><literal>to_jsonb(anyelement)</literal>
10758 Returns the value as <type>json</> or <type>jsonb</>.
10759 Arrays and composites are converted
10760 (recursively) to arrays and objects; otherwise, if there is a cast
10761 from the type to <type>json</type>, the cast function will be used to
10762 perform the conversion; otherwise, a scalar value is produced.
10763 For any scalar type other than a number, a Boolean, or a null value,
10764 the text representation will be used, in such a fashion that it is a
10765 valid <type>json</> or <type>jsonb</> value.
10767 <entry><literal>to_json('Fred said "Hi."'::text)</literal></entry>
10768 <entry><literal>"Fred said \"Hi.\""</literal></entry>
10772 <literal>array_to_json(anyarray [, pretty_bool])</literal>
10775 Returns the array as a JSON array. A PostgreSQL multidimensional array
10776 becomes a JSON array of arrays. Line feeds will be added between
10777 dimension-1 elements if <parameter>pretty_bool</parameter> is true.
10779 <entry><literal>array_to_json('{{1,5},{99,100}}'::int[])</literal></entry>
10780 <entry><literal>[[1,5],[99,100]]</literal></entry>
10784 <literal>row_to_json(record [, pretty_bool])</literal>
10787 Returns the row as a JSON object. Line feeds will be added between
10788 level-1 elements if <parameter>pretty_bool</parameter> is true.
10790 <entry><literal>row_to_json(row(1,'foo'))</literal></entry>
10791 <entry><literal>{"f1":1,"f2":"foo"}</literal></entry>
10794 <entry><para><literal>json_build_array(VARIADIC "any")</literal>
10795 </para><para><literal>jsonb_build_array(VARIADIC "any")</literal>
10798 Builds a possibly-heterogeneously-typed JSON array out of a variadic
10801 <entry><literal>json_build_array(1,2,'3',4,5)</literal></entry>
10802 <entry><literal>[1, 2, "3", 4, 5]</literal></entry>
10805 <entry><para><literal>json_build_object(VARIADIC "any")</literal>
10806 </para><para><literal>jsonb_build_object(VARIADIC "any")</literal>
10809 Builds a JSON object out of a variadic argument list. By
10810 convention, the argument list consists of alternating
10813 <entry><literal>json_build_object('foo',1,'bar',2)</literal></entry>
10814 <entry><literal>{"foo": 1, "bar": 2}</literal></entry>
10817 <entry><para><literal>json_object(text[])</literal>
10818 </para><para><literal>jsonb_object(text[])</literal>
10821 Builds a JSON object out of a text array. The array must have either
10822 exactly one dimension with an even number of members, in which case
10823 they are taken as alternating key/value pairs, or two dimensions
10824 such that each inner array has exactly two elements, which
10825 are taken as a key/value pair.
10827 <entry><para><literal>json_object('{a, 1, b, "def", c, 3.5}')</></para>
10828 <para><literal>json_object('{{a, 1},{b, "def"},{c, 3.5}}')</></para></entry>
10829 <entry><literal>{"a": "1", "b": "def", "c": "3.5"}</literal></entry>
10832 <entry><para><literal>json_object(keys text[], values text[])</literal>
10833 </para><para><literal>jsonb_object(keys text[], values text[])</literal>
10836 This form of <function>json_object</> takes keys and values pairwise from two separate
10837 arrays. In all other respects it is identical to the one-argument form.
10839 <entry><literal>json_object('{a, b}', '{1,2}')</literal></entry>
10840 <entry><literal>{"a": "1", "b": "2"}</literal></entry>
10848 <function>array_to_json</> and <function>row_to_json</> have the same
10849 behavior as <function>to_json</> except for offering a pretty-printing
10850 option. The behavior described for <function>to_json</> likewise applies
10851 to each individual value converted by the other JSON creation functions.
10857 The <xref linkend="hstore"> extension has a cast
10858 from <type>hstore</type> to <type>json</type>, so that
10859 <type>hstore</type> values converted via the JSON creation functions
10860 will be represented as JSON objects, not as primitive string values.
10865 <xref linkend="functions-json-processing-table"> shows the functions that
10866 are available for processing <type>json</type> and <type>jsonb</type> values.
10870 <primary>json_array_length</primary>
10873 <primary>jsonb_array_length</primary>
10876 <primary>json_each</primary>
10879 <primary>jsonb_each</primary>
10882 <primary>json_each_text</primary>
10885 <primary>jsonb_each_text</primary>
10888 <primary>json_extract_path</primary>
10891 <primary>jsonb_extract_path</primary>
10894 <primary>json_extract_path_text</primary>
10897 <primary>jsonb_extract_path_text</primary>
10900 <primary>json_object_keys</primary>
10903 <primary>jsonb_object_keys</primary>
10906 <primary>json_populate_record</primary>
10909 <primary>jsonb_populate_record</primary>
10912 <primary>json_populate_recordset</primary>
10915 <primary>jsonb_populate_recordset</primary>
10918 <primary>json_array_elements</primary>
10921 <primary>jsonb_array_elements</primary>
10924 <primary>json_array_elements_text</primary>
10927 <primary>jsonb_array_elements_text</primary>
10930 <primary>json_typeof</primary>
10933 <primary>jsonb_typeof</primary>
10936 <primary>json_to_record</primary>
10939 <primary>jsonb_to_record</primary>
10942 <primary>json_to_recordset</primary>
10945 <primary>jsonb_to_recordset</primary>
10948 <primary>json_strip_nulls</primary>
10951 <primary>jsonb_strip_nulls</primary>
10954 <primary>jsonb_set</primary>
10957 <primary>jsonb_insert</primary>
10960 <primary>jsonb_pretty</primary>
10963 <table id="functions-json-processing-table">
10964 <title>JSON Processing Functions</title>
10968 <entry>Function</entry>
10969 <entry>Return Type</entry>
10970 <entry>Description</entry>
10971 <entry>Example</entry>
10972 <entry>Example Result</entry>
10977 <entry><para><literal>json_array_length(json)</literal>
10978 </para><para><literal>jsonb_array_length(jsonb)</literal>
10980 <entry><type>int</type></entry>
10982 Returns the number of elements in the outermost JSON array.
10984 <entry><literal>json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]')</literal></entry>
10985 <entry><literal>5</literal></entry>
10988 <entry><para><literal>json_each(json)</literal>
10989 </para><para><literal>jsonb_each(jsonb)</literal>
10991 <entry><para><literal>setof key text, value json</literal>
10992 </para><para><literal>setof key text, value jsonb</literal>
10995 Expands the outermost JSON object into a set of key/value pairs.
10997 <entry><literal>select * from json_each('{"a":"foo", "b":"bar"}')</literal></entry>
11008 <entry><para><literal>json_each_text(json)</literal>
11009 </para><para><literal>jsonb_each_text(jsonb)</literal>
11011 <entry><type>setof key text, value text</type></entry>
11013 Expands the outermost JSON object into a set of key/value pairs. The
11014 returned values will be of type <type>text</>.
11016 <entry><literal>select * from json_each_text('{"a":"foo", "b":"bar"}')</literal></entry>
11027 <entry><para><literal>json_extract_path(from_json json, VARIADIC path_elems text[])</literal>
11028 </para><para><literal>jsonb_extract_path(from_json jsonb, VARIADIC path_elems text[])</literal>
11030 <entry><para><type>json</type></para><para><type>jsonb</type>
11033 Returns JSON value pointed to by <replaceable>path_elems</replaceable>
11034 (equivalent to <literal>#></literal> operator).
11036 <entry><literal>json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4')</literal></entry>
11037 <entry><literal>{"f5":99,"f6":"foo"}</literal></entry>
11040 <entry><para><literal>json_extract_path_text(from_json json, VARIADIC path_elems text[])</literal>
11041 </para><para><literal>jsonb_extract_path_text(from_json jsonb, VARIADIC path_elems text[])</literal>
11043 <entry><type>text</type></entry>
11045 Returns JSON value pointed to by <replaceable>path_elems</replaceable>
11047 (equivalent to <literal>#>></literal> operator).
11049 <entry><literal>json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4', 'f6')</literal></entry>
11050 <entry><literal>foo</literal></entry>
11053 <entry><para><literal>json_object_keys(json)</literal>
11054 </para><para><literal>jsonb_object_keys(jsonb)</literal>
11056 <entry><type>setof text</type></entry>
11058 Returns set of keys in the outermost JSON object.
11060 <entry><literal>json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')</literal></entry>
11071 <entry><para><literal>json_populate_record(base anyelement, from_json json)</literal>
11072 </para><para><literal>jsonb_populate_record(base anyelement, from_json jsonb)</literal>
11074 <entry><type>anyelement</type></entry>
11076 Expands the object in <replaceable>from_json</replaceable> to a row
11077 whose columns match the record type defined by <replaceable>base</>
11080 <entry><literal>select * from json_populate_record(null::myrowtype, '{"a":1,"b":2}')</literal></entry>
11090 <entry><para><literal>json_populate_recordset(base anyelement, from_json json)</literal>
11091 </para><para><literal>jsonb_populate_recordset(base anyelement, from_json jsonb)</literal>
11093 <entry><type>setof anyelement</type></entry>
11095 Expands the outermost array of objects
11096 in <replaceable>from_json</replaceable> to a set of rows whose
11097 columns match the record type defined by <replaceable>base</> (see
11100 <entry><literal>select * from json_populate_recordset(null::myrowtype, '[{"a":1,"b":2},{"a":3,"b":4}]')</literal></entry>
11111 <entry><para><literal>json_array_elements(json)</literal>
11112 </para><para><literal>jsonb_array_elements(jsonb)</literal>
11114 <entry><para><type>setof json</type>
11115 </para><para><type>setof jsonb</type>
11118 Expands a JSON array to a set of JSON values.
11120 <entry><literal>select * from json_array_elements('[1,true, [2,false]]')</literal></entry>
11132 <entry><para><literal>json_array_elements_text(json)</literal>
11133 </para><para><literal>jsonb_array_elements_text(jsonb)</literal>
11135 <entry><type>setof text</type></entry>
11137 Expands a JSON array to a set of <type>text</> values.
11139 <entry><literal>select * from json_array_elements_text('["foo", "bar"]')</literal></entry>
11150 <entry><para><literal>json_typeof(json)</literal>
11151 </para><para><literal>jsonb_typeof(jsonb)</literal>
11153 <entry><type>text</type></entry>
11155 Returns the type of the outermost JSON value as a text string.
11157 <literal>object</>, <literal>array</>, <literal>string</>, <literal>number</>,
11158 <literal>boolean</>, and <literal>null</>.
11160 <entry><literal>json_typeof('-123.4')</literal></entry>
11161 <entry><literal>number</literal></entry>
11164 <entry><para><literal>json_to_record(json)</literal>
11165 </para><para><literal>jsonb_to_record(jsonb)</literal>
11167 <entry><type>record</type></entry>
11169 Builds an arbitrary record from a JSON object (see note below). As
11170 with all functions returning <type>record</>, the caller must
11171 explicitly define the structure of the record with an <literal>AS</>
11174 <entry><literal>select * from json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}') as x(a int, b text, d text) </literal></entry>
11184 <entry><para><literal>json_to_recordset(json)</literal>
11185 </para><para><literal>jsonb_to_recordset(jsonb)</literal>
11187 <entry><type>setof record</type></entry>
11189 Builds an arbitrary set of records from a JSON array of objects (see
11190 note below). As with all functions returning <type>record</>, the
11191 caller must explicitly define the structure of the record with
11192 an <literal>AS</> clause.
11194 <entry><literal>select * from json_to_recordset('[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]') as x(a int, b text);</literal></entry>
11205 <entry><para><literal>json_strip_nulls(from_json json)</literal>
11206 </para><para><literal>jsonb_strip_nulls(from_json jsonb)</literal>
11208 <entry><para><type>json</type></para><para><type>jsonb</type></para></entry>
11210 Returns <replaceable>from_json</replaceable>
11211 with all object fields that have null values omitted. Other null values
11214 <entry><literal>json_strip_nulls('[{"f1":1,"f2":null},2,null,3]')</literal></entry>
11215 <entry><literal>[{"f1":1},2,null,3]</literal></entry>
11218 <entry><para><literal>jsonb_set(target jsonb, path text[], new_value jsonb<optional>, <parameter>create_missing</parameter> <type>boolean</type></optional>)</literal>
11220 <entry><para><type>jsonb</type></para></entry>
11222 Returns <replaceable>target</replaceable>
11223 with the section designated by <replaceable>path</replaceable>
11224 replaced by <replaceable>new_value</replaceable>, or with
11225 <replaceable>new_value</replaceable> added if
11226 <replaceable>create_missing</replaceable> is true ( default is
11227 <literal>true</>) and the item
11228 designated by <replaceable>path</replaceable> does not exist.
11229 As with the path orientated operators, negative integers that
11230 appear in <replaceable>path</replaceable> count from the end
11233 <entry><para><literal>jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}','[2,3,4]', false)</literal>
11234 </para><para><literal>jsonb_set('[{"f1":1,"f2":null},2]', '{0,f3}','[2,3,4]')</literal>
11236 <entry><para><literal>[{"f1":[2,3,4],"f2":null},2,null,3]</literal>
11237 </para><para><literal>[{"f1": 1, "f2": null, "f3": [2, 3, 4]}, 2]</literal>
11243 jsonb_insert(target jsonb, path text[], new_value jsonb, <optional><parameter>insert_after</parameter> <type>boolean</type></optional>)
11246 <entry><para><type>jsonb</type></para></entry>
11248 Returns <replaceable>target</replaceable> with
11249 <replaceable>new_value</replaceable> inserted. If
11250 <replaceable>target</replaceable> section designated by
11251 <replaceable>path</replaceable> is in a JSONB array,
11252 <replaceable>new_value</replaceable> will be inserted before target or
11253 after if <replaceable>insert_after</replaceable> is true (default is
11254 <literal>false</>). If <replaceable>target</replaceable> section
11255 designated by <replaceable>path</replaceable> is in JSONB object,
11256 <replaceable>new_value</replaceable> will be inserted only if
11257 <replaceable>target</replaceable> does not exist. As with the path
11258 orientated operators, negative integers that appear in
11259 <replaceable>path</replaceable> count from the end of JSON arrays.
11263 jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"')
11266 jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"', true)
11269 <entry><para><literal>{"a": [0, "new_value", 1, 2]}</literal>
11270 </para><para><literal>{"a": [0, 1, "new_value", 2]}</literal>
11274 <entry><para><literal>jsonb_pretty(from_json jsonb)</literal>
11276 <entry><para><type>text</type></para></entry>
11278 Returns <replaceable>from_json</replaceable>
11279 as indented JSON text.
11281 <entry><literal>jsonb_pretty('[{"f1":1,"f2":null},2,null,3]')</literal></entry>
11302 Many of these functions and operators will convert Unicode escapes in
11303 JSON strings to the appropriate single character. This is a non-issue
11304 if the input is type <type>jsonb</>, because the conversion was already
11305 done; but for <type>json</> input, this may result in throwing an error,
11306 as noted in <xref linkend="datatype-json">.
11312 In <function>json_populate_record</>, <function>json_populate_recordset</>,
11313 <function>json_to_record</> and <function>json_to_recordset</>,
11314 type coercion from the JSON is <quote>best effort</> and may not result
11315 in desired values for some types. JSON keys are matched to
11316 identical column names in the target row type. JSON fields that do not
11317 appear in the target row type will be omitted from the output, and
11318 target columns that do not match any JSON field will simply be NULL.
11324 All the items of the <literal>path</> parameter of <literal>jsonb_set</>
11325 as well as <literal>jsonb_insert</> except the last item must be present
11326 in the <literal>target</>. If <literal>create_missing</> is false, all
11327 items of the <literal>path</> parameter of <literal>jsonb_set</> must be
11328 present. If these conditions are not met the <literal>target</> is
11329 returned unchanged.
11332 If the last path item is an object key, it will be created if it
11333 is absent and given the new value. If the last path item is an array
11334 index, if it is positive the item to set is found by counting from
11335 the left, and if negative by counting from the right - <literal>-1</>
11336 designates the rightmost element, and so on.
11337 If the item is out of the range -array_length .. array_length -1,
11338 and create_missing is true, the new value is added at the beginning
11339 of the array if the item is negative, and at the end of the array if
11346 The <literal>json_typeof</> function's <literal>null</> return value
11347 should not be confused with a SQL NULL. While
11348 calling <literal>json_typeof('null'::json)</> will
11349 return <literal>null</>, calling <literal>json_typeof(NULL::json)</>
11350 will return a SQL NULL.
11356 If the argument to <literal>json_strip_nulls</> contains duplicate
11357 field names in any object, the result could be semantically somewhat
11358 different, depending on the order in which they occur. This is not an
11359 issue for <literal>jsonb_strip_nulls</> since <type>jsonb</type> values never have
11360 duplicate object field names.
11365 See also <xref linkend="functions-aggregate"> for the aggregate
11366 function <function>json_agg</function> which aggregates record
11367 values as JSON, and the aggregate function
11368 <function>json_object_agg</function> which aggregates pairs of values
11369 into a JSON object, and their <type>jsonb</type> equivalents,
11370 <function>jsonb_agg</> and <function>jsonb_object_agg</>.
11375 <sect1 id="functions-sequence">
11376 <title>Sequence Manipulation Functions</title>
11379 <primary>sequence</primary>
11382 <primary>nextval</primary>
11385 <primary>currval</primary>
11388 <primary>lastval</primary>
11391 <primary>setval</primary>
11395 This section describes functions for operating on <firstterm>sequence
11396 objects</firstterm>, also called sequence generators or just sequences.
11397 Sequence objects are special single-row tables created with <xref
11398 linkend="sql-createsequence">.
11399 Sequence objects are commonly used to generate unique identifiers
11400 for rows of a table. The sequence functions, listed in <xref
11401 linkend="functions-sequence-table">, provide simple, multiuser-safe
11402 methods for obtaining successive sequence values from sequence
11406 <table id="functions-sequence-table">
11407 <title>Sequence Functions</title>
11410 <row><entry>Function</entry> <entry>Return Type</entry> <entry>Description</entry></row>
11415 <entry><literal><function>currval(<type>regclass</type>)</function></literal></entry>
11416 <entry><type>bigint</type></entry>
11417 <entry>Return value most recently obtained with
11418 <function>nextval</function> for specified sequence</entry>
11421 <entry><literal><function>lastval()</function></literal></entry>
11422 <entry><type>bigint</type></entry>
11423 <entry>Return value most recently obtained with
11424 <function>nextval</function> for any sequence</entry>
11427 <entry><literal><function>nextval(<type>regclass</type>)</function></literal></entry>
11428 <entry><type>bigint</type></entry>
11429 <entry>Advance sequence and return new value</entry>
11432 <entry><literal><function>setval(<type>regclass</type>, <type>bigint</type>)</function></literal></entry>
11433 <entry><type>bigint</type></entry>
11434 <entry>Set sequence's current value</entry>
11437 <entry><literal><function>setval(<type>regclass</type>, <type>bigint</type>, <type>boolean</type>)</function></literal></entry>
11438 <entry><type>bigint</type></entry>
11439 <entry>Set sequence's current value and <literal>is_called</literal> flag</entry>
11446 The sequence to be operated on by a sequence function is specified by
11447 a <type>regclass</> argument, which is simply the OID of the sequence in the
11448 <structname>pg_class</> system catalog. You do not have to look up the
11449 OID by hand, however, since the <type>regclass</> data type's input
11450 converter will do the work for you. Just write the sequence name enclosed
11451 in single quotes so that it looks like a literal constant. For
11452 compatibility with the handling of ordinary
11453 <acronym>SQL</acronym> names, the string will be converted to lower case
11454 unless it contains double quotes around the sequence name. Thus:
11456 nextval('foo') <lineannotation>operates on sequence <literal>foo</literal></>
11457 nextval('FOO') <lineannotation>operates on sequence <literal>foo</literal></>
11458 nextval('"Foo"') <lineannotation>operates on sequence <literal>Foo</literal></>
11460 The sequence name can be schema-qualified if necessary:
11462 nextval('myschema.foo') <lineannotation>operates on <literal>myschema.foo</literal></>
11463 nextval('"myschema".foo') <lineannotation>same as above</lineannotation>
11464 nextval('foo') <lineannotation>searches search path for <literal>foo</literal></>
11466 See <xref linkend="datatype-oid"> for more information about
11472 Before <productname>PostgreSQL</productname> 8.1, the arguments of the
11473 sequence functions were of type <type>text</>, not <type>regclass</>, and
11474 the above-described conversion from a text string to an OID value would
11475 happen at run time during each call. For backward compatibility, this
11476 facility still exists, but internally it is now handled as an implicit
11477 coercion from <type>text</> to <type>regclass</> before the function is
11482 When you write the argument of a sequence function as an unadorned
11483 literal string, it becomes a constant of type <type>regclass</>.
11484 Since this is really just an OID, it will track the originally
11485 identified sequence despite later renaming, schema reassignment,
11486 etc. This <quote>early binding</> behavior is usually desirable for
11487 sequence references in column defaults and views. But sometimes you might
11488 want <quote>late binding</> where the sequence reference is resolved
11489 at run time. To get late-binding behavior, force the constant to be
11490 stored as a <type>text</> constant instead of <type>regclass</>:
11492 nextval('foo'::text) <lineannotation><literal>foo</literal> is looked up at runtime</>
11494 Note that late binding was the only behavior supported in
11495 <productname>PostgreSQL</productname> releases before 8.1, so you
11496 might need to do this to preserve the semantics of old applications.
11500 Of course, the argument of a sequence function can be an expression
11501 as well as a constant. If it is a text expression then the implicit
11502 coercion will result in a run-time lookup.
11507 The available sequence functions are:
11511 <term><function>nextval</function></term>
11514 Advance the sequence object to its next value and return that
11515 value. This is done atomically: even if multiple sessions
11516 execute <function>nextval</function> concurrently, each will safely receive
11517 a distinct sequence value.
11521 If a sequence object has been created with default parameters,
11522 successive <function>nextval</function> calls will return successive
11523 values beginning with 1. Other behaviors can be obtained by using
11524 special parameters in the <xref linkend="sql-createsequence"> command;
11525 see its command reference page for more information.
11530 To avoid blocking concurrent transactions that obtain numbers from
11531 the same sequence, a <function>nextval</function> operation is never
11532 rolled back; that is, once a value has been fetched it is considered
11533 used and will not be returned again. This is true even if the
11534 surrounding transaction later aborts, or if the calling query ends
11535 up not using the value. For example an <command>INSERT</> with
11536 an <literal>ON CONFLICT</> clause will compute the to-be-inserted
11537 tuple, including doing any required <function>nextval</function>
11538 calls, before detecting any conflict that would cause it to follow
11539 the <literal>ON CONFLICT</> rule instead. Such cases will leave
11540 unused <quote>holes</quote> in the sequence of assigned values.
11541 Thus, <productname>PostgreSQL</> sequence objects <emphasis>cannot
11542 be used to obtain <quote>gapless</> sequences</emphasis>.
11550 <term><function>currval</function></term>
11553 Return the value most recently obtained by <function>nextval</function>
11554 for this sequence in the current session. (An error is
11555 reported if <function>nextval</function> has never been called for this
11556 sequence in this session.) Because this is returning
11557 a session-local value, it gives a predictable answer whether or not
11558 other sessions have executed <function>nextval</function> since the
11559 current session did.
11565 <term><function>lastval</function></term>
11568 Return the value most recently returned by
11569 <function>nextval</> in the current session. This function is
11570 identical to <function>currval</function>, except that instead
11571 of taking the sequence name as an argument it refers to whichever
11572 sequence <function>nextval</function> was most recently applied to
11573 in the current session. It is an error to call
11574 <function>lastval</function> if <function>nextval</function>
11575 has not yet been called in the current session.
11581 <term><function>setval</function></term>
11584 Reset the sequence object's counter value. The two-parameter
11585 form sets the sequence's <literal>last_value</literal> field to the
11586 specified value and sets its <literal>is_called</literal> field to
11587 <literal>true</literal>, meaning that the next
11588 <function>nextval</function> will advance the sequence before
11589 returning a value. The value reported by <function>currval</> is
11590 also set to the specified value. In the three-parameter form,
11591 <literal>is_called</literal> can be set to either <literal>true</literal>
11592 or <literal>false</literal>. <literal>true</> has the same effect as
11593 the two-parameter form. If it is set to <literal>false</literal>, the
11594 next <function>nextval</function> will return exactly the specified
11595 value, and sequence advancement commences with the following
11596 <function>nextval</function>. Furthermore, the value reported by
11597 <function>currval</> is not changed in this case. For example,
11600 SELECT setval('foo', 42); <lineannotation>Next <function>nextval</> will return 43</lineannotation>
11601 SELECT setval('foo', 42, true); <lineannotation>Same as above</lineannotation>
11602 SELECT setval('foo', 42, false); <lineannotation>Next <function>nextval</> will return 42</lineannotation>
11605 The result returned by <function>setval</function> is just the value of its
11610 Because sequences are non-transactional, changes made by
11611 <function>setval</function> are not undone if the transaction rolls
11623 <sect1 id="functions-conditional">
11624 <title>Conditional Expressions</title>
11627 <primary>CASE</primary>
11631 <primary>conditional expression</primary>
11635 This section describes the <acronym>SQL</acronym>-compliant conditional expressions
11636 available in <productname>PostgreSQL</productname>.
11641 If your needs go beyond the capabilities of these conditional
11642 expressions, you might want to consider writing a stored procedure
11643 in a more expressive programming language.
11647 <sect2 id="functions-case">
11648 <title><literal>CASE</></title>
11651 The <acronym>SQL</acronym> <token>CASE</token> expression is a
11652 generic conditional expression, similar to if/else statements in
11653 other programming languages:
11656 CASE WHEN <replaceable>condition</replaceable> THEN <replaceable>result</replaceable>
11657 <optional>WHEN ...</optional>
11658 <optional>ELSE <replaceable>result</replaceable></optional>
11662 <token>CASE</token> clauses can be used wherever
11663 an expression is valid. Each <replaceable>condition</replaceable> is an
11664 expression that returns a <type>boolean</type> result. If the condition's
11665 result is true, the value of the <token>CASE</token> expression is the
11666 <replaceable>result</replaceable> that follows the condition, and the
11667 remainder of the <token>CASE</token> expression is not processed. If the
11668 condition's result is not true, any subsequent <token>WHEN</token> clauses
11669 are examined in the same manner. If no <token>WHEN</token>
11670 <replaceable>condition</replaceable> yields true, the value of the
11671 <token>CASE</> expression is the <replaceable>result</replaceable> of the
11672 <token>ELSE</token> clause. If the <token>ELSE</token> clause is
11673 omitted and no condition is true, the result is null.
11679 SELECT * FROM test;
11689 CASE WHEN a=1 THEN 'one'
11690 WHEN a=2 THEN 'two'
11704 The data types of all the <replaceable>result</replaceable>
11705 expressions must be convertible to a single output type.
11706 See <xref linkend="typeconv-union-case"> for more details.
11710 There is a <quote>simple</> form of <token>CASE</token> expression
11711 that is a variant of the general form above:
11714 CASE <replaceable>expression</replaceable>
11715 WHEN <replaceable>value</replaceable> THEN <replaceable>result</replaceable>
11716 <optional>WHEN ...</optional>
11717 <optional>ELSE <replaceable>result</replaceable></optional>
11722 <replaceable>expression</replaceable> is computed, then compared to
11723 each of the <replaceable>value</replaceable> expressions in the
11724 <token>WHEN</token> clauses until one is found that is equal to it. If
11725 no match is found, the <replaceable>result</replaceable> of the
11726 <token>ELSE</token> clause (or a null value) is returned. This is similar
11727 to the <function>switch</function> statement in C.
11731 The example above can be written using the simple
11732 <token>CASE</token> syntax:
11735 CASE a WHEN 1 THEN 'one'
11750 A <token>CASE</token> expression does not evaluate any subexpressions
11751 that are not needed to determine the result. For example, this is a
11752 possible way of avoiding a division-by-zero failure:
11754 SELECT ... WHERE CASE WHEN x <> 0 THEN y/x > 1.5 ELSE false END;
11760 As described in <xref linkend="syntax-express-eval">, there are various
11761 situations in which subexpressions of an expression are evaluated at
11762 different times, so that the principle that <quote><token>CASE</token>
11763 evaluates only necessary subexpressions</quote> is not ironclad. For
11764 example a constant <literal>1/0</> subexpression will usually result in
11765 a division-by-zero failure at planning time, even if it's within
11766 a <token>CASE</token> arm that would never be entered at run time.
11771 <sect2 id="functions-coalesce-nvl-ifnull">
11772 <title><literal>COALESCE</></title>
11775 <primary>COALESCE</primary>
11779 <primary>NVL</primary>
11783 <primary>IFNULL</primary>
11787 <function>COALESCE</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
11791 The <function>COALESCE</function> function returns the first of its
11792 arguments that is not null. Null is returned only if all arguments
11793 are null. It is often used to substitute a default value for
11794 null values when data is retrieved for display, for example:
11796 SELECT COALESCE(description, short_description, '(none)') ...
11798 This returns <varname>description</> if it is not null, otherwise
11799 <varname>short_description</> if it is not null, otherwise <literal>(none)</>.
11803 Like a <token>CASE</token> expression, <function>COALESCE</function> only
11804 evaluates the arguments that are needed to determine the result;
11805 that is, arguments to the right of the first non-null argument are
11806 not evaluated. This SQL-standard function provides capabilities similar
11807 to <function>NVL</> and <function>IFNULL</>, which are used in some other
11812 <sect2 id="functions-nullif">
11813 <title><literal>NULLIF</></title>
11816 <primary>NULLIF</primary>
11820 <function>NULLIF</function>(<replaceable>value1</replaceable>, <replaceable>value2</replaceable>)
11824 The <function>NULLIF</function> function returns a null value if
11825 <replaceable>value1</replaceable> equals <replaceable>value2</replaceable>;
11826 otherwise it returns <replaceable>value1</replaceable>.
11827 This can be used to perform the inverse operation of the
11828 <function>COALESCE</function> example given above:
11830 SELECT NULLIF(value, '(none)') ...
11834 In this example, if <literal>value</literal> is <literal>(none)</>,
11835 null is returned, otherwise the value of <literal>value</literal>
11841 <sect2 id="functions-greatest-least">
11842 <title><literal>GREATEST</literal> and <literal>LEAST</literal></title>
11845 <primary>GREATEST</primary>
11848 <primary>LEAST</primary>
11852 <function>GREATEST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
11855 <function>LEAST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
11859 The <function>GREATEST</> and <function>LEAST</> functions select the
11860 largest or smallest value from a list of any number of expressions.
11861 The expressions must all be convertible to a common data type, which
11862 will be the type of the result
11863 (see <xref linkend="typeconv-union-case"> for details). NULL values
11864 in the list are ignored. The result will be NULL only if all the
11865 expressions evaluate to NULL.
11869 Note that <function>GREATEST</> and <function>LEAST</> are not in
11870 the SQL standard, but are a common extension. Some other databases
11871 make them return NULL if any argument is NULL, rather than only when
11877 <sect1 id="functions-array">
11878 <title>Array Functions and Operators</title>
11881 <xref linkend="array-operators-table"> shows the operators
11882 available for array types.
11885 <table id="array-operators-table">
11886 <title>Array Operators</title>
11890 <entry>Operator</entry>
11891 <entry>Description</entry>
11892 <entry>Example</entry>
11893 <entry>Result</entry>
11898 <entry> <literal>=</literal> </entry>
11899 <entry>equal</entry>
11900 <entry><literal>ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3]</literal></entry>
11901 <entry><literal>t</literal></entry>
11905 <entry> <literal><></literal> </entry>
11906 <entry>not equal</entry>
11907 <entry><literal>ARRAY[1,2,3] <> ARRAY[1,2,4]</literal></entry>
11908 <entry><literal>t</literal></entry>
11912 <entry> <literal><</literal> </entry>
11913 <entry>less than</entry>
11914 <entry><literal>ARRAY[1,2,3] < ARRAY[1,2,4]</literal></entry>
11915 <entry><literal>t</literal></entry>
11919 <entry> <literal>></literal> </entry>
11920 <entry>greater than</entry>
11921 <entry><literal>ARRAY[1,4,3] > ARRAY[1,2,4]</literal></entry>
11922 <entry><literal>t</literal></entry>
11926 <entry> <literal><=</literal> </entry>
11927 <entry>less than or equal</entry>
11928 <entry><literal>ARRAY[1,2,3] <= ARRAY[1,2,3]</literal></entry>
11929 <entry><literal>t</literal></entry>
11933 <entry> <literal>>=</literal> </entry>
11934 <entry>greater than or equal</entry>
11935 <entry><literal>ARRAY[1,4,3] >= ARRAY[1,4,3]</literal></entry>
11936 <entry><literal>t</literal></entry>
11940 <entry> <literal>@></literal> </entry>
11941 <entry>contains</entry>
11942 <entry><literal>ARRAY[1,4,3] @> ARRAY[3,1]</literal></entry>
11943 <entry><literal>t</literal></entry>
11947 <entry> <literal><@</literal> </entry>
11948 <entry>is contained by</entry>
11949 <entry><literal>ARRAY[2,7] <@ ARRAY[1,7,4,2,6]</literal></entry>
11950 <entry><literal>t</literal></entry>
11954 <entry> <literal>&&</literal> </entry>
11955 <entry>overlap (have elements in common)</entry>
11956 <entry><literal>ARRAY[1,4,3] && ARRAY[2,1]</literal></entry>
11957 <entry><literal>t</literal></entry>
11961 <entry> <literal>||</literal> </entry>
11962 <entry>array-to-array concatenation</entry>
11963 <entry><literal>ARRAY[1,2,3] || ARRAY[4,5,6]</literal></entry>
11964 <entry><literal>{1,2,3,4,5,6}</literal></entry>
11968 <entry> <literal>||</literal> </entry>
11969 <entry>array-to-array concatenation</entry>
11970 <entry><literal>ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9]]</literal></entry>
11971 <entry><literal>{{1,2,3},{4,5,6},{7,8,9}}</literal></entry>
11975 <entry> <literal>||</literal> </entry>
11976 <entry>element-to-array concatenation</entry>
11977 <entry><literal>3 || ARRAY[4,5,6]</literal></entry>
11978 <entry><literal>{3,4,5,6}</literal></entry>
11982 <entry> <literal>||</literal> </entry>
11983 <entry>array-to-element concatenation</entry>
11984 <entry><literal>ARRAY[4,5,6] || 7</literal></entry>
11985 <entry><literal>{4,5,6,7}</literal></entry>
11992 Array comparisons compare the array contents element-by-element,
11993 using the default B-tree comparison function for the element data type.
11994 In multidimensional arrays the elements are visited in row-major order
11995 (last subscript varies most rapidly).
11996 If the contents of two arrays are equal but the dimensionality is
11997 different, the first difference in the dimensionality information
11998 determines the sort order. (This is a change from versions of
11999 <productname>PostgreSQL</> prior to 8.2: older versions would claim
12000 that two arrays with the same contents were equal, even if the
12001 number of dimensions or subscript ranges were different.)
12005 See <xref linkend="arrays"> for more details about array operator
12006 behavior. See <xref linkend="indexes-types"> for more details about
12007 which operators support indexed operations.
12011 <xref linkend="array-functions-table"> shows the functions
12012 available for use with array types. See <xref linkend="arrays">
12013 for more information and examples of the use of these functions.
12017 <primary>array_append</primary>
12020 <primary>array_cat</primary>
12023 <primary>array_ndims</primary>
12026 <primary>array_dims</primary>
12029 <primary>array_fill</primary>
12032 <primary>array_length</primary>
12035 <primary>array_lower</primary>
12038 <primary>array_position</primary>
12041 <primary>array_positions</primary>
12044 <primary>array_prepend</primary>
12047 <primary>array_remove</primary>
12050 <primary>array_replace</primary>
12053 <primary>array_to_string</primary>
12056 <primary>array_upper</primary>
12059 <primary>cardinality</primary>
12062 <primary>string_to_array</primary>
12065 <primary>unnest</primary>
12068 <table id="array-functions-table">
12069 <title>Array Functions</title>
12073 <entry>Function</entry>
12074 <entry>Return Type</entry>
12075 <entry>Description</entry>
12076 <entry>Example</entry>
12077 <entry>Result</entry>
12084 <function>array_append</function>(<type>anyarray</type>, <type>anyelement</type>)
12087 <entry><type>anyarray</type></entry>
12088 <entry>append an element to the end of an array</entry>
12089 <entry><literal>array_append(ARRAY[1,2], 3)</literal></entry>
12090 <entry><literal>{1,2,3}</literal></entry>
12095 <function>array_cat</function>(<type>anyarray</type>, <type>anyarray</type>)
12098 <entry><type>anyarray</type></entry>
12099 <entry>concatenate two arrays</entry>
12100 <entry><literal>array_cat(ARRAY[1,2,3], ARRAY[4,5])</literal></entry>
12101 <entry><literal>{1,2,3,4,5}</literal></entry>
12106 <function>array_ndims</function>(<type>anyarray</type>)
12109 <entry><type>int</type></entry>
12110 <entry>returns the number of dimensions of the array</entry>
12111 <entry><literal>array_ndims(ARRAY[[1,2,3], [4,5,6]])</literal></entry>
12112 <entry><literal>2</literal></entry>
12117 <function>array_dims</function>(<type>anyarray</type>)
12120 <entry><type>text</type></entry>
12121 <entry>returns a text representation of array's dimensions</entry>
12122 <entry><literal>array_dims(ARRAY[[1,2,3], [4,5,6]])</literal></entry>
12123 <entry><literal>[1:2][1:3]</literal></entry>
12128 <function>array_fill</function>(<type>anyelement</type>, <type>int[]</type>,
12129 <optional>, <type>int[]</type></optional>)
12132 <entry><type>anyarray</type></entry>
12133 <entry>returns an array initialized with supplied value and
12134 dimensions, optionally with lower bounds other than 1</entry>
12135 <entry><literal>array_fill(7, ARRAY[3], ARRAY[2])</literal></entry>
12136 <entry><literal>[2:4]={7,7,7}</literal></entry>
12141 <function>array_length</function>(<type>anyarray</type>, <type>int</type>)
12144 <entry><type>int</type></entry>
12145 <entry>returns the length of the requested array dimension</entry>
12146 <entry><literal>array_length(array[1,2,3], 1)</literal></entry>
12147 <entry><literal>3</literal></entry>
12152 <function>array_lower</function>(<type>anyarray</type>, <type>int</type>)
12155 <entry><type>int</type></entry>
12156 <entry>returns lower bound of the requested array dimension</entry>
12157 <entry><literal>array_lower('[0:2]={1,2,3}'::int[], 1)</literal></entry>
12158 <entry><literal>0</literal></entry>
12163 <function>array_position</function>(<type>anyarray</type>, <type>anyelement</type> <optional>, <type>int</type></optional>)
12166 <entry><type>int</type></entry>
12167 <entry>returns the subscript of the first occurrence of the second
12168 argument in the array, starting at the element indicated by the third
12169 argument or at the first element (array must be one-dimensional)</entry>
12170 <entry><literal>array_position(ARRAY['sun','mon','tue','wed','thu','fri','sat'], 'mon')</literal></entry>
12171 <entry><literal>2</literal></entry>
12176 <function>array_positions</function>(<type>anyarray</type>, <type>anyelement</type>)
12179 <entry><type>int[]</type></entry>
12180 <entry>returns an array of subscripts of all occurrences of the second
12181 argument in the array given as first argument (array must be
12182 one-dimensional)</entry>
12183 <entry><literal>array_positions(ARRAY['A','A','B','A'], 'A')</literal></entry>
12184 <entry><literal>{1,2,4}</literal></entry>
12189 <function>array_prepend</function>(<type>anyelement</type>, <type>anyarray</type>)
12192 <entry><type>anyarray</type></entry>
12193 <entry>append an element to the beginning of an array</entry>
12194 <entry><literal>array_prepend(1, ARRAY[2,3])</literal></entry>
12195 <entry><literal>{1,2,3}</literal></entry>
12200 <function>array_remove</function>(<type>anyarray</type>, <type>anyelement</type>)
12203 <entry><type>anyarray</type></entry>
12204 <entry>remove all elements equal to the given value from the array
12205 (array must be one-dimensional)</entry>
12206 <entry><literal>array_remove(ARRAY[1,2,3,2], 2)</literal></entry>
12207 <entry><literal>{1,3}</literal></entry>
12212 <function>array_replace</function>(<type>anyarray</type>, <type>anyelement</type>, <type>anyelement</type>)
12215 <entry><type>anyarray</type></entry>
12216 <entry>replace each array element equal to the given value with a new value</entry>
12217 <entry><literal>array_replace(ARRAY[1,2,5,4], 5, 3)</literal></entry>
12218 <entry><literal>{1,2,3,4}</literal></entry>
12223 <function>array_to_string</function>(<type>anyarray</type>, <type>text</type> <optional>, <type>text</type></optional>)
12226 <entry><type>text</type></entry>
12227 <entry>concatenates array elements using supplied delimiter and
12228 optional null string</entry>
12229 <entry><literal>array_to_string(ARRAY[1, 2, 3, NULL, 5], ',', '*')</literal></entry>
12230 <entry><literal>1,2,3,*,5</literal></entry>
12235 <function>array_upper</function>(<type>anyarray</type>, <type>int</type>)
12238 <entry><type>int</type></entry>
12239 <entry>returns upper bound of the requested array dimension</entry>
12240 <entry><literal>array_upper(ARRAY[1,8,3,7], 1)</literal></entry>
12241 <entry><literal>4</literal></entry>
12246 <function>cardinality</function>(<type>anyarray</type>)
12249 <entry><type>int</type></entry>
12250 <entry>returns the total number of elements in the array, or 0 if the array is empty</entry>
12251 <entry><literal>cardinality(ARRAY[[1,2],[3,4]])</literal></entry>
12252 <entry><literal>4</literal></entry>
12257 <function>string_to_array</function>(<type>text</type>, <type>text</type> <optional>, <type>text</type></optional>)
12260 <entry><type>text[]</type></entry>
12261 <entry>splits string into array elements using supplied delimiter and
12262 optional null string</entry>
12263 <entry><literal>string_to_array('xx~^~yy~^~zz', '~^~', 'yy')</literal></entry>
12264 <entry><literal>{xx,NULL,zz}</literal></entry>
12269 <function>unnest</function>(<type>anyarray</type>)
12272 <entry><type>setof anyelement</type></entry>
12273 <entry>expand an array to a set of rows</entry>
12274 <entry><literal>unnest(ARRAY[1,2])</literal></entry>
12275 <entry><literallayout class="monospaced">1
12276 2</literallayout>(2 rows)</entry>
12281 <function>unnest</function>(<type>anyarray</type>, <type>anyarray</type> [, ...])
12284 <entry><type>setof anyelement, anyelement [, ...]</type></entry>
12285 <entry>expand multiple arrays (possibly of different types) to a set
12286 of rows. This is only allowed in the FROM clause; see
12287 <xref linkend="queries-tablefunctions"></entry>
12288 <entry><literal>unnest(ARRAY[1,2],ARRAY['foo','bar','baz'])</literal></entry>
12289 <entry><literallayout class="monospaced">1 foo
12291 NULL baz</literallayout>(3 rows)</entry>
12298 In <function>array_position</function> and <function>array_positions</>,
12299 each array element is compared to the searched value using
12300 <literal>IS NOT DISTINCT FROM</literal> semantics.
12304 In <function>array_position</function>, <literal>NULL</literal> is returned
12305 if the value is not found.
12309 In <function>array_positions</function>, <literal>NULL</literal> is returned
12310 only if the array is <literal>NULL</literal>; if the value is not found in
12311 the array, an empty array is returned instead.
12315 In <function>string_to_array</function>, if the delimiter parameter is
12316 NULL, each character in the input string will become a separate element in
12317 the resulting array. If the delimiter is an empty string, then the entire
12318 input string is returned as a one-element array. Otherwise the input
12319 string is split at each occurrence of the delimiter string.
12323 In <function>string_to_array</function>, if the null-string parameter
12324 is omitted or NULL, none of the substrings of the input will be replaced
12326 In <function>array_to_string</function>, if the null-string parameter
12327 is omitted or NULL, any null elements in the array are simply skipped
12328 and not represented in the output string.
12333 There are two differences in the behavior of <function>string_to_array</>
12334 from pre-9.1 versions of <productname>PostgreSQL</>.
12335 First, it will return an empty (zero-element) array rather than NULL when
12336 the input string is of zero length. Second, if the delimiter string is
12337 NULL, the function splits the input into individual characters, rather
12338 than returning NULL as before.
12343 See also <xref linkend="functions-aggregate"> about the aggregate
12344 function <function>array_agg</function> for use with arrays.
12348 <sect1 id="functions-range">
12349 <title>Range Functions and Operators</title>
12352 See <xref linkend="rangetypes"> for an overview of range types.
12356 <xref linkend="range-operators-table"> shows the operators
12357 available for range types.
12360 <table id="range-operators-table">
12361 <title>Range Operators</title>
12365 <entry>Operator</entry>
12366 <entry>Description</entry>
12367 <entry>Example</entry>
12368 <entry>Result</entry>
12373 <entry> <literal>=</literal> </entry>
12374 <entry>equal</entry>
12375 <entry><literal>int4range(1,5) = '[1,4]'::int4range</literal></entry>
12376 <entry><literal>t</literal></entry>
12380 <entry> <literal><></literal> </entry>
12381 <entry>not equal</entry>
12382 <entry><literal>numrange(1.1,2.2) <> numrange(1.1,2.3)</literal></entry>
12383 <entry><literal>t</literal></entry>
12387 <entry> <literal><</literal> </entry>
12388 <entry>less than</entry>
12389 <entry><literal>int4range(1,10) < int4range(2,3)</literal></entry>
12390 <entry><literal>t</literal></entry>
12394 <entry> <literal>></literal> </entry>
12395 <entry>greater than</entry>
12396 <entry><literal>int4range(1,10) > int4range(1,5)</literal></entry>
12397 <entry><literal>t</literal></entry>
12401 <entry> <literal><=</literal> </entry>
12402 <entry>less than or equal</entry>
12403 <entry><literal>numrange(1.1,2.2) <= numrange(1.1,2.2)</literal></entry>
12404 <entry><literal>t</literal></entry>
12408 <entry> <literal>>=</literal> </entry>
12409 <entry>greater than or equal</entry>
12410 <entry><literal>numrange(1.1,2.2) >= numrange(1.1,2.0)</literal></entry>
12411 <entry><literal>t</literal></entry>
12415 <entry> <literal>@></literal> </entry>
12416 <entry>contains range</entry>
12417 <entry><literal>int4range(2,4) @> int4range(2,3)</literal></entry>
12418 <entry><literal>t</literal></entry>
12422 <entry> <literal>@></literal> </entry>
12423 <entry>contains element</entry>
12424 <entry><literal>'[2011-01-01,2011-03-01)'::tsrange @> '2011-01-10'::timestamp</literal></entry>
12425 <entry><literal>t</literal></entry>
12429 <entry> <literal><@</literal> </entry>
12430 <entry>range is contained by</entry>
12431 <entry><literal>int4range(2,4) <@ int4range(1,7)</literal></entry>
12432 <entry><literal>t</literal></entry>
12436 <entry> <literal><@</literal> </entry>
12437 <entry>element is contained by</entry>
12438 <entry><literal>42 <@ int4range(1,7)</literal></entry>
12439 <entry><literal>f</literal></entry>
12443 <entry> <literal>&&</literal> </entry>
12444 <entry>overlap (have points in common)</entry>
12445 <entry><literal>int8range(3,7) && int8range(4,12)</literal></entry>
12446 <entry><literal>t</literal></entry>
12450 <entry> <literal><<</literal> </entry>
12451 <entry>strictly left of</entry>
12452 <entry><literal>int8range(1,10) << int8range(100,110)</literal></entry>
12453 <entry><literal>t</literal></entry>
12457 <entry> <literal>>></literal> </entry>
12458 <entry>strictly right of</entry>
12459 <entry><literal>int8range(50,60) >> int8range(20,30)</literal></entry>
12460 <entry><literal>t</literal></entry>
12464 <entry> <literal>&<</literal> </entry>
12465 <entry>does not extend to the right of</entry>
12466 <entry><literal>int8range(1,20) &< int8range(18,20)</literal></entry>
12467 <entry><literal>t</literal></entry>
12471 <entry> <literal>&></literal> </entry>
12472 <entry>does not extend to the left of</entry>
12473 <entry><literal>int8range(7,20) &> int8range(5,10)</literal></entry>
12474 <entry><literal>t</literal></entry>
12478 <entry> <literal>-|-</literal> </entry>
12479 <entry>is adjacent to</entry>
12480 <entry><literal>numrange(1.1,2.2) -|- numrange(2.2,3.3)</literal></entry>
12481 <entry><literal>t</literal></entry>
12485 <entry> <literal>+</literal> </entry>
12486 <entry>union</entry>
12487 <entry><literal>numrange(5,15) + numrange(10,20)</literal></entry>
12488 <entry><literal>[5,20)</literal></entry>
12492 <entry> <literal>*</literal> </entry>
12493 <entry>intersection</entry>
12494 <entry><literal>int8range(5,15) * int8range(10,20)</literal></entry>
12495 <entry><literal>[10,15)</literal></entry>
12499 <entry> <literal>-</literal> </entry>
12500 <entry>difference</entry>
12501 <entry><literal>int8range(5,15) - int8range(10,20)</literal></entry>
12502 <entry><literal>[5,10)</literal></entry>
12510 The simple comparison operators <literal><</literal>,
12511 <literal>></literal>, <literal><=</literal>, and
12512 <literal>>=</literal> compare the lower bounds first, and only if those
12513 are equal, compare the upper bounds. These comparisons are not usually
12514 very useful for ranges, but are provided to allow B-tree indexes to be
12515 constructed on ranges.
12519 The left-of/right-of/adjacent operators always return false when an empty
12520 range is involved; that is, an empty range is not considered to be either
12521 before or after any other range.
12525 The union and difference operators will fail if the resulting range would
12526 need to contain two disjoint sub-ranges, as such a range cannot be
12531 <xref linkend="range-functions-table"> shows the functions
12532 available for use with range types.
12536 <primary>lower</primary>
12539 <primary>upper</primary>
12542 <primary>isempty</primary>
12545 <primary>lower_inc</primary>
12548 <primary>upper_inc</primary>
12551 <primary>lower_inf</primary>
12554 <primary>upper_inf</primary>
12557 <table id="range-functions-table">
12558 <title>Range Functions</title>
12562 <entry>Function</entry>
12563 <entry>Return Type</entry>
12564 <entry>Description</entry>
12565 <entry>Example</entry>
12566 <entry>Result</entry>
12573 <function>lower</function>(<type>anyrange</type>)
12576 <entry>range's element type</entry>
12577 <entry>lower bound of range</entry>
12578 <entry><literal>lower(numrange(1.1,2.2))</literal></entry>
12579 <entry><literal>1.1</literal></entry>
12584 <function>upper</function>(<type>anyrange</type>)
12587 <entry>range's element type</entry>
12588 <entry>upper bound of range</entry>
12589 <entry><literal>upper(numrange(1.1,2.2))</literal></entry>
12590 <entry><literal>2.2</literal></entry>
12595 <function>isempty</function>(<type>anyrange</type>)
12598 <entry><type>boolean</type></entry>
12599 <entry>is the range empty?</entry>
12600 <entry><literal>isempty(numrange(1.1,2.2))</literal></entry>
12601 <entry><literal>false</literal></entry>
12606 <function>lower_inc</function>(<type>anyrange</type>)
12609 <entry><type>boolean</type></entry>
12610 <entry>is the lower bound inclusive?</entry>
12611 <entry><literal>lower_inc(numrange(1.1,2.2))</literal></entry>
12612 <entry><literal>true</literal></entry>
12617 <function>upper_inc</function>(<type>anyrange</type>)
12620 <entry><type>boolean</type></entry>
12621 <entry>is the upper bound inclusive?</entry>
12622 <entry><literal>upper_inc(numrange(1.1,2.2))</literal></entry>
12623 <entry><literal>false</literal></entry>
12628 <function>lower_inf</function>(<type>anyrange</type>)
12631 <entry><type>boolean</type></entry>
12632 <entry>is the lower bound infinite?</entry>
12633 <entry><literal>lower_inf('(,)'::daterange)</literal></entry>
12634 <entry><literal>true</literal></entry>
12639 <function>upper_inf</function>(<type>anyrange</type>)
12642 <entry><type>boolean</type></entry>
12643 <entry>is the upper bound infinite?</entry>
12644 <entry><literal>upper_inf('(,)'::daterange)</literal></entry>
12645 <entry><literal>true</literal></entry>
12650 <function>range_merge</function>(<type>anyrange</type>, <type>anyrange</type>)
12653 <entry><type>anyrange</type></entry>
12654 <entry>the smallest range which includes both of the given ranges</entry>
12655 <entry><literal>range_merge('[1,2)'::int4range, '[3,4)'::int4range)</literal></entry>
12656 <entry><literal>[1,4)</literal></entry>
12663 The <function>lower</> and <function>upper</> functions return null
12664 if the range is empty or the requested bound is infinite.
12665 The <function>lower_inc</function>, <function>upper_inc</function>,
12666 <function>lower_inf</function>, and <function>upper_inf</function>
12667 functions all return false for an empty range.
12671 <sect1 id="functions-aggregate">
12672 <title>Aggregate Functions</title>
12674 <indexterm zone="functions-aggregate">
12675 <primary>aggregate function</primary>
12676 <secondary>built-in</secondary>
12680 <firstterm>Aggregate functions</firstterm> compute a single result
12681 from a set of input values. The built-in normal aggregate functions
12683 <xref linkend="functions-aggregate-table"> and
12684 <xref linkend="functions-aggregate-statistics-table">.
12685 The built-in ordered-set aggregate functions
12686 are listed in <xref linkend="functions-orderedset-table"> and
12687 <xref linkend="functions-hypothetical-table">. Grouping operations,
12688 which are closely related to aggregate functions, are listed in
12689 <xref linkend="functions-grouping-table">.
12690 The special syntax considerations for aggregate
12691 functions are explained in <xref linkend="syntax-aggregates">.
12692 Consult <xref linkend="tutorial-agg"> for additional introductory
12696 <table id="functions-aggregate-table">
12697 <title>General-Purpose Aggregate Functions</title>
12702 <entry>Function</entry>
12703 <entry>Argument Type(s)</entry>
12704 <entry>Return Type</entry>
12705 <entry>Partial Mode</entry>
12706 <entry>Description</entry>
12714 <primary>array_agg</primary>
12716 <function>array_agg(<replaceable class="parameter">expression</replaceable>)</function>
12722 array of the argument type
12725 <entry>input values, including nulls, concatenated into an array</entry>
12730 <function>array_agg(<replaceable class="parameter">expression</replaceable>)</function>
12736 same as argument data type
12739 <entry>input arrays concatenated into array of one higher dimension
12740 (inputs must all have same dimensionality,
12741 and cannot be empty or NULL)</entry>
12747 <primary>average</primary>
12750 <primary>avg</primary>
12752 <function>avg(<replaceable class="parameter">expression</replaceable>)</function>
12755 <type>smallint</type>, <type>int</type>,
12756 <type>bigint</type>, <type>real</type>, <type>double
12757 precision</type>, <type>numeric</type>, or <type>interval</type>
12760 <type>numeric</type> for any integer-type argument,
12761 <type>double precision</type> for a floating-point argument,
12762 otherwise the same as the argument data type
12765 <entry>the average (arithmetic mean) of all input values</entry>
12771 <primary>bit_and</primary>
12773 <function>bit_and(<replaceable class="parameter">expression</replaceable>)</function>
12776 <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
12780 same as argument data type
12783 <entry>the bitwise AND of all non-null input values, or null if none</entry>
12789 <primary>bit_or</primary>
12791 <function>bit_or(<replaceable class="parameter">expression</replaceable>)</function>
12794 <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
12798 same as argument data type
12801 <entry>the bitwise OR of all non-null input values, or null if none</entry>
12807 <primary>bool_and</primary>
12809 <function>bool_and(<replaceable class="parameter">expression</replaceable>)</function>
12818 <entry>true if all input values are true, otherwise false</entry>
12824 <primary>bool_or</primary>
12826 <function>bool_or(<replaceable class="parameter">expression</replaceable>)</function>
12835 <entry>true if at least one input value is true, otherwise false</entry>
12841 <primary>count</primary>
12843 <function>count(*)</function>
12846 <entry><type>bigint</type></entry>
12848 <entry>number of input rows</entry>
12852 <entry><function>count(<replaceable class="parameter">expression</replaceable>)</function></entry>
12854 <entry><type>bigint</type></entry>
12857 number of input rows for which the value of <replaceable
12858 class="parameter">expression</replaceable> is not null
12865 <primary>every</primary>
12867 <function>every(<replaceable class="parameter">expression</replaceable>)</function>
12876 <entry>equivalent to <function>bool_and</function></entry>
12882 <primary>json_agg</primary>
12884 <function>json_agg(<replaceable class="parameter">expression</replaceable>)</function>
12893 <entry>aggregates values as a JSON array</entry>
12899 <primary>jsonb_agg</primary>
12901 <function>jsonb_agg(<replaceable class="parameter">expression</replaceable>)</function>
12910 <entry>aggregates values as a JSON array</entry>
12916 <primary>json_object_agg</primary>
12918 <function>json_object_agg(<replaceable class="parameter">name</replaceable>, <replaceable class="parameter">value</replaceable>)</function>
12921 <type>(any, any)</type>
12927 <entry>aggregates name/value pairs as a JSON object</entry>
12933 <primary>jsonb_object_agg</primary>
12935 <function>jsonb_object_agg(<replaceable class="parameter">name</replaceable>, <replaceable class="parameter">value</replaceable>)</function>
12938 <type>(any, any)</type>
12944 <entry>aggregates name/value pairs as a JSON object</entry>
12950 <primary>max</primary>
12952 <function>max(<replaceable class="parameter">expression</replaceable>)</function>
12954 <entry>any numeric, string, date/time, network, or enum type,
12955 or arrays of these types</entry>
12956 <entry>same as argument type</entry>
12959 maximum value of <replaceable
12960 class="parameter">expression</replaceable> across all input
12968 <primary>min</primary>
12970 <function>min(<replaceable class="parameter">expression</replaceable>)</function>
12972 <entry>any numeric, string, date/time, network, or enum type,
12973 or arrays of these types</entry>
12974 <entry>same as argument type</entry>
12977 minimum value of <replaceable
12978 class="parameter">expression</replaceable> across all input
12986 <primary>string_agg</primary>
12989 string_agg(<replaceable class="parameter">expression</replaceable>,
12990 <replaceable class="parameter">delimiter</replaceable>)
12994 (<type>text</type>, <type>text</type>) or (<type>bytea</type>, <type>bytea</type>)
12997 same as argument types
13000 <entry>input values concatenated into a string, separated by delimiter</entry>
13006 <primary>sum</primary>
13008 <function>sum(<replaceable class="parameter">expression</replaceable>)</function>
13011 <type>smallint</type>, <type>int</type>,
13012 <type>bigint</type>, <type>real</type>, <type>double
13013 precision</type>, <type>numeric</type>,
13014 <type>interval</type>, or <type>money</>
13017 <type>bigint</type> for <type>smallint</type> or
13018 <type>int</type> arguments, <type>numeric</type> for
13019 <type>bigint</type> arguments, otherwise the same as the
13023 <entry>sum of <replaceable class="parameter">expression</replaceable> across all input values</entry>
13029 <primary>xmlagg</primary>
13031 <function>xmlagg(<replaceable class="parameter">expression</replaceable>)</function>
13040 <entry>concatenation of XML values (see also <xref linkend="functions-xml-xmlagg">)</entry>
13047 It should be noted that except for <function>count</function>,
13048 these functions return a null value when no rows are selected. In
13049 particular, <function>sum</function> of no rows returns null, not
13050 zero as one might expect, and <function>array_agg</function>
13051 returns null rather than an empty array when there are no input
13052 rows. The <function>coalesce</function> function can be used to
13053 substitute zero or an empty array for null when necessary.
13057 Aggregate functions which support <firstterm>Partial Mode</firstterm>
13058 are eligible to participate in various optimizations, such as parallel
13064 <primary>ANY</primary>
13067 <primary>SOME</primary>
13070 Boolean aggregates <function>bool_and</function> and
13071 <function>bool_or</function> correspond to standard SQL aggregates
13072 <function>every</function> and <function>any</function> or
13073 <function>some</function>.
13074 As for <function>any</function> and <function>some</function>,
13075 it seems that there is an ambiguity built into the standard syntax:
13077 SELECT b1 = ANY((SELECT b2 FROM t2 ...)) FROM t1 ...;
13079 Here <function>ANY</function> can be considered either as introducing
13080 a subquery, or as being an aggregate function, if the subquery
13081 returns one row with a Boolean value.
13082 Thus the standard name cannot be given to these aggregates.
13088 Users accustomed to working with other SQL database management
13089 systems might be disappointed by the performance of the
13090 <function>count</function> aggregate when it is applied to the
13091 entire table. A query like:
13093 SELECT count(*) FROM sometable;
13095 will require effort proportional to the size of the table:
13096 <productname>PostgreSQL</productname> will need to scan either the
13097 entire table or the entirety of an index which includes all rows in
13103 The aggregate functions <function>array_agg</function>,
13104 <function>json_agg</function>, <function>jsonb_agg</function>,
13105 <function>json_object_agg</function>, <function>jsonb_object_agg</function>,
13106 <function>string_agg</function>,
13107 and <function>xmlagg</function>, as well as similar user-defined
13108 aggregate functions, produce meaningfully different result values
13109 depending on the order of the input values. This ordering is
13110 unspecified by default, but can be controlled by writing an
13111 <literal>ORDER BY</> clause within the aggregate call, as shown in
13112 <xref linkend="syntax-aggregates">.
13113 Alternatively, supplying the input values from a sorted subquery
13114 will usually work. For example:
13117 SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;
13120 Beware that this approach can fail if the outer query level contains
13121 additional processing, such as a join, because that might cause the
13122 subquery's output to be reordered before the aggregate is computed.
13126 <xref linkend="functions-aggregate-statistics-table"> shows
13127 aggregate functions typically used in statistical analysis.
13128 (These are separated out merely to avoid cluttering the listing
13129 of more-commonly-used aggregates.) Where the description mentions
13130 <replaceable class="parameter">N</replaceable>, it means the
13131 number of input rows for which all the input expressions are non-null.
13132 In all cases, null is returned if the computation is meaningless,
13133 for example when <replaceable class="parameter">N</replaceable> is zero.
13137 <primary>statistics</primary>
13140 <primary>linear regression</primary>
13143 <table id="functions-aggregate-statistics-table">
13144 <title>Aggregate Functions for Statistics</title>
13149 <entry>Function</entry>
13150 <entry>Argument Type</entry>
13151 <entry>Return Type</entry>
13152 <entry>Partial Mode</entry>
13153 <entry>Description</entry>
13162 <primary>correlation</primary>
13165 <primary>corr</primary>
13167 <function>corr(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13170 <type>double precision</type>
13173 <type>double precision</type>
13176 <entry>correlation coefficient</entry>
13182 <primary>covariance</primary>
13183 <secondary>population</secondary>
13186 <primary>covar_pop</primary>
13188 <function>covar_pop(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13191 <type>double precision</type>
13194 <type>double precision</type>
13197 <entry>population covariance</entry>
13203 <primary>covariance</primary>
13204 <secondary>sample</secondary>
13207 <primary>covar_samp</primary>
13209 <function>covar_samp(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13212 <type>double precision</type>
13215 <type>double precision</type>
13218 <entry>sample covariance</entry>
13224 <primary>regr_avgx</primary>
13226 <function>regr_avgx(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13229 <type>double precision</type>
13232 <type>double precision</type>
13235 <entry>average of the independent variable
13236 (<literal>sum(<replaceable class="parameter">X</replaceable>)/<replaceable class="parameter">N</replaceable></literal>)</entry>
13242 <primary>regr_avgy</primary>
13244 <function>regr_avgy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13247 <type>double precision</type>
13250 <type>double precision</type>
13253 <entry>average of the dependent variable
13254 (<literal>sum(<replaceable class="parameter">Y</replaceable>)/<replaceable class="parameter">N</replaceable></literal>)</entry>
13260 <primary>regr_count</primary>
13262 <function>regr_count(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13265 <type>double precision</type>
13268 <type>bigint</type>
13271 <entry>number of input rows in which both expressions are nonnull</entry>
13277 <primary>regression intercept</primary>
13280 <primary>regr_intercept</primary>
13282 <function>regr_intercept(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13285 <type>double precision</type>
13288 <type>double precision</type>
13291 <entry>y-intercept of the least-squares-fit linear equation
13292 determined by the (<replaceable
13293 class="parameter">X</replaceable>, <replaceable
13294 class="parameter">Y</replaceable>) pairs</entry>
13300 <primary>regr_r2</primary>
13302 <function>regr_r2(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13305 <type>double precision</type>
13308 <type>double precision</type>
13311 <entry>square of the correlation coefficient</entry>
13317 <primary>regression slope</primary>
13320 <primary>regr_slope</primary>
13322 <function>regr_slope(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13325 <type>double precision</type>
13328 <type>double precision</type>
13331 <entry>slope of the least-squares-fit linear equation determined
13332 by the (<replaceable class="parameter">X</replaceable>,
13333 <replaceable class="parameter">Y</replaceable>) pairs</entry>
13339 <primary>regr_sxx</primary>
13341 <function>regr_sxx(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13344 <type>double precision</type>
13347 <type>double precision</type>
13350 <entry><literal>sum(<replaceable
13351 class="parameter">X</replaceable>^2) - sum(<replaceable
13352 class="parameter">X</replaceable>)^2/<replaceable
13353 class="parameter">N</replaceable></literal> (<quote>sum of
13354 squares</quote> of the independent variable)</entry>
13360 <primary>regr_sxy</primary>
13362 <function>regr_sxy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13365 <type>double precision</type>
13368 <type>double precision</type>
13371 <entry><literal>sum(<replaceable
13372 class="parameter">X</replaceable>*<replaceable
13373 class="parameter">Y</replaceable>) - sum(<replaceable
13374 class="parameter">X</replaceable>) * sum(<replaceable
13375 class="parameter">Y</replaceable>)/<replaceable
13376 class="parameter">N</replaceable></literal> (<quote>sum of
13377 products</quote> of independent times dependent
13384 <primary>regr_syy</primary>
13386 <function>regr_syy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13389 <type>double precision</type>
13392 <type>double precision</type>
13395 <entry><literal>sum(<replaceable
13396 class="parameter">Y</replaceable>^2) - sum(<replaceable
13397 class="parameter">Y</replaceable>)^2/<replaceable
13398 class="parameter">N</replaceable></literal> (<quote>sum of
13399 squares</quote> of the dependent variable)</entry>
13405 <primary>standard deviation</primary>
13408 <primary>stddev</primary>
13410 <function>stddev(<replaceable class="parameter">expression</replaceable>)</function>
13413 <type>smallint</type>, <type>int</type>,
13414 <type>bigint</type>, <type>real</type>, <type>double
13415 precision</type>, or <type>numeric</type>
13418 <type>double precision</type> for floating-point arguments,
13419 otherwise <type>numeric</type>
13422 <entry>historical alias for <function>stddev_samp</function></entry>
13428 <primary>standard deviation</primary>
13429 <secondary>population</secondary>
13432 <primary>stddev_pop</primary>
13434 <function>stddev_pop(<replaceable class="parameter">expression</replaceable>)</function>
13437 <type>smallint</type>, <type>int</type>,
13438 <type>bigint</type>, <type>real</type>, <type>double
13439 precision</type>, or <type>numeric</type>
13442 <type>double precision</type> for floating-point arguments,
13443 otherwise <type>numeric</type>
13446 <entry>population standard deviation of the input values</entry>
13452 <primary>standard deviation</primary>
13453 <secondary>sample</secondary>
13456 <primary>stddev_samp</primary>
13458 <function>stddev_samp(<replaceable class="parameter">expression</replaceable>)</function>
13461 <type>smallint</type>, <type>int</type>,
13462 <type>bigint</type>, <type>real</type>, <type>double
13463 precision</type>, or <type>numeric</type>
13466 <type>double precision</type> for floating-point arguments,
13467 otherwise <type>numeric</type>
13470 <entry>sample standard deviation of the input values</entry>
13476 <primary>variance</primary>
13478 <function>variance</function>(<replaceable class="parameter">expression</replaceable>)
13481 <type>smallint</type>, <type>int</type>,
13482 <type>bigint</type>, <type>real</type>, <type>double
13483 precision</type>, or <type>numeric</type>
13486 <type>double precision</type> for floating-point arguments,
13487 otherwise <type>numeric</type>
13490 <entry>historical alias for <function>var_samp</function></entry>
13496 <primary>variance</primary>
13497 <secondary>population</secondary>
13500 <primary>var_pop</primary>
13502 <function>var_pop</function>(<replaceable class="parameter">expression</replaceable>)
13505 <type>smallint</type>, <type>int</type>,
13506 <type>bigint</type>, <type>real</type>, <type>double
13507 precision</type>, or <type>numeric</type>
13510 <type>double precision</type> for floating-point arguments,
13511 otherwise <type>numeric</type>
13514 <entry>population variance of the input values (square of the population standard deviation)</entry>
13520 <primary>variance</primary>
13521 <secondary>sample</secondary>
13524 <primary>var_samp</primary>
13526 <function>var_samp</function>(<replaceable class="parameter">expression</replaceable>)
13529 <type>smallint</type>, <type>int</type>,
13530 <type>bigint</type>, <type>real</type>, <type>double
13531 precision</type>, or <type>numeric</type>
13534 <type>double precision</type> for floating-point arguments,
13535 otherwise <type>numeric</type>
13538 <entry>sample variance of the input values (square of the sample standard deviation)</entry>
13545 <xref linkend="functions-orderedset-table"> shows some
13546 aggregate functions that use the <firstterm>ordered-set aggregate</>
13547 syntax. These functions are sometimes referred to as <quote>inverse
13548 distribution</> functions.
13552 <primary>ordered-set aggregate</primary>
13553 <secondary>built-in</secondary>
13556 <primary>inverse distribution</primary>
13559 <table id="functions-orderedset-table">
13560 <title>Ordered-Set Aggregate Functions</title>
13565 <entry>Function</entry>
13566 <entry>Direct Argument Type(s)</entry>
13567 <entry>Aggregated Argument Type(s)</entry>
13568 <entry>Return Type</entry>
13569 <entry>Partial Mode</entry>
13570 <entry>Description</entry>
13579 <primary>mode</primary>
13580 <secondary>statistical</secondary>
13582 <function>mode() WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13590 same as sort expression
13594 returns the most frequent input value (arbitrarily choosing the first
13595 one if there are multiple equally-frequent results)
13602 <primary>percentile</primary>
13603 <secondary>continuous</secondary>
13606 <primary>median</primary>
13608 <function>percentile_cont(<replaceable class="parameter">fraction</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13611 <type>double precision</type>
13614 <type>double precision</type> or <type>interval</type>
13617 same as sort expression
13621 continuous percentile: returns a value corresponding to the specified
13622 fraction in the ordering, interpolating between adjacent input items if
13629 <function>percentile_cont(<replaceable class="parameter">fractions</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13632 <type>double precision[]</type>
13635 <type>double precision</type> or <type>interval</type>
13638 array of sort expression's type
13642 multiple continuous percentile: returns an array of results matching
13643 the shape of the <literal>fractions</literal> parameter, with each
13644 non-null element replaced by the value corresponding to that percentile
13651 <primary>percentile</primary>
13652 <secondary>discrete</secondary>
13654 <function>percentile_disc(<replaceable class="parameter">fraction</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13657 <type>double precision</type>
13663 same as sort expression
13667 discrete percentile: returns the first input value whose position in
13668 the ordering equals or exceeds the specified fraction
13674 <function>percentile_disc(<replaceable class="parameter">fractions</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13677 <type>double precision[]</type>
13683 array of sort expression's type
13687 multiple discrete percentile: returns an array of results matching the
13688 shape of the <literal>fractions</literal> parameter, with each non-null
13689 element replaced by the input value corresponding to that percentile
13698 All the aggregates listed in <xref linkend="functions-orderedset-table">
13699 ignore null values in their sorted input. For those that take
13700 a <replaceable>fraction</replaceable> parameter, the fraction value must be
13701 between 0 and 1; an error is thrown if not. However, a null fraction value
13702 simply produces a null result.
13706 <primary>hypothetical-set aggregate</primary>
13707 <secondary>built-in</secondary>
13711 Each of the aggregates listed in
13712 <xref linkend="functions-hypothetical-table"> is associated with a
13713 window function of the same name defined in
13714 <xref linkend="functions-window">. In each case, the aggregate result
13715 is the value that the associated window function would have
13716 returned for the <quote>hypothetical</> row constructed from
13717 <replaceable>args</replaceable>, if such a row had been added to the sorted
13718 group of rows computed from the <replaceable>sorted_args</replaceable>.
13721 <table id="functions-hypothetical-table">
13722 <title>Hypothetical-Set Aggregate Functions</title>
13727 <entry>Function</entry>
13728 <entry>Direct Argument Type(s)</entry>
13729 <entry>Aggregated Argument Type(s)</entry>
13730 <entry>Return Type</entry>
13731 <entry>Partial Mode</entry>
13732 <entry>Description</entry>
13741 <primary>rank</primary>
13742 <secondary>hypothetical</secondary>
13744 <function>rank(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
13747 <literal>VARIADIC</> <type>"any"</type>
13750 <literal>VARIADIC</> <type>"any"</type>
13753 <type>bigint</type>
13757 rank of the hypothetical row, with gaps for duplicate rows
13764 <primary>dense_rank</primary>
13765 <secondary>hypothetical</secondary>
13767 <function>dense_rank(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
13770 <literal>VARIADIC</> <type>"any"</type>
13773 <literal>VARIADIC</> <type>"any"</type>
13776 <type>bigint</type>
13780 rank of the hypothetical row, without gaps
13787 <primary>percent_rank</primary>
13788 <secondary>hypothetical</secondary>
13790 <function>percent_rank(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
13793 <literal>VARIADIC</> <type>"any"</type>
13796 <literal>VARIADIC</> <type>"any"</type>
13799 <type>double precision</type>
13803 relative rank of the hypothetical row, ranging from 0 to 1
13810 <primary>cume_dist</primary>
13811 <secondary>hypothetical</secondary>
13813 <function>cume_dist(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
13816 <literal>VARIADIC</> <type>"any"</type>
13819 <literal>VARIADIC</> <type>"any"</type>
13822 <type>double precision</type>
13826 relative rank of the hypothetical row, ranging from
13827 1/<replaceable>N</> to 1
13836 For each of these hypothetical-set aggregates, the list of direct arguments
13837 given in <replaceable>args</replaceable> must match the number and types of
13838 the aggregated arguments given in <replaceable>sorted_args</replaceable>.
13839 Unlike most built-in aggregates, these aggregates are not strict, that is
13840 they do not drop input rows containing nulls. Null values sort according
13841 to the rule specified in the <literal>ORDER BY</> clause.
13844 <table id="functions-grouping-table">
13845 <title>Grouping Operations</title>
13850 <entry>Function</entry>
13851 <entry>Return Type</entry>
13852 <entry>Description</entry>
13861 <primary>GROUPING</primary>
13863 <function>GROUPING(<replaceable class="parameter">args...</replaceable>)</function>
13866 <type>integer</type>
13869 Integer bit mask indicating which arguments are not being included in the current
13878 Grouping operations are used in conjunction with grouping sets (see
13879 <xref linkend="queries-grouping-sets">) to distinguish result rows. The
13880 arguments to the <literal>GROUPING</> operation are not actually evaluated,
13881 but they must match exactly expressions given in the <literal>GROUP BY</>
13882 clause of the associated query level. Bits are assigned with the rightmost
13883 argument being the least-significant bit; each bit is 0 if the corresponding
13884 expression is included in the grouping criteria of the grouping set generating
13885 the result row, and 1 if it is not. For example:
13887 <prompt>=></> <userinput>SELECT * FROM items_sold;</>
13888 make | model | sales
13889 -------+-------+-------
13896 <prompt>=></> <userinput>SELECT make, model, GROUPING(make,model), sum(sales) FROM items_sold GROUP BY ROLLUP(make,model);</>
13897 make | model | grouping | sum
13898 -------+-------+----------+-----
13900 Foo | Tour | 0 | 20
13901 Bar | City | 0 | 15
13902 Bar | Sport | 0 | 5
13912 <sect1 id="functions-window">
13913 <title>Window Functions</title>
13915 <indexterm zone="functions-window">
13916 <primary>window function</primary>
13917 <secondary>built-in</secondary>
13921 <firstterm>Window functions</firstterm> provide the ability to perform
13922 calculations across sets of rows that are related to the current query
13923 row. See <xref linkend="tutorial-window"> for an introduction to this
13924 feature, and <xref linkend="syntax-window-functions"> for syntax
13929 The built-in window functions are listed in
13930 <xref linkend="functions-window-table">. Note that these functions
13931 <emphasis>must</> be invoked using window function syntax; that is an
13932 <literal>OVER</> clause is required.
13936 In addition to these functions, any built-in or user-defined normal
13937 aggregate function (but not ordered-set or hypothetical-set aggregates)
13938 can be used as a window function; see
13939 <xref linkend="functions-aggregate"> for a list of the built-in aggregates.
13940 Aggregate functions act as window functions only when an <literal>OVER</>
13941 clause follows the call; otherwise they act as regular aggregates.
13944 <table id="functions-window-table">
13945 <title>General-Purpose Window Functions</title>
13950 <entry>Function</entry>
13951 <entry>Return Type</entry>
13952 <entry>Description</entry>
13960 <primary>row_number</primary>
13962 <function>row_number()</function>
13965 <type>bigint</type>
13967 <entry>number of the current row within its partition, counting from 1</entry>
13973 <primary>rank</primary>
13975 <function>rank()</function>
13978 <type>bigint</type>
13980 <entry>rank of the current row with gaps; same as <function>row_number</> of its first peer</entry>
13986 <primary>dense_rank</primary>
13988 <function>dense_rank()</function>
13991 <type>bigint</type>
13993 <entry>rank of the current row without gaps; this function counts peer groups</entry>
13999 <primary>percent_rank</primary>
14001 <function>percent_rank()</function>
14004 <type>double precision</type>
14006 <entry>relative rank of the current row: (<function>rank</> - 1) / (total rows - 1)</entry>
14012 <primary>cume_dist</primary>
14014 <function>cume_dist()</function>
14017 <type>double precision</type>
14019 <entry>relative rank of the current row: (number of rows preceding or peer with current row) / (total rows)</entry>
14025 <primary>ntile</primary>
14027 <function>ntile(<replaceable class="parameter">num_buckets</replaceable> <type>integer</>)</function>
14030 <type>integer</type>
14032 <entry>integer ranging from 1 to the argument value, dividing the
14033 partition as equally as possible</entry>
14039 <primary>lag</primary>
14042 lag(<replaceable class="parameter">value</replaceable> <type>anyelement</>
14043 [, <replaceable class="parameter">offset</replaceable> <type>integer</>
14044 [, <replaceable class="parameter">default</replaceable> <type>anyelement</> ]])
14048 <type>same type as <replaceable class="parameter">value</replaceable></type>
14051 returns <replaceable class="parameter">value</replaceable> evaluated at
14052 the row that is <replaceable class="parameter">offset</replaceable>
14053 rows before the current row within the partition; if there is no such
14054 row, instead return <replaceable class="parameter">default</replaceable>
14055 (which must be of the same type as
14056 <replaceable class="parameter">value</replaceable>).
14057 Both <replaceable class="parameter">offset</replaceable> and
14058 <replaceable class="parameter">default</replaceable> are evaluated
14059 with respect to the current row. If omitted,
14060 <replaceable class="parameter">offset</replaceable> defaults to 1 and
14061 <replaceable class="parameter">default</replaceable> to null
14068 <primary>lead</primary>
14071 lead(<replaceable class="parameter">value</replaceable> <type>anyelement</>
14072 [, <replaceable class="parameter">offset</replaceable> <type>integer</>
14073 [, <replaceable class="parameter">default</replaceable> <type>anyelement</> ]])
14077 <type>same type as <replaceable class="parameter">value</replaceable></type>
14080 returns <replaceable class="parameter">value</replaceable> evaluated at
14081 the row that is <replaceable class="parameter">offset</replaceable>
14082 rows after the current row within the partition; if there is no such
14083 row, instead return <replaceable class="parameter">default</replaceable>
14084 (which must be of the same type as
14085 <replaceable class="parameter">value</replaceable>).
14086 Both <replaceable class="parameter">offset</replaceable> and
14087 <replaceable class="parameter">default</replaceable> are evaluated
14088 with respect to the current row. If omitted,
14089 <replaceable class="parameter">offset</replaceable> defaults to 1 and
14090 <replaceable class="parameter">default</replaceable> to null
14097 <primary>first_value</primary>
14099 <function>first_value(<replaceable class="parameter">value</replaceable> <type>any</>)</function>
14102 <type>same type as <replaceable class="parameter">value</replaceable></type>
14105 returns <replaceable class="parameter">value</replaceable> evaluated
14106 at the row that is the first row of the window frame
14113 <primary>last_value</primary>
14115 <function>last_value(<replaceable class="parameter">value</replaceable> <type>any</>)</function>
14118 <type>same type as <replaceable class="parameter">value</replaceable></type>
14121 returns <replaceable class="parameter">value</replaceable> evaluated
14122 at the row that is the last row of the window frame
14129 <primary>nth_value</primary>
14132 nth_value(<replaceable class="parameter">value</replaceable> <type>any</>, <replaceable class="parameter">nth</replaceable> <type>integer</>)
14136 <type>same type as <replaceable class="parameter">value</replaceable></type>
14139 returns <replaceable class="parameter">value</replaceable> evaluated
14140 at the row that is the <replaceable class="parameter">nth</replaceable>
14141 row of the window frame (counting from 1); null if no such row
14149 All of the functions listed in
14150 <xref linkend="functions-window-table"> depend on the sort ordering
14151 specified by the <literal>ORDER BY</> clause of the associated window
14152 definition. Rows that are not distinct in the <literal>ORDER BY</>
14153 ordering are said to be <firstterm>peers</>; the four ranking functions
14154 are defined so that they give the same answer for any two peer rows.
14158 Note that <function>first_value</>, <function>last_value</>, and
14159 <function>nth_value</> consider only the rows within the <quote>window
14160 frame</>, which by default contains the rows from the start of the
14161 partition through the last peer of the current row. This is
14162 likely to give unhelpful results for <function>last_value</> and
14163 sometimes also <function>nth_value</>. You can redefine the frame by
14164 adding a suitable frame specification (<literal>RANGE</> or
14165 <literal>ROWS</>) to the <literal>OVER</> clause.
14166 See <xref linkend="syntax-window-functions"> for more information
14167 about frame specifications.
14171 When an aggregate function is used as a window function, it aggregates
14172 over the rows within the current row's window frame.
14173 An aggregate used with <literal>ORDER BY</> and the default window frame
14174 definition produces a <quote>running sum</> type of behavior, which may or
14175 may not be what's wanted. To obtain
14176 aggregation over the whole partition, omit <literal>ORDER BY</> or use
14177 <literal>ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING</>.
14178 Other frame specifications can be used to obtain other effects.
14183 The SQL standard defines a <literal>RESPECT NULLS</> or
14184 <literal>IGNORE NULLS</> option for <function>lead</>, <function>lag</>,
14185 <function>first_value</>, <function>last_value</>, and
14186 <function>nth_value</>. This is not implemented in
14187 <productname>PostgreSQL</productname>: the behavior is always the
14188 same as the standard's default, namely <literal>RESPECT NULLS</>.
14189 Likewise, the standard's <literal>FROM FIRST</> or <literal>FROM LAST</>
14190 option for <function>nth_value</> is not implemented: only the
14191 default <literal>FROM FIRST</> behavior is supported. (You can achieve
14192 the result of <literal>FROM LAST</> by reversing the <literal>ORDER BY</>
14199 <sect1 id="functions-subquery">
14200 <title>Subquery Expressions</title>
14203 <primary>EXISTS</primary>
14207 <primary>IN</primary>
14211 <primary>NOT IN</primary>
14215 <primary>ANY</primary>
14219 <primary>ALL</primary>
14223 <primary>SOME</primary>
14227 <primary>subquery</primary>
14231 This section describes the <acronym>SQL</acronym>-compliant subquery
14232 expressions available in <productname>PostgreSQL</productname>.
14233 All of the expression forms documented in this section return
14234 Boolean (true/false) results.
14237 <sect2 id="functions-subquery-exists">
14238 <title><literal>EXISTS</literal></title>
14241 EXISTS (<replaceable>subquery</replaceable>)
14245 The argument of <token>EXISTS</token> is an arbitrary <command>SELECT</> statement,
14246 or <firstterm>subquery</firstterm>. The
14247 subquery is evaluated to determine whether it returns any rows.
14248 If it returns at least one row, the result of <token>EXISTS</token> is
14249 <quote>true</>; if the subquery returns no rows, the result of <token>EXISTS</token>
14250 is <quote>false</>.
14254 The subquery can refer to variables from the surrounding query,
14255 which will act as constants during any one evaluation of the subquery.
14259 The subquery will generally only be executed long enough to determine
14260 whether at least one row is returned, not all the way to completion.
14261 It is unwise to write a subquery that has side effects (such as
14262 calling sequence functions); whether the side effects occur
14263 might be unpredictable.
14267 Since the result depends only on whether any rows are returned,
14268 and not on the contents of those rows, the output list of the
14269 subquery is normally unimportant. A common coding convention is
14270 to write all <literal>EXISTS</> tests in the form
14271 <literal>EXISTS(SELECT 1 WHERE ...)</literal>. There are exceptions to
14272 this rule however, such as subqueries that use <token>INTERSECT</token>.
14276 This simple example is like an inner join on <literal>col2</>, but
14277 it produces at most one output row for each <literal>tab1</> row,
14278 even if there are several matching <literal>tab2</> rows:
14282 WHERE EXISTS (SELECT 1 FROM tab2 WHERE col2 = tab1.col2);
14287 <sect2 id="functions-subquery-in">
14288 <title><literal>IN</literal></title>
14291 <replaceable>expression</replaceable> IN (<replaceable>subquery</replaceable>)
14295 The right-hand side is a parenthesized
14296 subquery, which must return exactly one column. The left-hand expression
14297 is evaluated and compared to each row of the subquery result.
14298 The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
14299 The result is <quote>false</> if no equal row is found (including the
14300 case where the subquery returns no rows).
14304 Note that if the left-hand expression yields null, or if there are
14305 no equal right-hand values and at least one right-hand row yields
14306 null, the result of the <token>IN</token> construct will be null, not false.
14307 This is in accordance with SQL's normal rules for Boolean combinations
14312 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14313 be evaluated completely.
14317 <replaceable>row_constructor</replaceable> IN (<replaceable>subquery</replaceable>)
14321 The left-hand side of this form of <token>IN</token> is a row constructor,
14322 as described in <xref linkend="sql-syntax-row-constructors">.
14323 The right-hand side is a parenthesized
14324 subquery, which must return exactly as many columns as there are
14325 expressions in the left-hand row. The left-hand expressions are
14326 evaluated and compared row-wise to each row of the subquery result.
14327 The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
14328 The result is <quote>false</> if no equal row is found (including the
14329 case where the subquery returns no rows).
14333 As usual, null values in the rows are combined per
14334 the normal rules of SQL Boolean expressions. Two rows are considered
14335 equal if all their corresponding members are non-null and equal; the rows
14336 are unequal if any corresponding members are non-null and unequal;
14337 otherwise the result of that row comparison is unknown (null).
14338 If all the per-row results are either unequal or null, with at least one
14339 null, then the result of <token>IN</token> is null.
14343 <sect2 id="functions-subquery-notin">
14344 <title><literal>NOT IN</literal></title>
14347 <replaceable>expression</replaceable> NOT IN (<replaceable>subquery</replaceable>)
14351 The right-hand side is a parenthesized
14352 subquery, which must return exactly one column. The left-hand expression
14353 is evaluated and compared to each row of the subquery result.
14354 The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
14355 are found (including the case where the subquery returns no rows).
14356 The result is <quote>false</> if any equal row is found.
14360 Note that if the left-hand expression yields null, or if there are
14361 no equal right-hand values and at least one right-hand row yields
14362 null, the result of the <token>NOT IN</token> construct will be null, not true.
14363 This is in accordance with SQL's normal rules for Boolean combinations
14368 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14369 be evaluated completely.
14373 <replaceable>row_constructor</replaceable> NOT IN (<replaceable>subquery</replaceable>)
14377 The left-hand side of this form of <token>NOT IN</token> is a row constructor,
14378 as described in <xref linkend="sql-syntax-row-constructors">.
14379 The right-hand side is a parenthesized
14380 subquery, which must return exactly as many columns as there are
14381 expressions in the left-hand row. The left-hand expressions are
14382 evaluated and compared row-wise to each row of the subquery result.
14383 The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
14384 are found (including the case where the subquery returns no rows).
14385 The result is <quote>false</> if any equal row is found.
14389 As usual, null values in the rows are combined per
14390 the normal rules of SQL Boolean expressions. Two rows are considered
14391 equal if all their corresponding members are non-null and equal; the rows
14392 are unequal if any corresponding members are non-null and unequal;
14393 otherwise the result of that row comparison is unknown (null).
14394 If all the per-row results are either unequal or null, with at least one
14395 null, then the result of <token>NOT IN</token> is null.
14399 <sect2 id="functions-subquery-any-some">
14400 <title><literal>ANY</literal>/<literal>SOME</literal></title>
14403 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>subquery</replaceable>)
14404 <replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>subquery</replaceable>)
14408 The right-hand side is a parenthesized
14409 subquery, which must return exactly one column. The left-hand expression
14410 is evaluated and compared to each row of the subquery result using the
14411 given <replaceable>operator</replaceable>, which must yield a Boolean
14413 The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
14414 The result is <quote>false</> if no true result is found (including the
14415 case where the subquery returns no rows).
14419 <token>SOME</token> is a synonym for <token>ANY</token>.
14420 <token>IN</token> is equivalent to <literal>= ANY</literal>.
14424 Note that if there are no successes and at least one right-hand row yields
14425 null for the operator's result, the result of the <token>ANY</token> construct
14426 will be null, not false.
14427 This is in accordance with SQL's normal rules for Boolean combinations
14432 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14433 be evaluated completely.
14437 <replaceable>row_constructor</replaceable> <replaceable>operator</> ANY (<replaceable>subquery</replaceable>)
14438 <replaceable>row_constructor</replaceable> <replaceable>operator</> SOME (<replaceable>subquery</replaceable>)
14442 The left-hand side of this form of <token>ANY</token> is a row constructor,
14443 as described in <xref linkend="sql-syntax-row-constructors">.
14444 The right-hand side is a parenthesized
14445 subquery, which must return exactly as many columns as there are
14446 expressions in the left-hand row. The left-hand expressions are
14447 evaluated and compared row-wise to each row of the subquery result,
14448 using the given <replaceable>operator</replaceable>.
14449 The result of <token>ANY</token> is <quote>true</> if the comparison
14450 returns true for any subquery row.
14451 The result is <quote>false</> if the comparison returns false for every
14452 subquery row (including the case where the subquery returns no
14454 The result is NULL if the comparison does not return true for any row,
14455 and it returns NULL for at least one row.
14459 See <xref linkend="row-wise-comparison"> for details about the meaning
14460 of a row constructor comparison.
14464 <sect2 id="functions-subquery-all">
14465 <title><literal>ALL</literal></title>
14468 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
14472 The right-hand side is a parenthesized
14473 subquery, which must return exactly one column. The left-hand expression
14474 is evaluated and compared to each row of the subquery result using the
14475 given <replaceable>operator</replaceable>, which must yield a Boolean
14477 The result of <token>ALL</token> is <quote>true</> if all rows yield true
14478 (including the case where the subquery returns no rows).
14479 The result is <quote>false</> if any false result is found.
14480 The result is NULL if the comparison does not return false for any row,
14481 and it returns NULL for at least one row.
14485 <token>NOT IN</token> is equivalent to <literal><> ALL</literal>.
14489 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14490 be evaluated completely.
14494 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
14498 The left-hand side of this form of <token>ALL</token> is a row constructor,
14499 as described in <xref linkend="sql-syntax-row-constructors">.
14500 The right-hand side is a parenthesized
14501 subquery, which must return exactly as many columns as there are
14502 expressions in the left-hand row. The left-hand expressions are
14503 evaluated and compared row-wise to each row of the subquery result,
14504 using the given <replaceable>operator</replaceable>.
14505 The result of <token>ALL</token> is <quote>true</> if the comparison
14506 returns true for all subquery rows (including the
14507 case where the subquery returns no rows).
14508 The result is <quote>false</> if the comparison returns false for any
14510 The result is NULL if the comparison does not return false for any
14511 subquery row, and it returns NULL for at least one row.
14515 See <xref linkend="row-wise-comparison"> for details about the meaning
14516 of a row constructor comparison.
14521 <title>Single-row Comparison</title>
14523 <indexterm zone="functions-subquery">
14524 <primary>comparison</primary>
14525 <secondary>subquery result row</secondary>
14529 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> (<replaceable>subquery</replaceable>)
14533 The left-hand side is a row constructor,
14534 as described in <xref linkend="sql-syntax-row-constructors">.
14535 The right-hand side is a parenthesized subquery, which must return exactly
14536 as many columns as there are expressions in the left-hand row. Furthermore,
14537 the subquery cannot return more than one row. (If it returns zero rows,
14538 the result is taken to be null.) The left-hand side is evaluated and
14539 compared row-wise to the single subquery result row.
14543 See <xref linkend="row-wise-comparison"> for details about the meaning
14544 of a row constructor comparison.
14550 <sect1 id="functions-comparisons">
14551 <title>Row and Array Comparisons</title>
14554 <primary>IN</primary>
14558 <primary>NOT IN</primary>
14562 <primary>ANY</primary>
14566 <primary>ALL</primary>
14570 <primary>SOME</primary>
14574 <primary>composite type</primary>
14575 <secondary>comparison</secondary>
14579 <primary>row-wise comparison</primary>
14583 <primary>comparison</primary>
14584 <secondary>composite type</secondary>
14588 <primary>comparison</primary>
14589 <secondary>row constructor</secondary>
14593 <primary>IS DISTINCT FROM</primary>
14597 <primary>IS NOT DISTINCT FROM</primary>
14601 This section describes several specialized constructs for making
14602 multiple comparisons between groups of values. These forms are
14603 syntactically related to the subquery forms of the previous section,
14604 but do not involve subqueries.
14605 The forms involving array subexpressions are
14606 <productname>PostgreSQL</productname> extensions; the rest are
14607 <acronym>SQL</acronym>-compliant.
14608 All of the expression forms documented in this section return
14609 Boolean (true/false) results.
14613 <title><literal>IN</literal></title>
14616 <replaceable>expression</replaceable> IN (<replaceable>value</replaceable> <optional>, ...</optional>)
14620 The right-hand side is a parenthesized list
14621 of scalar expressions. The result is <quote>true</> if the left-hand expression's
14622 result is equal to any of the right-hand expressions. This is a shorthand
14626 <replaceable>expression</replaceable> = <replaceable>value1</replaceable>
14628 <replaceable>expression</replaceable> = <replaceable>value2</replaceable>
14635 Note that if the left-hand expression yields null, or if there are
14636 no equal right-hand values and at least one right-hand expression yields
14637 null, the result of the <token>IN</token> construct will be null, not false.
14638 This is in accordance with SQL's normal rules for Boolean combinations
14644 <title><literal>NOT IN</literal></title>
14647 <replaceable>expression</replaceable> NOT IN (<replaceable>value</replaceable> <optional>, ...</optional>)
14651 The right-hand side is a parenthesized list
14652 of scalar expressions. The result is <quote>true</quote> if the left-hand expression's
14653 result is unequal to all of the right-hand expressions. This is a shorthand
14657 <replaceable>expression</replaceable> <> <replaceable>value1</replaceable>
14659 <replaceable>expression</replaceable> <> <replaceable>value2</replaceable>
14666 Note that if the left-hand expression yields null, or if there are
14667 no equal right-hand values and at least one right-hand expression yields
14668 null, the result of the <token>NOT IN</token> construct will be null, not true
14669 as one might naively expect.
14670 This is in accordance with SQL's normal rules for Boolean combinations
14676 <literal>x NOT IN y</literal> is equivalent to <literal>NOT (x IN y)</literal> in all
14677 cases. However, null values are much more likely to trip up the novice when
14678 working with <token>NOT IN</token> than when working with <token>IN</token>.
14679 It is best to express your condition positively if possible.
14685 <title><literal>ANY</literal>/<literal>SOME</literal> (array)</title>
14688 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>array expression</replaceable>)
14689 <replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>array expression</replaceable>)
14693 The right-hand side is a parenthesized expression, which must yield an
14695 The left-hand expression
14696 is evaluated and compared to each element of the array using the
14697 given <replaceable>operator</replaceable>, which must yield a Boolean
14699 The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
14700 The result is <quote>false</> if no true result is found (including the
14701 case where the array has zero elements).
14705 If the array expression yields a null array, the result of
14706 <token>ANY</token> will be null. If the left-hand expression yields null,
14707 the result of <token>ANY</token> is ordinarily null (though a non-strict
14708 comparison operator could possibly yield a different result).
14709 Also, if the right-hand array contains any null elements and no true
14710 comparison result is obtained, the result of <token>ANY</token>
14711 will be null, not false (again, assuming a strict comparison operator).
14712 This is in accordance with SQL's normal rules for Boolean combinations
14717 <token>SOME</token> is a synonym for <token>ANY</token>.
14722 <title><literal>ALL</literal> (array)</title>
14725 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>array expression</replaceable>)
14729 The right-hand side is a parenthesized expression, which must yield an
14731 The left-hand expression
14732 is evaluated and compared to each element of the array using the
14733 given <replaceable>operator</replaceable>, which must yield a Boolean
14735 The result of <token>ALL</token> is <quote>true</> if all comparisons yield true
14736 (including the case where the array has zero elements).
14737 The result is <quote>false</> if any false result is found.
14741 If the array expression yields a null array, the result of
14742 <token>ALL</token> will be null. If the left-hand expression yields null,
14743 the result of <token>ALL</token> is ordinarily null (though a non-strict
14744 comparison operator could possibly yield a different result).
14745 Also, if the right-hand array contains any null elements and no false
14746 comparison result is obtained, the result of <token>ALL</token>
14747 will be null, not true (again, assuming a strict comparison operator).
14748 This is in accordance with SQL's normal rules for Boolean combinations
14753 <sect2 id="row-wise-comparison">
14754 <title>Row Constructor Comparison</title>
14757 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> <replaceable>row_constructor</replaceable>
14761 Each side is a row constructor,
14762 as described in <xref linkend="sql-syntax-row-constructors">.
14763 The two row values must have the same number of fields.
14764 Each side is evaluated and they are compared row-wise. Row constructor
14765 comparisons are allowed when the <replaceable>operator</replaceable> is
14767 <literal><></>,
14770 <literal>></> or
14772 Every row element must be of a type which has a default B-tree operator
14773 class or the attempted comparison may generate an error.
14778 Errors related to the number or types of elements might not occur if
14779 the comparison is resolved using earlier columns.
14784 The <literal>=</> and <literal><></> cases work slightly differently
14785 from the others. Two rows are considered
14786 equal if all their corresponding members are non-null and equal; the rows
14787 are unequal if any corresponding members are non-null and unequal;
14788 otherwise the result of the row comparison is unknown (null).
14792 For the <literal><</>, <literal><=</>, <literal>></> and
14793 <literal>>=</> cases, the row elements are compared left-to-right,
14794 stopping as soon as an unequal or null pair of elements is found.
14795 If either of this pair of elements is null, the result of the
14796 row comparison is unknown (null); otherwise comparison of this pair
14797 of elements determines the result. For example,
14798 <literal>ROW(1,2,NULL) < ROW(1,3,0)</>
14799 yields true, not null, because the third pair of elements are not
14805 Prior to <productname>PostgreSQL</productname> 8.2, the
14806 <literal><</>, <literal><=</>, <literal>></> and <literal>>=</>
14807 cases were not handled per SQL specification. A comparison like
14808 <literal>ROW(a,b) < ROW(c,d)</>
14810 <literal>a < c AND b < d</>
14811 whereas the correct behavior is equivalent to
14812 <literal>a < c OR (a = c AND b < d)</>.
14817 <replaceable>row_constructor</replaceable> IS DISTINCT FROM <replaceable>row_constructor</replaceable>
14821 This construct is similar to a <literal><></literal> row comparison,
14822 but it does not yield null for null inputs. Instead, any null value is
14823 considered unequal to (distinct from) any non-null value, and any two
14824 nulls are considered equal (not distinct). Thus the result will
14825 either be true or false, never null.
14829 <replaceable>row_constructor</replaceable> IS NOT DISTINCT FROM <replaceable>row_constructor</replaceable>
14833 This construct is similar to a <literal>=</literal> row comparison,
14834 but it does not yield null for null inputs. Instead, any null value is
14835 considered unequal to (distinct from) any non-null value, and any two
14836 nulls are considered equal (not distinct). Thus the result will always
14837 be either true or false, never null.
14842 <sect2 id="composite-type-comparison">
14843 <title>Composite Type Comparison</title>
14846 <replaceable>record</replaceable> <replaceable>operator</replaceable> <replaceable>record</replaceable>
14850 The SQL specification requires row-wise comparison to return NULL if the
14851 result depends on comparing two NULL values or a NULL and a non-NULL.
14852 <productname>PostgreSQL</productname> does this only when comparing the
14853 results of two row constructors (as in
14854 <xref linkend="row-wise-comparison">) or comparing a row constructor
14855 to the output of a subquery (as in <xref linkend="functions-subquery">).
14856 In other contexts where two composite-type values are compared, two
14857 NULL field values are considered equal, and a NULL is considered larger
14858 than a non-NULL. This is necessary in order to have consistent sorting
14859 and indexing behavior for composite types.
14863 Each side is evaluated and they are compared row-wise. Composite type
14864 comparisons are allowed when the <replaceable>operator</replaceable> is
14866 <literal><></>,
14869 <literal>></> or
14871 or has semantics similar to one of these. (To be specific, an operator
14872 can be a row comparison operator if it is a member of a B-tree operator
14873 class, or is the negator of the <literal>=</> member of a B-tree operator
14874 class.) The default behavior of the above operators is the same as for
14875 <literal>IS [ NOT ] DISTINCT FROM</literal> for row constructors (see
14876 <xref linkend="row-wise-comparison">).
14880 To support matching of rows which include elements without a default
14881 B-tree operator class, the following operators are defined for composite
14884 <literal>*<></>,
14886 <literal>*<=</>,
14887 <literal>*></>, and
14888 <literal>*>=</>.
14889 These operators compare the internal binary representation of the two
14890 rows. Two rows might have a different binary representation even
14891 though comparisons of the two rows with the equality operator is true.
14892 The ordering of rows under these comparison operators is deterministic
14893 but not otherwise meaningful. These operators are used internally for
14894 materialized views and might be useful for other specialized purposes
14895 such as replication but are not intended to be generally useful for
14901 <sect1 id="functions-srf">
14902 <title>Set Returning Functions</title>
14904 <indexterm zone="functions-srf">
14905 <primary>set returning functions</primary>
14906 <secondary>functions</secondary>
14910 <primary>generate_series</primary>
14914 This section describes functions that possibly return more than one row.
14915 The most widely used functions in this class are series generating
14916 functions, as detailed in <xref linkend="functions-srf-series"> and
14917 <xref linkend="functions-srf-subscripts">. Other, more specialized
14918 set-returning functions are described elsewhere in this manual.
14919 See <xref linkend="queries-tablefunctions"> for ways to combine multiple
14920 set-returning functions.
14923 <table id="functions-srf-series">
14924 <title>Series Generating Functions</title>
14928 <entry>Function</entry>
14929 <entry>Argument Type</entry>
14930 <entry>Return Type</entry>
14931 <entry>Description</entry>
14937 <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>)</function></literal></entry>
14938 <entry><type>int</type>, <type>bigint</type> or <type>numeric</type></entry>
14939 <entry><type>setof int</type>, <type>setof bigint</type>, or <type>setof numeric</type> (same as argument type)</entry>
14941 Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
14942 with a step size of one
14947 <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>, <parameter>step</parameter>)</function></literal></entry>
14948 <entry><type>int</type>, <type>bigint</type> or <type>numeric</type></entry>
14949 <entry><type>setof int</type>, <type>setof bigint</type> or <type>setof numeric</type> (same as argument type)</entry>
14951 Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
14952 with a step size of <parameter>step</parameter>
14957 <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>, <parameter>step</parameter> <type>interval</>)</function></literal></entry>
14958 <entry><type>timestamp</type> or <type>timestamp with time zone</type></entry>
14959 <entry><type>setof timestamp</type> or <type>setof timestamp with time zone</type> (same as argument type)</entry>
14961 Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
14962 with a step size of <parameter>step</parameter>
14971 When <parameter>step</parameter> is positive, zero rows are returned if
14972 <parameter>start</parameter> is greater than <parameter>stop</parameter>.
14973 Conversely, when <parameter>step</parameter> is negative, zero rows are
14974 returned if <parameter>start</parameter> is less than <parameter>stop</parameter>.
14975 Zero rows are also returned for <literal>NULL</literal> inputs. It is an error
14976 for <parameter>step</parameter> to be zero. Some examples follow:
14978 SELECT * FROM generate_series(2,4);
14986 SELECT * FROM generate_series(5,1,-2);
14994 SELECT * FROM generate_series(4,3);
14999 SELECT generate_series(1.1, 4, 1.3);
15007 -- this example relies on the date-plus-integer operator
15008 SELECT current_date + s.a AS dates FROM generate_series(0,14,7) AS s(a);
15016 SELECT * FROM generate_series('2008-03-01 00:00'::timestamp,
15017 '2008-03-04 12:00', '10 hours');
15019 ---------------------
15020 2008-03-01 00:00:00
15021 2008-03-01 10:00:00
15022 2008-03-01 20:00:00
15023 2008-03-02 06:00:00
15024 2008-03-02 16:00:00
15025 2008-03-03 02:00:00
15026 2008-03-03 12:00:00
15027 2008-03-03 22:00:00
15028 2008-03-04 08:00:00
15033 <table id="functions-srf-subscripts">
15034 <title>Subscript Generating Functions</title>
15038 <entry>Function</entry>
15039 <entry>Return Type</entry>
15040 <entry>Description</entry>
15046 <entry><literal><function>generate_subscripts(<parameter>array anyarray</parameter>, <parameter>dim int</parameter>)</function></literal></entry>
15047 <entry><type>setof int</type></entry>
15049 Generate a series comprising the given array's subscripts.
15054 <entry><literal><function>generate_subscripts(<parameter>array anyarray</parameter>, <parameter>dim int</parameter>, <parameter>reverse boolean</parameter>)</function></literal></entry>
15055 <entry><type>setof int</type></entry>
15057 Generate a series comprising the given array's subscripts. When
15058 <parameter>reverse</parameter> is true, the series is returned in
15068 <primary>generate_subscripts</primary>
15072 <function>generate_subscripts</> is a convenience function that generates
15073 the set of valid subscripts for the specified dimension of the given
15075 Zero rows are returned for arrays that do not have the requested dimension,
15076 or for NULL arrays (but valid subscripts are returned for NULL array
15077 elements). Some examples follow:
15080 SELECT generate_subscripts('{NULL,1,NULL,2}'::int[], 1) AS s;
15089 -- presenting an array, the subscript and the subscripted
15090 -- value requires a subquery
15091 SELECT * FROM arrays;
15093 --------------------
15098 SELECT a AS array, s AS subscript, a[s] AS value
15099 FROM (SELECT generate_subscripts(a, 1) AS s, a FROM arrays) foo;
15100 array | subscript | value
15101 ---------------+-----------+-------
15104 {100,200,300} | 1 | 100
15105 {100,200,300} | 2 | 200
15106 {100,200,300} | 3 | 300
15109 -- unnest a 2D array
15110 CREATE OR REPLACE FUNCTION unnest2(anyarray)
15111 RETURNS SETOF anyelement AS $$
15113 from generate_subscripts($1,1) g1(i),
15114 generate_subscripts($1,2) g2(j);
15115 $$ LANGUAGE sql IMMUTABLE;
15117 SELECT * FROM unnest2(ARRAY[[1,2],[3,4]]);
15129 <primary>ordinality</primary>
15133 When a function in the <literal>FROM</literal> clause is suffixed
15134 by <literal>WITH ORDINALITY</literal>, a <type>bigint</type> column is
15135 appended to the output which starts from 1 and increments by 1 for each row
15136 of the function's output. This is most useful in the case of set returning
15137 functions such as <function>unnest()</>.
15140 -- set returning function WITH ORDINALITY
15141 SELECT * FROM pg_ls_dir('.') WITH ORDINALITY AS t(ls,n);
15143 -----------------+----
15146 postmaster.opts | 3
15148 postgresql.conf | 5
15169 <sect1 id="functions-info">
15170 <title>System Information Functions</title>
15173 <xref linkend="functions-info-session-table"> shows several
15174 functions that extract session and system information.
15178 In addition to the functions listed in this section, there are a number of
15179 functions related to the statistics system that also provide system
15180 information. See <xref linkend="monitoring-stats-views"> for more
15184 <table id="functions-info-session-table">
15185 <title>Session Information Functions</title>
15188 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
15193 <entry><literal><function>current_catalog</function></literal></entry>
15194 <entry><type>name</type></entry>
15195 <entry>name of current database (called <quote>catalog</quote> in the SQL standard)</entry>
15199 <entry><literal><function>current_database()</function></literal></entry>
15200 <entry><type>name</type></entry>
15201 <entry>name of current database</entry>
15205 <entry><literal><function>current_query()</function></literal></entry>
15206 <entry><type>text</type></entry>
15207 <entry>text of the currently executing query, as submitted
15208 by the client (might contain more than one statement)</entry>
15212 <entry><literal><function>current_schema</function>[()]</literal></entry>
15213 <entry><type>name</type></entry>
15214 <entry>name of current schema</entry>
15218 <entry><literal><function>current_schemas(<type>boolean</type>)</function></literal></entry>
15219 <entry><type>name[]</type></entry>
15220 <entry>names of schemas in search path, optionally including implicit schemas</entry>
15224 <entry><literal><function>current_user</function></literal></entry>
15225 <entry><type>name</type></entry>
15226 <entry>user name of current execution context</entry>
15230 <entry><literal><function>inet_client_addr()</function></literal></entry>
15231 <entry><type>inet</type></entry>
15232 <entry>address of the remote connection</entry>
15236 <entry><literal><function>inet_client_port()</function></literal></entry>
15237 <entry><type>int</type></entry>
15238 <entry>port of the remote connection</entry>
15242 <entry><literal><function>inet_server_addr()</function></literal></entry>
15243 <entry><type>inet</type></entry>
15244 <entry>address of the local connection</entry>
15248 <entry><literal><function>inet_server_port()</function></literal></entry>
15249 <entry><type>int</type></entry>
15250 <entry>port of the local connection</entry>
15254 <!-- See also the entry for this in monitoring.sgml -->
15255 <entry><literal><function>pg_backend_pid()</function></literal></entry>
15256 <entry><type>int</type></entry>
15258 Process ID of the server process attached to the current session
15263 <entry><literal><function>pg_blocking_pids(<type>int</type>)</function></literal></entry>
15264 <entry><type>int[]</type></entry>
15265 <entry>Process ID(s) that are blocking specified server process ID</entry>
15269 <entry><literal><function>pg_conf_load_time()</function></literal></entry>
15270 <entry><type>timestamp with time zone</type></entry>
15271 <entry>configuration load time</entry>
15275 <entry><literal><function>pg_my_temp_schema()</function></literal></entry>
15276 <entry><type>oid</type></entry>
15277 <entry>OID of session's temporary schema, or 0 if none</entry>
15281 <entry><literal><function>pg_is_other_temp_schema(<type>oid</type>)</function></literal></entry>
15282 <entry><type>boolean</type></entry>
15283 <entry>is schema another session's temporary schema?</entry>
15287 <entry><literal><function>pg_listening_channels()</function></literal></entry>
15288 <entry><type>setof text</type></entry>
15289 <entry>channel names that the session is currently listening on</entry>
15293 <entry><literal><function>pg_notification_queue_usage()</function></literal></entry>
15294 <entry><type>double</type></entry>
15295 <entry>fraction of the asynchronous notification queue currently occupied (0-1)</entry>
15299 <entry><literal><function>pg_postmaster_start_time()</function></literal></entry>
15300 <entry><type>timestamp with time zone</type></entry>
15301 <entry>server start time</entry>
15305 <entry><literal><function>pg_trigger_depth()</function></literal></entry>
15306 <entry><type>int</type></entry>
15307 <entry>current nesting level of <productname>PostgreSQL</> triggers
15308 (0 if not called, directly or indirectly, from inside a trigger)</entry>
15312 <entry><literal><function>session_user</function></literal></entry>
15313 <entry><type>name</type></entry>
15314 <entry>session user name</entry>
15318 <entry><literal><function>user</function></literal></entry>
15319 <entry><type>name</type></entry>
15320 <entry>equivalent to <function>current_user</function></entry>
15324 <entry><literal><function>version()</function></literal></entry>
15325 <entry><type>text</type></entry>
15326 <entry><productname>PostgreSQL</> version information. See also <xref linkend="guc-server-version-num"> for a machine-readable version.</entry>
15334 <function>current_catalog</function>, <function>current_schema</function>,
15335 <function>current_user</function>, <function>session_user</function>,
15336 and <function>user</function> have special syntactic status
15337 in <acronym>SQL</acronym>: they must be called without trailing
15338 parentheses. (In PostgreSQL, parentheses can optionally be used with
15339 <function>current_schema</function>, but not with the others.)
15344 <primary>current_catalog</primary>
15348 <primary>current_database</primary>
15352 <primary>current_query</primary>
15356 <primary>current_schema</primary>
15360 <primary>current_schemas</primary>
15364 <primary>current_user</primary>
15368 <primary>pg_backend_pid</primary>
15372 <primary>schema</primary>
15373 <secondary>current</secondary>
15377 <primary>search path</primary>
15378 <secondary>current</secondary>
15382 <primary>session_user</primary>
15386 <primary>user</primary>
15387 <secondary>current</secondary>
15391 <primary>user</primary>
15395 The <function>session_user</function> is normally the user who initiated
15396 the current database connection; but superusers can change this setting
15397 with <xref linkend="sql-set-session-authorization">.
15398 The <function>current_user</function> is the user identifier
15399 that is applicable for permission checking. Normally it is equal
15400 to the session user, but it can be changed with
15401 <xref linkend="sql-set-role">.
15402 It also changes during the execution of
15403 functions with the attribute <literal>SECURITY DEFINER</literal>.
15404 In Unix parlance, the session user is the <quote>real user</quote> and
15405 the current user is the <quote>effective user</quote>.
15409 <function>current_schema</function> returns the name of the schema that is
15410 first in the search path (or a null value if the search path is
15411 empty). This is the schema that will be used for any tables or
15412 other named objects that are created without specifying a target schema.
15413 <function>current_schemas(boolean)</function> returns an array of the names of all
15414 schemas presently in the search path. The Boolean option determines whether or not
15415 implicitly included system schemas such as <literal>pg_catalog</> are included in the
15416 returned search path.
15421 The search path can be altered at run time. The command is:
15423 SET search_path TO <replaceable>schema</> <optional>, <replaceable>schema</>, ...</optional>
15429 <primary>inet_client_addr</primary>
15433 <primary>inet_client_port</primary>
15437 <primary>inet_server_addr</primary>
15441 <primary>inet_server_port</primary>
15445 <function>inet_client_addr</function> returns the IP address of the
15446 current client, and <function>inet_client_port</function> returns the
15448 <function>inet_server_addr</function> returns the IP address on which
15449 the server accepted the current connection, and
15450 <function>inet_server_port</function> returns the port number.
15451 All these functions return NULL if the current connection is via a
15452 Unix-domain socket.
15456 <primary>pg_blocking_pids</primary>
15460 <function>pg_blocking_pids</function> returns an array of the process IDs
15461 of the sessions that are blocking the server process with the specified
15462 process ID, or an empty array if there is no such server process or it is
15463 not blocked. One server process blocks another if it either holds a lock
15464 that conflicts with the blocked process's lock request (hard block), or is
15465 waiting for a lock that would conflict with the blocked process's lock
15466 request and is ahead of it in the wait queue (soft block). When using
15467 parallel queries the result always lists client-visible process IDs (that
15468 is, <function>pg_backend_pid</> results) even if the actual lock is held
15469 or awaited by a child worker process. As a result of that, there may be
15470 duplicated PIDs in the result. Also note that when a prepared transaction
15471 holds a conflicting lock, it will be represented by a zero process ID in
15472 the result of this function.
15473 Frequent calls to this function could have some impact on database
15474 performance, because it needs exclusive access to the lock manager's
15475 shared state for a short time.
15479 <primary>pg_conf_load_time</primary>
15483 <function>pg_conf_load_time</function> returns the
15484 <type>timestamp with time zone</type> when the
15485 server configuration files were last loaded.
15486 (If the current session was alive at the time, this will be the time
15487 when the session itself re-read the configuration files, so the
15488 reading will vary a little in different sessions. Otherwise it is
15489 the time when the postmaster process re-read the configuration files.)
15493 <primary>pg_my_temp_schema</primary>
15497 <primary>pg_is_other_temp_schema</primary>
15501 <function>pg_my_temp_schema</function> returns the OID of the current
15502 session's temporary schema, or zero if it has none (because it has not
15503 created any temporary tables).
15504 <function>pg_is_other_temp_schema</function> returns true if the
15505 given OID is the OID of another session's temporary schema.
15506 (This can be useful, for example, to exclude other sessions' temporary
15507 tables from a catalog display.)
15511 <primary>pg_listening_channels</primary>
15515 <primary>pg_notification_queue_usage</primary>
15519 <function>pg_listening_channels</function> returns a set of names of
15520 asynchronous notification channels that the current session is listening
15521 to. <function>pg_notification_queue_usage</function> returns the
15522 fraction of the total available space for notifications currently
15523 occupied by notifications that are waiting to be processed, as a
15524 <type>double</type> in the range 0-1.
15525 See <xref linkend="sql-listen"> and <xref linkend="sql-notify">
15526 for more information.
15530 <primary>pg_postmaster_start_time</primary>
15534 <function>pg_postmaster_start_time</function> returns the
15535 <type>timestamp with time zone</type> when the
15540 <primary>version</primary>
15544 <function>version</function> returns a string describing the
15545 <productname>PostgreSQL</productname> server's version. You can also
15546 get this information from <xref linkend="guc-server-version"> or
15547 for a machine-readable version, <xref linkend="guc-server-version-num">.
15548 Software developers should use <literal>server_version_num</literal>
15549 (available since 8.2) or <xref linkend="libpq-pqserverversion"> instead
15550 of parsing the text version.
15554 <primary>privilege</primary>
15555 <secondary>querying</secondary>
15559 <xref linkend="functions-info-access-table"> lists functions that
15560 allow the user to query object access privileges programmatically.
15561 See <xref linkend="ddl-priv"> for more information about
15565 <table id="functions-info-access-table">
15566 <title>Access Privilege Inquiry Functions</title>
15569 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
15574 <entry><literal><function>has_any_column_privilege</function>(<parameter>user</parameter>,
15575 <parameter>table</parameter>,
15576 <parameter>privilege</parameter>)</literal>
15578 <entry><type>boolean</type></entry>
15579 <entry>does user have privilege for any column of table</entry>
15582 <entry><literal><function>has_any_column_privilege</function>(<parameter>table</parameter>,
15583 <parameter>privilege</parameter>)</literal>
15585 <entry><type>boolean</type></entry>
15586 <entry>does current user have privilege for any column of table</entry>
15589 <entry><literal><function>has_column_privilege</function>(<parameter>user</parameter>,
15590 <parameter>table</parameter>,
15591 <parameter>column</parameter>,
15592 <parameter>privilege</parameter>)</literal>
15594 <entry><type>boolean</type></entry>
15595 <entry>does user have privilege for column</entry>
15598 <entry><literal><function>has_column_privilege</function>(<parameter>table</parameter>,
15599 <parameter>column</parameter>,
15600 <parameter>privilege</parameter>)</literal>
15602 <entry><type>boolean</type></entry>
15603 <entry>does current user have privilege for column</entry>
15606 <entry><literal><function>has_database_privilege</function>(<parameter>user</parameter>,
15607 <parameter>database</parameter>,
15608 <parameter>privilege</parameter>)</literal>
15610 <entry><type>boolean</type></entry>
15611 <entry>does user have privilege for database</entry>
15614 <entry><literal><function>has_database_privilege</function>(<parameter>database</parameter>,
15615 <parameter>privilege</parameter>)</literal>
15617 <entry><type>boolean</type></entry>
15618 <entry>does current user have privilege for database</entry>
15621 <entry><literal><function>has_foreign_data_wrapper_privilege</function>(<parameter>user</parameter>,
15622 <parameter>fdw</parameter>,
15623 <parameter>privilege</parameter>)</literal>
15625 <entry><type>boolean</type></entry>
15626 <entry>does user have privilege for foreign-data wrapper</entry>
15629 <entry><literal><function>has_foreign_data_wrapper_privilege</function>(<parameter>fdw</parameter>,
15630 <parameter>privilege</parameter>)</literal>
15632 <entry><type>boolean</type></entry>
15633 <entry>does current user have privilege for foreign-data wrapper</entry>
15636 <entry><literal><function>has_function_privilege</function>(<parameter>user</parameter>,
15637 <parameter>function</parameter>,
15638 <parameter>privilege</parameter>)</literal>
15640 <entry><type>boolean</type></entry>
15641 <entry>does user have privilege for function</entry>
15644 <entry><literal><function>has_function_privilege</function>(<parameter>function</parameter>,
15645 <parameter>privilege</parameter>)</literal>
15647 <entry><type>boolean</type></entry>
15648 <entry>does current user have privilege for function</entry>
15651 <entry><literal><function>has_language_privilege</function>(<parameter>user</parameter>,
15652 <parameter>language</parameter>,
15653 <parameter>privilege</parameter>)</literal>
15655 <entry><type>boolean</type></entry>
15656 <entry>does user have privilege for language</entry>
15659 <entry><literal><function>has_language_privilege</function>(<parameter>language</parameter>,
15660 <parameter>privilege</parameter>)</literal>
15662 <entry><type>boolean</type></entry>
15663 <entry>does current user have privilege for language</entry>
15666 <entry><literal><function>has_schema_privilege</function>(<parameter>user</parameter>,
15667 <parameter>schema</parameter>,
15668 <parameter>privilege</parameter>)</literal>
15670 <entry><type>boolean</type></entry>
15671 <entry>does user have privilege for schema</entry>
15674 <entry><literal><function>has_schema_privilege</function>(<parameter>schema</parameter>,
15675 <parameter>privilege</parameter>)</literal>
15677 <entry><type>boolean</type></entry>
15678 <entry>does current user have privilege for schema</entry>
15681 <entry><literal><function>has_sequence_privilege</function>(<parameter>user</parameter>,
15682 <parameter>sequence</parameter>,
15683 <parameter>privilege</parameter>)</literal>
15685 <entry><type>boolean</type></entry>
15686 <entry>does user have privilege for sequence</entry>
15689 <entry><literal><function>has_sequence_privilege</function>(<parameter>sequence</parameter>,
15690 <parameter>privilege</parameter>)</literal>
15692 <entry><type>boolean</type></entry>
15693 <entry>does current user have privilege for sequence</entry>
15696 <entry><literal><function>has_server_privilege</function>(<parameter>user</parameter>,
15697 <parameter>server</parameter>,
15698 <parameter>privilege</parameter>)</literal>
15700 <entry><type>boolean</type></entry>
15701 <entry>does user have privilege for foreign server</entry>
15704 <entry><literal><function>has_server_privilege</function>(<parameter>server</parameter>,
15705 <parameter>privilege</parameter>)</literal>
15707 <entry><type>boolean</type></entry>
15708 <entry>does current user have privilege for foreign server</entry>
15711 <entry><literal><function>has_table_privilege</function>(<parameter>user</parameter>,
15712 <parameter>table</parameter>,
15713 <parameter>privilege</parameter>)</literal>
15715 <entry><type>boolean</type></entry>
15716 <entry>does user have privilege for table</entry>
15719 <entry><literal><function>has_table_privilege</function>(<parameter>table</parameter>,
15720 <parameter>privilege</parameter>)</literal>
15722 <entry><type>boolean</type></entry>
15723 <entry>does current user have privilege for table</entry>
15726 <entry><literal><function>has_tablespace_privilege</function>(<parameter>user</parameter>,
15727 <parameter>tablespace</parameter>,
15728 <parameter>privilege</parameter>)</literal>
15730 <entry><type>boolean</type></entry>
15731 <entry>does user have privilege for tablespace</entry>
15734 <entry><literal><function>has_tablespace_privilege</function>(<parameter>tablespace</parameter>,
15735 <parameter>privilege</parameter>)</literal>
15737 <entry><type>boolean</type></entry>
15738 <entry>does current user have privilege for tablespace</entry>
15741 <entry><literal><function>pg_has_role</function>(<parameter>user</parameter>,
15742 <parameter>role</parameter>,
15743 <parameter>privilege</parameter>)</literal>
15745 <entry><type>boolean</type></entry>
15746 <entry>does user have privilege for role</entry>
15749 <entry><literal><function>pg_has_role</function>(<parameter>role</parameter>,
15750 <parameter>privilege</parameter>)</literal>
15752 <entry><type>boolean</type></entry>
15753 <entry>does current user have privilege for role</entry>
15756 <entry><literal><function>row_security_active</function>(<parameter>table</parameter>)</literal>
15758 <entry><type>boolean</type></entry>
15759 <entry>does current user have row level security active for table</entry>
15766 <primary>has_any_column_privilege</primary>
15769 <primary>has_column_privilege</primary>
15772 <primary>has_database_privilege</primary>
15775 <primary>has_function_privilege</primary>
15778 <primary>has_foreign_data_wrapper_privilege</primary>
15781 <primary>has_language_privilege</primary>
15784 <primary>has_schema_privilege</primary>
15787 <primary>has_server_privilege</primary>
15790 <primary>has_sequence_privilege</primary>
15793 <primary>has_table_privilege</primary>
15796 <primary>has_tablespace_privilege</primary>
15799 <primary>pg_has_role</primary>
15802 <primary>row_security_active</primary>
15806 <function>has_table_privilege</function> checks whether a user
15807 can access a table in a particular way. The user can be
15808 specified by name, by OID (<literal>pg_authid.oid</literal>),
15809 <literal>public</> to indicate the PUBLIC pseudo-role, or if the argument is
15811 <function>current_user</function> is assumed. The table can be specified
15812 by name or by OID. (Thus, there are actually six variants of
15813 <function>has_table_privilege</function>, which can be distinguished by
15814 the number and types of their arguments.) When specifying by name,
15815 the name can be schema-qualified if necessary.
15816 The desired access privilege type
15817 is specified by a text string, which must evaluate to one of the
15818 values <literal>SELECT</literal>, <literal>INSERT</literal>,
15819 <literal>UPDATE</literal>, <literal>DELETE</literal>, <literal>TRUNCATE</>,
15820 <literal>REFERENCES</literal>, or <literal>TRIGGER</literal>. Optionally,
15821 <literal>WITH GRANT OPTION</> can be added to a privilege type to test
15822 whether the privilege is held with grant option. Also, multiple privilege
15823 types can be listed separated by commas, in which case the result will
15824 be <literal>true</> if any of the listed privileges is held.
15825 (Case of the privilege string is not significant, and extra whitespace
15826 is allowed between but not within privilege names.)
15829 SELECT has_table_privilege('myschema.mytable', 'select');
15830 SELECT has_table_privilege('joe', 'mytable', 'INSERT, SELECT WITH GRANT OPTION');
15835 <function>has_sequence_privilege</function> checks whether a user
15836 can access a sequence in a particular way. The possibilities for its
15837 arguments are analogous to <function>has_table_privilege</function>.
15838 The desired access privilege type must evaluate to one of
15839 <literal>USAGE</literal>,
15840 <literal>SELECT</literal>, or
15841 <literal>UPDATE</literal>.
15845 <function>has_any_column_privilege</function> checks whether a user can
15846 access any column of a table in a particular way.
15847 Its argument possibilities
15848 are analogous to <function>has_table_privilege</>,
15849 except that the desired access privilege type must evaluate to some
15851 <literal>SELECT</literal>,
15852 <literal>INSERT</literal>,
15853 <literal>UPDATE</literal>, or
15854 <literal>REFERENCES</literal>. Note that having any of these privileges
15855 at the table level implicitly grants it for each column of the table,
15856 so <function>has_any_column_privilege</function> will always return
15857 <literal>true</> if <function>has_table_privilege</> does for the same
15858 arguments. But <function>has_any_column_privilege</> also succeeds if
15859 there is a column-level grant of the privilege for at least one column.
15863 <function>has_column_privilege</function> checks whether a user
15864 can access a column in a particular way.
15865 Its argument possibilities
15866 are analogous to <function>has_table_privilege</function>,
15867 with the addition that the column can be specified either by name
15868 or attribute number.
15869 The desired access privilege type must evaluate to some combination of
15870 <literal>SELECT</literal>,
15871 <literal>INSERT</literal>,
15872 <literal>UPDATE</literal>, or
15873 <literal>REFERENCES</literal>. Note that having any of these privileges
15874 at the table level implicitly grants it for each column of the table.
15878 <function>has_database_privilege</function> checks whether a user
15879 can access a database in a particular way.
15880 Its argument possibilities
15881 are analogous to <function>has_table_privilege</function>.
15882 The desired access privilege type must evaluate to some combination of
15883 <literal>CREATE</literal>,
15884 <literal>CONNECT</literal>,
15885 <literal>TEMPORARY</literal>, or
15886 <literal>TEMP</literal> (which is equivalent to
15887 <literal>TEMPORARY</literal>).
15891 <function>has_function_privilege</function> checks whether a user
15892 can access a function in a particular way.
15893 Its argument possibilities
15894 are analogous to <function>has_table_privilege</function>.
15895 When specifying a function by a text string rather than by OID,
15896 the allowed input is the same as for the <type>regprocedure</> data type
15897 (see <xref linkend="datatype-oid">).
15898 The desired access privilege type must evaluate to
15899 <literal>EXECUTE</literal>.
15902 SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');
15907 <function>has_foreign_data_wrapper_privilege</function> checks whether a user
15908 can access a foreign-data wrapper in a particular way.
15909 Its argument possibilities
15910 are analogous to <function>has_table_privilege</function>.
15911 The desired access privilege type must evaluate to
15912 <literal>USAGE</literal>.
15916 <function>has_language_privilege</function> checks whether a user
15917 can access a procedural language in a particular way.
15918 Its argument possibilities
15919 are analogous to <function>has_table_privilege</function>.
15920 The desired access privilege type must evaluate to
15921 <literal>USAGE</literal>.
15925 <function>has_schema_privilege</function> checks whether a user
15926 can access a schema in a particular way.
15927 Its argument possibilities
15928 are analogous to <function>has_table_privilege</function>.
15929 The desired access privilege type must evaluate to some combination of
15930 <literal>CREATE</literal> or
15931 <literal>USAGE</literal>.
15935 <function>has_server_privilege</function> checks whether a user
15936 can access a foreign server in a particular way.
15937 Its argument possibilities
15938 are analogous to <function>has_table_privilege</function>.
15939 The desired access privilege type must evaluate to
15940 <literal>USAGE</literal>.
15944 <function>has_tablespace_privilege</function> checks whether a user
15945 can access a tablespace in a particular way.
15946 Its argument possibilities
15947 are analogous to <function>has_table_privilege</function>.
15948 The desired access privilege type must evaluate to
15949 <literal>CREATE</literal>.
15953 <function>pg_has_role</function> checks whether a user
15954 can access a role in a particular way.
15955 Its argument possibilities
15956 are analogous to <function>has_table_privilege</function>,
15957 except that <literal>public</> is not allowed as a user name.
15958 The desired access privilege type must evaluate to some combination of
15959 <literal>MEMBER</literal> or
15960 <literal>USAGE</literal>.
15961 <literal>MEMBER</literal> denotes direct or indirect membership in
15962 the role (that is, the right to do <command>SET ROLE</>), while
15963 <literal>USAGE</literal> denotes whether the privileges of the role
15964 are immediately available without doing <command>SET ROLE</>.
15968 <function>row_security_active</function> checks whether row level
15969 security is active for the specified table in the context of the
15970 <function>current_user</function> and environment. The table can
15971 be specified by name or by OID.
15975 <xref linkend="functions-info-schema-table"> shows functions that
15976 determine whether a certain object is <firstterm>visible</> in the
15977 current schema search path.
15978 For example, a table is said to be visible if its
15979 containing schema is in the search path and no table of the same
15980 name appears earlier in the search path. This is equivalent to the
15981 statement that the table can be referenced by name without explicit
15982 schema qualification. To list the names of all visible tables:
15984 SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
15989 <primary>search path</primary>
15990 <secondary>object visibility</secondary>
15993 <table id="functions-info-schema-table">
15994 <title>Schema Visibility Inquiry Functions</title>
15997 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16002 <entry><literal><function>pg_collation_is_visible(<parameter>collation_oid</parameter>)</function></literal>
16004 <entry><type>boolean</type></entry>
16005 <entry>is collation visible in search path</entry>
16008 <entry><literal><function>pg_conversion_is_visible(<parameter>conversion_oid</parameter>)</function></literal>
16010 <entry><type>boolean</type></entry>
16011 <entry>is conversion visible in search path</entry>
16014 <entry><literal><function>pg_function_is_visible(<parameter>function_oid</parameter>)</function></literal>
16016 <entry><type>boolean</type></entry>
16017 <entry>is function visible in search path</entry>
16020 <entry><literal><function>pg_opclass_is_visible(<parameter>opclass_oid</parameter>)</function></literal>
16022 <entry><type>boolean</type></entry>
16023 <entry>is operator class visible in search path</entry>
16026 <entry><literal><function>pg_operator_is_visible(<parameter>operator_oid</parameter>)</function></literal>
16028 <entry><type>boolean</type></entry>
16029 <entry>is operator visible in search path</entry>
16032 <entry><literal><function>pg_opfamily_is_visible(<parameter>opclass_oid</parameter>)</function></literal>
16034 <entry><type>boolean</type></entry>
16035 <entry>is operator family visible in search path</entry>
16038 <entry><literal><function>pg_table_is_visible(<parameter>table_oid</parameter>)</function></literal>
16040 <entry><type>boolean</type></entry>
16041 <entry>is table visible in search path</entry>
16044 <entry><literal><function>pg_ts_config_is_visible(<parameter>config_oid</parameter>)</function></literal>
16046 <entry><type>boolean</type></entry>
16047 <entry>is text search configuration visible in search path</entry>
16050 <entry><literal><function>pg_ts_dict_is_visible(<parameter>dict_oid</parameter>)</function></literal>
16052 <entry><type>boolean</type></entry>
16053 <entry>is text search dictionary visible in search path</entry>
16056 <entry><literal><function>pg_ts_parser_is_visible(<parameter>parser_oid</parameter>)</function></literal>
16058 <entry><type>boolean</type></entry>
16059 <entry>is text search parser visible in search path</entry>
16062 <entry><literal><function>pg_ts_template_is_visible(<parameter>template_oid</parameter>)</function></literal>
16064 <entry><type>boolean</type></entry>
16065 <entry>is text search template visible in search path</entry>
16068 <entry><literal><function>pg_type_is_visible(<parameter>type_oid</parameter>)</function></literal>
16070 <entry><type>boolean</type></entry>
16071 <entry>is type (or domain) visible in search path</entry>
16078 <primary>pg_collation_is_visible</primary>
16081 <primary>pg_conversion_is_visible</primary>
16084 <primary>pg_function_is_visible</primary>
16087 <primary>pg_opclass_is_visible</primary>
16090 <primary>pg_operator_is_visible</primary>
16093 <primary>pg_opfamily_is_visible</primary>
16096 <primary>pg_table_is_visible</primary>
16099 <primary>pg_ts_config_is_visible</primary>
16102 <primary>pg_ts_dict_is_visible</primary>
16105 <primary>pg_ts_parser_is_visible</primary>
16108 <primary>pg_ts_template_is_visible</primary>
16111 <primary>pg_type_is_visible</primary>
16115 Each function performs the visibility check for one type of database
16116 object. Note that <function>pg_table_is_visible</function> can also be used
16117 with views, materialized views, indexes, sequences and foreign tables;
16118 <function>pg_type_is_visible</function> can also be used with domains.
16119 For functions and operators, an object in
16120 the search path is visible if there is no object of the same name
16121 <emphasis>and argument data type(s)</> earlier in the path. For operator
16122 classes, both name and associated index access method are considered.
16126 All these functions require object OIDs to identify the object to be
16127 checked. If you want to test an object by name, it is convenient to use
16128 the OID alias types (<type>regclass</>, <type>regtype</>,
16129 <type>regprocedure</>, <type>regoperator</>, <type>regconfig</>,
16130 or <type>regdictionary</>),
16133 SELECT pg_type_is_visible('myschema.widget'::regtype);
16135 Note that it would not make much sense to test a non-schema-qualified
16136 type name in this way — if the name can be recognized at all, it must be visible.
16140 <primary>format_type</primary>
16144 <primary>pg_get_constraintdef</primary>
16148 <primary>pg_get_expr</primary>
16152 <primary>pg_get_functiondef</primary>
16156 <primary>pg_get_function_arguments</primary>
16160 <primary>pg_get_function_identity_arguments</primary>
16164 <primary>pg_get_function_result</primary>
16168 <primary>pg_get_indexdef</primary>
16172 <primary>pg_get_keywords</primary>
16176 <primary>pg_get_ruledef</primary>
16180 <primary>pg_get_serial_sequence</primary>
16184 <primary>pg_get_triggerdef</primary>
16188 <primary>pg_get_userbyid</primary>
16192 <primary>pg_get_viewdef</primary>
16196 <primary>pg_options_to_table</primary>
16200 <primary>pg_tablespace_databases</primary>
16204 <primary>pg_tablespace_location</primary>
16208 <primary>pg_typeof</primary>
16212 <primary>collation for</primary>
16216 <primary>to_regclass</primary>
16220 <primary>to_regproc</primary>
16224 <primary>to_regprocedure</primary>
16228 <primary>to_regoper</primary>
16232 <primary>to_regoperator</primary>
16236 <primary>to_regtype</primary>
16240 <primary>to_regnamespace</primary>
16244 <primary>to_regrole</primary>
16248 <xref linkend="functions-info-catalog-table"> lists functions that
16249 extract information from the system catalogs.
16252 <table id="functions-info-catalog-table">
16253 <title>System Catalog Information Functions</title>
16256 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16261 <entry><literal><function>format_type(<parameter>type_oid</parameter>, <parameter>typemod</>)</function></literal></entry>
16262 <entry><type>text</type></entry>
16263 <entry>get SQL name of a data type</entry>
16266 <entry><literal><function>pg_get_constraintdef(<parameter>constraint_oid</parameter>)</function></literal></entry>
16267 <entry><type>text</type></entry>
16268 <entry>get definition of a constraint</entry>
16271 <entry><literal><function>pg_get_constraintdef(<parameter>constraint_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16272 <entry><type>text</type></entry>
16273 <entry>get definition of a constraint</entry>
16276 <entry><literal><function>pg_get_expr(<parameter>pg_node_tree</parameter>, <parameter>relation_oid</>)</function></literal></entry>
16277 <entry><type>text</type></entry>
16278 <entry>decompile internal form of an expression, assuming that any Vars
16279 in it refer to the relation indicated by the second parameter</entry>
16282 <entry><literal><function>pg_get_expr(<parameter>pg_node_tree</parameter>, <parameter>relation_oid</>, <parameter>pretty_bool</>)</function></literal></entry>
16283 <entry><type>text</type></entry>
16284 <entry>decompile internal form of an expression, assuming that any Vars
16285 in it refer to the relation indicated by the second parameter</entry>
16288 <entry><literal><function>pg_get_functiondef(<parameter>func_oid</parameter>)</function></literal></entry>
16289 <entry><type>text</type></entry>
16290 <entry>get definition of a function</entry>
16293 <entry><literal><function>pg_get_function_arguments(<parameter>func_oid</parameter>)</function></literal></entry>
16294 <entry><type>text</type></entry>
16295 <entry>get argument list of function's definition (with default values)</entry>
16298 <entry><literal><function>pg_get_function_identity_arguments(<parameter>func_oid</parameter>)</function></literal></entry>
16299 <entry><type>text</type></entry>
16300 <entry>get argument list to identify a function (without default values)</entry>
16303 <entry><literal><function>pg_get_function_result(<parameter>func_oid</parameter>)</function></literal></entry>
16304 <entry><type>text</type></entry>
16305 <entry>get <literal>RETURNS</> clause for function</entry>
16308 <entry><literal><function>pg_get_indexdef(<parameter>index_oid</parameter>)</function></literal></entry>
16309 <entry><type>text</type></entry>
16310 <entry>get <command>CREATE INDEX</> command for index</entry>
16313 <entry><literal><function>pg_get_indexdef(<parameter>index_oid</parameter>, <parameter>column_no</>, <parameter>pretty_bool</>)</function></literal></entry>
16314 <entry><type>text</type></entry>
16315 <entry>get <command>CREATE INDEX</> command for index,
16316 or definition of just one index column when
16317 <parameter>column_no</> is not zero</entry>
16320 <entry><literal><function>pg_get_keywords()</function></literal></entry>
16321 <entry><type>setof record</type></entry>
16322 <entry>get list of SQL keywords and their categories</entry>
16325 <entry><literal><function>pg_get_ruledef(<parameter>rule_oid</parameter>)</function></literal></entry>
16326 <entry><type>text</type></entry>
16327 <entry>get <command>CREATE RULE</> command for rule</entry>
16330 <entry><literal><function>pg_get_ruledef(<parameter>rule_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16331 <entry><type>text</type></entry>
16332 <entry>get <command>CREATE RULE</> command for rule</entry>
16335 <entry><literal><function>pg_get_serial_sequence(<parameter>table_name</parameter>, <parameter>column_name</parameter>)</function></literal></entry>
16336 <entry><type>text</type></entry>
16337 <entry>get name of the sequence that a <type>serial</type>, <type>smallserial</type> or <type>bigserial</type> column
16341 <entry><function>pg_get_triggerdef</function>(<parameter>trigger_oid</parameter>)</entry>
16342 <entry><type>text</type></entry>
16343 <entry>get <command>CREATE [ CONSTRAINT ] TRIGGER</> command for trigger</entry>
16346 <entry><function>pg_get_triggerdef</function>(<parameter>trigger_oid</parameter>, <parameter>pretty_bool</>)</entry>
16347 <entry><type>text</type></entry>
16348 <entry>get <command>CREATE [ CONSTRAINT ] TRIGGER</> command for trigger</entry>
16351 <entry><literal><function>pg_get_userbyid(<parameter>role_oid</parameter>)</function></literal></entry>
16352 <entry><type>name</type></entry>
16353 <entry>get role name with given OID</entry>
16356 <entry><literal><function>pg_get_viewdef(<parameter>view_name</parameter>)</function></literal></entry>
16357 <entry><type>text</type></entry>
16358 <entry>get underlying <command>SELECT</command> command for view or materialized view (<emphasis>deprecated</emphasis>)</entry>
16361 <entry><literal><function>pg_get_viewdef(<parameter>view_name</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16362 <entry><type>text</type></entry>
16363 <entry>get underlying <command>SELECT</command> command for view or materialized view (<emphasis>deprecated</emphasis>)</entry>
16366 <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>)</function></literal></entry>
16367 <entry><type>text</type></entry>
16368 <entry>get underlying <command>SELECT</command> command for view or materialized view</entry>
16371 <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16372 <entry><type>text</type></entry>
16373 <entry>get underlying <command>SELECT</command> command for view or materialized view</entry>
16376 <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>, <parameter>wrap_column_int</>)</function></literal></entry>
16377 <entry><type>text</type></entry>
16378 <entry>get underlying <command>SELECT</command> command for view or
16379 materialized view; lines with fields are wrapped to specified
16380 number of columns, pretty-printing is implied</entry>
16383 <entry><literal><function>pg_options_to_table(<parameter>reloptions</parameter>)</function></literal></entry>
16384 <entry><type>setof record</type></entry>
16385 <entry>get the set of storage option name/value pairs</entry>
16388 <entry><literal><function>pg_tablespace_databases(<parameter>tablespace_oid</parameter>)</function></literal></entry>
16389 <entry><type>setof oid</type></entry>
16390 <entry>get the set of database OIDs that have objects in the tablespace</entry>
16393 <entry><literal><function>pg_tablespace_location(<parameter>tablespace_oid</parameter>)</function></literal></entry>
16394 <entry><type>text</type></entry>
16395 <entry>get the path in the file system that this tablespace is located in</entry>
16398 <entry><literal><function>pg_typeof(<parameter>any</parameter>)</function></literal></entry>
16399 <entry><type>regtype</type></entry>
16400 <entry>get the data type of any value</entry>
16403 <entry><literal><function>collation for (<parameter>any</parameter>)</function></literal></entry>
16404 <entry><type>text</type></entry>
16405 <entry>get the collation of the argument</entry>
16408 <entry><literal><function>to_regclass(<parameter>rel_name</parameter>)</function></literal></entry>
16409 <entry><type>regclass</type></entry>
16410 <entry>get the OID of the named relation</entry>
16413 <entry><literal><function>to_regproc(<parameter>func_name</parameter>)</function></literal></entry>
16414 <entry><type>regproc</type></entry>
16415 <entry>get the OID of the named function</entry>
16418 <entry><literal><function>to_regprocedure(<parameter>func_name</parameter>)</function></literal></entry>
16419 <entry><type>regprocedure</type></entry>
16420 <entry>get the OID of the named function</entry>
16423 <entry><literal><function>to_regoper(<parameter>operator_name</parameter>)</function></literal></entry>
16424 <entry><type>regoper</type></entry>
16425 <entry>get the OID of the named operator</entry>
16428 <entry><literal><function>to_regoperator(<parameter>operator_name</parameter>)</function></literal></entry>
16429 <entry><type>regoperator</type></entry>
16430 <entry>get the OID of the named operator</entry>
16433 <entry><literal><function>to_regtype(<parameter>type_name</parameter>)</function></literal></entry>
16434 <entry><type>regtype</type></entry>
16435 <entry>get the OID of the named type</entry>
16438 <entry><literal><function>to_regnamespace(<parameter>schema_name</parameter>)</function></literal></entry>
16439 <entry><type>regnamespace</type></entry>
16440 <entry>get the OID of the named schema</entry>
16443 <entry><literal><function>to_regrole(<parameter>role_name</parameter>)</function></literal></entry>
16444 <entry><type>regrole</type></entry>
16445 <entry>get the OID of the named role</entry>
16452 <function>format_type</function> returns the SQL name of a data type that
16453 is identified by its type OID and possibly a type modifier. Pass NULL
16454 for the type modifier if no specific modifier is known.
16458 <function>pg_get_keywords</function> returns a set of records describing
16459 the SQL keywords recognized by the server. The <structfield>word</> column
16460 contains the keyword. The <structfield>catcode</> column contains a
16461 category code: <literal>U</> for unreserved, <literal>C</> for column name,
16462 <literal>T</> for type or function name, or <literal>R</> for reserved.
16463 The <structfield>catdesc</> column contains a possibly-localized string
16464 describing the category.
16468 <function>pg_get_constraintdef</function>,
16469 <function>pg_get_indexdef</function>, <function>pg_get_ruledef</function>,
16470 and <function>pg_get_triggerdef</function>, respectively reconstruct the
16471 creating command for a constraint, index, rule, or trigger. (Note that this
16472 is a decompiled reconstruction, not the original text of the command.)
16473 <function>pg_get_expr</function> decompiles the internal form of an
16474 individual expression, such as the default value for a column. It can be
16475 useful when examining the contents of system catalogs. If the expression
16476 might contain Vars, specify the OID of the relation they refer to as the
16477 second parameter; if no Vars are expected, zero is sufficient.
16478 <function>pg_get_viewdef</function> reconstructs the <command>SELECT</>
16479 query that defines a view. Most of these functions come in two variants,
16480 one of which can optionally <quote>pretty-print</> the result. The
16481 pretty-printed format is more readable, but the default format is more
16482 likely to be interpreted the same way by future versions of
16483 <productname>PostgreSQL</>; avoid using pretty-printed output for dump
16484 purposes. Passing <literal>false</> for the pretty-print parameter yields
16485 the same result as the variant that does not have the parameter at all.
16489 <function>pg_get_functiondef</> returns a complete
16490 <command>CREATE OR REPLACE FUNCTION</> statement for a function.
16491 <function>pg_get_function_arguments</function> returns the argument list
16492 of a function, in the form it would need to appear in within
16493 <command>CREATE FUNCTION</>.
16494 <function>pg_get_function_result</function> similarly returns the
16495 appropriate <literal>RETURNS</> clause for the function.
16496 <function>pg_get_function_identity_arguments</function> returns the
16497 argument list necessary to identify a function, in the form it
16498 would need to appear in within <command>ALTER FUNCTION</>, for
16499 instance. This form omits default values.
16503 <function>pg_get_serial_sequence</function> returns the name of the
16504 sequence associated with a column, or NULL if no sequence is associated
16505 with the column. The first input parameter is a table name with
16506 optional schema, and the second parameter is a column name. Because
16507 the first parameter is potentially a schema and table, it is not treated
16508 as a double-quoted identifier, meaning it is lower cased by default,
16509 while the second parameter, being just a column name, is treated as
16510 double-quoted and has its case preserved. The function returns a value
16511 suitably formatted for passing to sequence functions (see <xref
16512 linkend="functions-sequence">). This association can be modified or
16513 removed with <command>ALTER SEQUENCE OWNED BY</>. (The function
16514 probably should have been called
16515 <function>pg_get_owned_sequence</function>; its current name reflects the fact
16516 that it's typically used with <type>serial</> or <type>bigserial</>
16521 <function>pg_get_userbyid</function> extracts a role's name given
16526 <function>pg_options_to_table</function> returns the set of storage
16527 option name/value pairs
16528 (<literal>option_name</>/<literal>option_value</>) when passed
16529 <structname>pg_class</>.<structfield>reloptions</> or
16530 <structname>pg_attribute</>.<structfield>attoptions</>.
16534 <function>pg_tablespace_databases</function> allows a tablespace to be
16535 examined. It returns the set of OIDs of databases that have objects stored
16536 in the tablespace. If this function returns any rows, the tablespace is not
16537 empty and cannot be dropped. To display the specific objects populating the
16538 tablespace, you will need to connect to the databases identified by
16539 <function>pg_tablespace_databases</function> and query their
16540 <structname>pg_class</> catalogs.
16544 <function>pg_typeof</function> returns the OID of the data type of the
16545 value that is passed to it. This can be helpful for troubleshooting or
16546 dynamically constructing SQL queries. The function is declared as
16547 returning <type>regtype</>, which is an OID alias type (see
16548 <xref linkend="datatype-oid">); this means that it is the same as an
16549 OID for comparison purposes but displays as a type name. For example:
16551 SELECT pg_typeof(33);
16558 SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
16567 The expression <literal>collation for</literal> returns the collation of the
16568 value that is passed to it. Example:
16570 SELECT collation for (description) FROM pg_description LIMIT 1;
16576 SELECT collation for ('foo' COLLATE "de_DE");
16582 The value might be quoted and schema-qualified. If no collation is derived
16583 for the argument expression, then a null value is returned. If the argument
16584 is not of a collatable data type, then an error is raised.
16588 The <function>to_regclass</function>, <function>to_regproc</function>,
16589 <function>to_regprocedure</function>, <function>to_regoper</function>,
16590 <function>to_regoperator</function>, <function>to_regtype</function>,
16591 <function>to_regnamespace</function>, and <function>to_regrole</function>
16592 functions translate relation, function, operator, type, schema, and role
16593 names (given as <type>text</>) to objects of
16594 type <type>regclass</>, <type>regproc</>, <type>regprocedure</type>,
16595 <type>regoper</>, <type>regoperator</type>, <type>regtype</>,
16596 <type>regnamespace</>, and <type>regrole</>
16597 respectively. These functions differ from a cast from
16598 text in that they don't accept a numeric OID, and that they return null
16599 rather than throwing an error if the name is not found (or, for
16600 <function>to_regproc</function> and <function>to_regoper</function>, if
16601 the given name matches multiple objects).
16605 <primary>pg_describe_object</primary>
16609 <primary>pg_identify_object</primary>
16613 <primary>pg_identify_object_as_address</primary>
16617 <primary>pg_get_object_address</primary>
16621 <xref linkend="functions-info-object-table"> lists functions related to
16622 database object identification and addressing.
16625 <table id="functions-info-object-table">
16626 <title>Object Information and Addressing Functions</title>
16629 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16634 <entry><literal><function>pg_describe_object(<parameter>catalog_id</parameter>, <parameter>object_id</parameter>, <parameter>object_sub_id</parameter>)</function></literal></entry>
16635 <entry><type>text</type></entry>
16636 <entry>get description of a database object</entry>
16639 <entry><literal><function>pg_identify_object(<parameter>catalog_id</parameter> <type>oid</>, <parameter>object_id</parameter> <type>oid</>, <parameter>object_sub_id</parameter> <type>integer</>)</function></literal></entry>
16640 <entry><parameter>type</> <type>text</>, <parameter>schema</> <type>text</>, <parameter>name</> <type>text</>, <parameter>identity</> <type>text</></entry>
16641 <entry>get identity of a database object</entry>
16644 <entry><literal><function>pg_identify_object_as_address(<parameter>catalog_id</parameter> <type>oid</>, <parameter>object_id</parameter> <type>oid</>, <parameter>object_sub_id</parameter> <type>integer</>)</function></literal></entry>
16645 <entry><parameter>type</> <type>text</>, <parameter>name</> <type>text[]</>, <parameter>args</> <type>text[]</></entry>
16646 <entry>get external representation of a database object's address</entry>
16649 <entry><literal><function>pg_get_object_address(<parameter>type</parameter> <type>text</>, <parameter>name</parameter> <type>text[]</>, <parameter>args</parameter> <type>text[]</>)</function></literal></entry>
16650 <entry><parameter>catalog_id</> <type>oid</>, <parameter>object_id</> <type>oid</>, <parameter>object_sub_id</> <type>int32</></entry>
16651 <entry>get address of a database object, from its external representation</entry>
16658 <function>pg_describe_object</function> returns a textual description of a database
16659 object specified by catalog OID, object OID and a (possibly zero) sub-object ID.
16660 This description is intended to be human-readable, and might be translated,
16661 depending on server configuration.
16662 This is useful to determine the identity of an object as stored in the
16663 <structname>pg_depend</structname> catalog.
16667 <function>pg_identify_object</function> returns a row containing enough information
16668 to uniquely identify the database object specified by catalog OID, object OID and a
16669 (possibly zero) sub-object ID. This information is intended to be machine-readable,
16670 and is never translated.
16671 <parameter>type</> identifies the type of database object;
16672 <parameter>schema</> is the schema name that the object belongs in, or
16673 <literal>NULL</> for object types that do not belong to schemas;
16674 <parameter>name</> is the name of the object, quoted if necessary, only
16675 present if it can be used (alongside schema name, if pertinent) as a unique
16676 identifier of the object, otherwise <literal>NULL</>;
16677 <parameter>identity</> is the complete object identity, with the precise format
16678 depending on object type, and each part within the format being
16679 schema-qualified and quoted as necessary.
16683 <function>pg_identify_object_as_address</function> returns a row containing
16684 enough information to uniquely identify the database object specified by
16685 catalog OID, object OID and a (possibly zero) sub-object ID. The returned
16686 information is independent of the current server, that is, it could be used
16687 to identify an identically named object in another server.
16688 <parameter>type</> identifies the type of database object;
16689 <parameter>name</> and <parameter>args</> are text arrays that together
16690 form a reference to the object. These three columns can be passed to
16691 <function>pg_get_object_address</> to obtain the internal address
16693 This function is the inverse of <function>pg_get_object_address</function>.
16697 <function>pg_get_object_address</function> returns a row containing enough
16698 information to uniquely identify the database object specified by its
16699 type and object name and argument arrays. The returned values are the
16700 ones that would be used in system catalogs such as <structname>pg_depend</>
16701 and can be passed to other system functions such as
16702 <function>pg_identify_object</> or <function>pg_describe_object</>.
16703 <parameter>catalog_id</> is the OID of the system catalog containing the
16705 <parameter>object_id</> is the OID of the object itself, and
16706 <parameter>object_sub_id</> is the object sub-ID, or zero if none.
16707 This function is the inverse of <function>pg_identify_object_as_address</function>.
16711 <primary>col_description</primary>
16715 <primary>obj_description</primary>
16719 <primary>shobj_description</primary>
16723 <primary>comment</primary>
16724 <secondary sortas="database objects">about database objects</secondary>
16728 The functions shown in <xref linkend="functions-info-comment-table">
16729 extract comments previously stored with the <xref linkend="sql-comment">
16730 command. A null value is returned if no
16731 comment could be found for the specified parameters.
16734 <table id="functions-info-comment-table">
16735 <title>Comment Information Functions</title>
16738 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16743 <entry><literal><function>col_description(<parameter>table_oid</parameter>, <parameter>column_number</parameter>)</function></literal></entry>
16744 <entry><type>text</type></entry>
16745 <entry>get comment for a table column</entry>
16748 <entry><literal><function>obj_description(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</function></literal></entry>
16749 <entry><type>text</type></entry>
16750 <entry>get comment for a database object</entry>
16753 <entry><literal><function>obj_description(<parameter>object_oid</parameter>)</function></literal></entry>
16754 <entry><type>text</type></entry>
16755 <entry>get comment for a database object (<emphasis>deprecated</emphasis>)</entry>
16758 <entry><literal><function>shobj_description(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</function></literal></entry>
16759 <entry><type>text</type></entry>
16760 <entry>get comment for a shared database object</entry>
16767 <function>col_description</function> returns the comment for a table
16768 column, which is specified by the OID of its table and its column number.
16769 (<function>obj_description</function> cannot be used for table columns
16770 since columns do not have OIDs of their own.)
16774 The two-parameter form of <function>obj_description</function> returns the
16775 comment for a database object specified by its OID and the name of the
16776 containing system catalog. For example,
16777 <literal>obj_description(123456,'pg_class')</literal>
16778 would retrieve the comment for the table with OID 123456.
16779 The one-parameter form of <function>obj_description</function> requires only
16780 the object OID. It is deprecated since there is no guarantee that
16781 OIDs are unique across different system catalogs; therefore, the wrong
16782 comment might be returned.
16786 <function>shobj_description</function> is used just like
16787 <function>obj_description</function> except it is used for retrieving
16788 comments on shared objects. Some system catalogs are global to all
16789 databases within each cluster, and the descriptions for objects in them
16790 are stored globally as well.
16794 <primary>txid_current</primary>
16798 <primary>txid_current_snapshot</primary>
16802 <primary>txid_snapshot_xip</primary>
16806 <primary>txid_snapshot_xmax</primary>
16810 <primary>txid_snapshot_xmin</primary>
16814 <primary>txid_visible_in_snapshot</primary>
16818 The functions shown in <xref linkend="functions-txid-snapshot">
16819 provide server transaction information in an exportable form. The main
16820 use of these functions is to determine which transactions were committed
16821 between two snapshots.
16824 <table id="functions-txid-snapshot">
16825 <title>Transaction IDs and Snapshots</title>
16828 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16833 <entry><literal><function>txid_current()</function></literal></entry>
16834 <entry><type>bigint</type></entry>
16835 <entry>get current transaction ID, assigning a new one if the current transaction does not have one</entry>
16838 <entry><literal><function>txid_current_snapshot()</function></literal></entry>
16839 <entry><type>txid_snapshot</type></entry>
16840 <entry>get current snapshot</entry>
16843 <entry><literal><function>txid_snapshot_xip(<parameter>txid_snapshot</parameter>)</function></literal></entry>
16844 <entry><type>setof bigint</type></entry>
16845 <entry>get in-progress transaction IDs in snapshot</entry>
16848 <entry><literal><function>txid_snapshot_xmax(<parameter>txid_snapshot</parameter>)</function></literal></entry>
16849 <entry><type>bigint</type></entry>
16850 <entry>get <literal>xmax</literal> of snapshot</entry>
16853 <entry><literal><function>txid_snapshot_xmin(<parameter>txid_snapshot</parameter>)</function></literal></entry>
16854 <entry><type>bigint</type></entry>
16855 <entry>get <literal>xmin</literal> of snapshot</entry>
16858 <entry><literal><function>txid_visible_in_snapshot(<parameter>bigint</parameter>, <parameter>txid_snapshot</parameter>)</function></literal></entry>
16859 <entry><type>boolean</type></entry>
16860 <entry>is transaction ID visible in snapshot? (do not use with subtransaction ids)</entry>
16867 The internal transaction ID type (<type>xid</>) is 32 bits wide and
16868 wraps around every 4 billion transactions. However, these functions
16869 export a 64-bit format that is extended with an <quote>epoch</> counter
16870 so it will not wrap around during the life of an installation.
16871 The data type used by these functions, <type>txid_snapshot</type>,
16872 stores information about transaction ID
16873 visibility at a particular moment in time. Its components are
16874 described in <xref linkend="functions-txid-snapshot-parts">.
16877 <table id="functions-txid-snapshot-parts">
16878 <title>Snapshot Components</title>
16882 <entry>Name</entry>
16883 <entry>Description</entry>
16890 <entry><type>xmin</type></entry>
16892 Earliest transaction ID (txid) that is still active. All earlier
16893 transactions will either be committed and visible, or rolled
16899 <entry><type>xmax</type></entry>
16901 First as-yet-unassigned txid. All txids greater than or equal to this
16902 are not yet started as of the time of the snapshot, and thus invisible.
16907 <entry><type>xip_list</type></entry>
16909 Active txids at the time of the snapshot. The list
16910 includes only those active txids between <literal>xmin</>
16911 and <literal>xmax</>; there might be active txids higher
16912 than <literal>xmax</>. A txid that is <literal>xmin <= txid <
16913 xmax</literal> and not in this list was already completed
16914 at the time of the snapshot, and thus either visible or
16915 dead according to its commit status. The list does not
16916 include txids of subtransactions.
16925 <type>txid_snapshot</>'s textual representation is
16926 <literal><replaceable>xmin</>:<replaceable>xmax</>:<replaceable>xip_list</></literal>.
16927 For example <literal>10:20:10,14,15</literal> means
16928 <literal>xmin=10, xmax=20, xip_list=10, 14, 15</literal>.
16932 The functions shown in <xref linkend="functions-commit-timestamp">
16933 provide information about transactions that have been already committed.
16934 These functions mainly provide information about when the transactions
16935 were committed. They only provide useful data when
16936 <xref linkend="guc-track-commit-timestamp"> configuration option is enabled
16937 and only for transactions that were committed after it was enabled.
16940 <table id="functions-commit-timestamp">
16941 <title>Committed transaction information</title>
16944 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16950 <indexterm><primary>pg_xact_commit_timestamp</primary></indexterm>
16951 <literal><function>pg_xact_commit_timestamp(<parameter>xid</parameter>)</function></literal>
16953 <entry><type>timestamp with time zone</type></entry>
16954 <entry>get commit timestamp of a transaction</entry>
16959 <indexterm><primary>pg_last_committed_xact</primary></indexterm>
16960 <literal><function>pg_last_committed_xact()</function></literal>
16962 <entry><parameter>xid</> <type>xid</>, <parameter>timestamp</> <type>timestamp with time zone</></entry>
16963 <entry>get transaction ID and commit timestamp of latest committed transaction</entry>
16970 The functions shown in <xref linkend="functions-controldata">
16971 print information initialized during <command>initdb</>, such
16972 as the catalog version. They also show information about write-ahead
16973 logging and checkpoint processing. This information is cluster-wide,
16974 and not specific to any one database. They provide most of the same
16975 information, from the same source, as
16976 <xref linkend="APP-PGCONTROLDATA">, although in a form better suited
16977 to <acronym>SQL</acronym> functions.
16980 <table id="functions-controldata">
16981 <title>Control Data Functions</title>
16984 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16990 <indexterm><primary>pg_control_checkpoint</primary></indexterm>
16991 <literal><function>pg_control_checkpoint()</function></literal>
16993 <entry><type>record</type></entry>
16995 Returns information about current checkpoint state.
17001 <indexterm><primary>pg_control_system</primary></indexterm>
17002 <literal><function>pg_control_system()</function></literal>
17004 <entry><type>record</type></entry>
17006 Returns information about current controldata file state.
17012 <indexterm><primary>pg_control_init</primary></indexterm>
17013 <literal><function>pg_control_init()</function></literal>
17015 <entry><type>record</type></entry>
17017 Returns information about cluster initialization state.
17023 <indexterm><primary>pg_control_recovery</primary></indexterm>
17024 <literal><function>pg_control_recovery()</function></literal>
17026 <entry><type>record</type></entry>
17028 Returns information about recovery state.
17037 <function>pg_control_checkpoint</> returns a record, shown in
17038 <xref linkend="functions-pg-control-checkpoint">
17041 <table id="functions-pg-control-checkpoint">
17042 <title><function>pg_control_checkpoint</> Columns</title>
17046 <entry>Column Name</entry>
17047 <entry>Data Type</entry>
17054 <entry>checkpoint_location</entry>
17055 <entry><type>pg_lsn</type></entry>
17059 <entry>prior_location</entry>
17060 <entry><type>pg_lsn</type></entry>
17064 <entry>redo_location</entry>
17065 <entry><type>pg_lsn</type></entry>
17069 <entry>redo_wal_file</entry>
17070 <entry><type>text</type></entry>
17074 <entry>timeline_id</entry>
17075 <entry><type>integer</type></entry>
17079 <entry>prev_timeline_id</entry>
17080 <entry><type>integer</type></entry>
17084 <entry>full_page_writes</entry>
17085 <entry><type>boolean</type></entry>
17089 <entry>next_xid</entry>
17090 <entry><type>text</type></entry>
17094 <entry>next_oid</entry>
17095 <entry><type>oid</type></entry>
17099 <entry>next_multixact_id</entry>
17100 <entry><type>xid</type></entry>
17104 <entry>next_multi_offset</entry>
17105 <entry><type>xid</type></entry>
17109 <entry>oldest_xid</entry>
17110 <entry><type>xid</type></entry>
17114 <entry>oldest_xid_dbid</entry>
17115 <entry><type>oid</type></entry>
17119 <entry>oldest_active_xid</entry>
17120 <entry><type>xid</type></entry>
17124 <entry>oldest_multi_xid</entry>
17125 <entry><type>xid</type></entry>
17129 <entry>oldest_multi_dbid</entry>
17130 <entry><type>oid</type></entry>
17134 <entry>oldest_commit_ts_xid</entry>
17135 <entry><type>xid</type></entry>
17139 <entry>newest_commit_ts_xid</entry>
17140 <entry><type>xid</type></entry>
17144 <entry>checkpoint_time</entry>
17145 <entry><type>timestamp with time zone</type></entry>
17153 <function>pg_control_system</> returns a record, shown in
17154 <xref linkend="functions-pg-control-system">
17157 <table id="functions-pg-control-system">
17158 <title><function>pg_control_system</> Columns</title>
17162 <entry>Column Name</entry>
17163 <entry>Data Type</entry>
17170 <entry>pg_control_version</entry>
17171 <entry><type>integer</type></entry>
17175 <entry>catalog_version_no</entry>
17176 <entry><type>integer</type></entry>
17180 <entry>system_identifier</entry>
17181 <entry><type>bigint</type></entry>
17185 <entry>pg_control_last_modified</entry>
17186 <entry><type>timestamp with time zone</type></entry>
17194 <function>pg_control_init</> returns a record, shown in
17195 <xref linkend="functions-pg-control-init">
17198 <table id="functions-pg-control-init">
17199 <title><function>pg_control_init</> Columns</title>
17203 <entry>Column Name</entry>
17204 <entry>Data Type</entry>
17211 <entry>max_data_alignment</entry>
17212 <entry><type>integer</type></entry>
17216 <entry>database_block_size</entry>
17217 <entry><type>integer</type></entry>
17221 <entry>blocks_per_segment</entry>
17222 <entry><type>integer</type></entry>
17226 <entry>wal_block_size</entry>
17227 <entry><type>integer</type></entry>
17231 <entry>bytes_per_wal_segment</entry>
17232 <entry><type>integer</type></entry>
17236 <entry>max_identifier_length</entry>
17237 <entry><type>integer</type></entry>
17241 <entry>max_index_columns</entry>
17242 <entry><type>integer</type></entry>
17246 <entry>max_toast_chunk_size</entry>
17247 <entry><type>integer</type></entry>
17251 <entry>large_object_chunk_size</entry>
17252 <entry><type>integer</type></entry>
17256 <entry>bigint_timestamps</entry>
17257 <entry><type>boolean</type></entry>
17261 <entry>float4_pass_by_value</entry>
17262 <entry><type>boolean</type></entry>
17266 <entry>float8_pass_by_value</entry>
17267 <entry><type>boolean</type></entry>
17271 <entry>data_page_checksum_version</entry>
17272 <entry><type>integer</type></entry>
17280 <function>pg_control_recovery</> returns a record, shown in
17281 <xref linkend="functions-pg-control-recovery">
17284 <table id="functions-pg-control-recovery">
17285 <title><function>pg_control_recovery</> Columns</title>
17289 <entry>Column Name</entry>
17290 <entry>Data Type</entry>
17297 <entry>min_recovery_end_location</entry>
17298 <entry><type>pg_lsn</type></entry>
17302 <entry>min_recovery_end_timeline</entry>
17303 <entry><type>integer</type></entry>
17307 <entry>backup_start_location</entry>
17308 <entry><type>pg_lsn</type></entry>
17312 <entry>backup_end_location</entry>
17313 <entry><type>pg_lsn</type></entry>
17317 <entry>end_of_backup_record_required</entry>
17318 <entry><type>boolean</type></entry>
17327 <sect1 id="functions-admin">
17328 <title>System Administration Functions</title>
17331 The functions described in this section are used to control and
17332 monitor a <productname>PostgreSQL</> installation.
17335 <sect2 id="functions-admin-set">
17336 <title>Configuration Settings Functions</title>
17339 <xref linkend="functions-admin-set-table"> shows the functions
17340 available to query and alter run-time configuration parameters.
17343 <table id="functions-admin-set-table">
17344 <title>Configuration Settings Functions</title>
17347 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
17354 <primary>current_setting</primary>
17356 <literal><function>current_setting(<parameter>setting_name</parameter> [, <parameter>missing_ok</parameter> ])</function></literal>
17358 <entry><type>text</type></entry>
17359 <entry>get current value of setting</entry>
17364 <primary>set_config</primary>
17366 <literal><function>set_config(<parameter>setting_name</parameter>,
17367 <parameter>new_value</parameter>,
17368 <parameter>is_local</parameter>)</function></literal>
17370 <entry><type>text</type></entry>
17371 <entry>set parameter and return new value</entry>
17378 <primary>SET</primary>
17382 <primary>SHOW</primary>
17386 <primary>configuration</primary>
17387 <secondary sortas="server">of the server</secondary>
17388 <tertiary>functions</tertiary>
17392 The function <function>current_setting</function> yields the
17393 current value of the setting <parameter>setting_name</parameter>.
17394 It corresponds to the <acronym>SQL</acronym> command
17395 <command>SHOW</command>. An example:
17397 SELECT current_setting('datestyle');
17405 If there is no setting named <parameter>setting_name</parameter>,
17406 <function>current_setting</function> throws an error
17407 unless <parameter>missing_ok</parameter> is supplied and is
17408 <literal>true</literal>.
17412 <function>set_config</function> sets the parameter
17413 <parameter>setting_name</parameter> to
17414 <parameter>new_value</parameter>. If
17415 <parameter>is_local</parameter> is <literal>true</literal>, the
17416 new value will only apply to the current transaction. If you want
17417 the new value to apply for the current session, use
17418 <literal>false</literal> instead. The function corresponds to the
17419 SQL command <command>SET</command>. An example:
17421 SELECT set_config('log_statement_stats', 'off', false);
17432 <sect2 id="functions-admin-signal">
17433 <title>Server Signaling Functions</title>
17436 <primary>pg_cancel_backend</primary>
17439 <primary>pg_reload_conf</primary>
17442 <primary>pg_rotate_logfile</primary>
17445 <primary>pg_terminate_backend</primary>
17449 <primary>signal</primary>
17450 <secondary sortas="backend">backend processes</secondary>
17454 The functions shown in <xref
17455 linkend="functions-admin-signal-table"> send control signals to
17456 other server processes. Use of these functions is restricted to
17457 superusers by default but access may be granted to others with the
17458 <command>GRANT</command>, with noted exceptions.
17461 <table id="functions-admin-signal-table">
17462 <title>Server Signaling Functions</title>
17465 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
17472 <literal><function>pg_cancel_backend(<parameter>pid</parameter> <type>int</>)</function></literal>
17474 <entry><type>boolean</type></entry>
17475 <entry>Cancel a backend's current query. This is also allowed if the
17476 calling role is a member of the role whose backend is being canceled or
17477 the calling role has been granted <literal>pg_signal_backend</literal>,
17478 however only superusers can cancel superuser backends.
17483 <literal><function>pg_reload_conf()</function></literal>
17485 <entry><type>boolean</type></entry>
17486 <entry>Cause server processes to reload their configuration files</entry>
17490 <literal><function>pg_rotate_logfile()</function></literal>
17492 <entry><type>boolean</type></entry>
17493 <entry>Rotate server's log file</entry>
17497 <literal><function>pg_terminate_backend(<parameter>pid</parameter> <type>int</>)</function></literal>
17499 <entry><type>boolean</type></entry>
17500 <entry>Terminate a backend. This is also allowed if the calling role
17501 is a member of the role whose backend is being terminated or the
17502 calling role has been granted <literal>pg_signal_backend</literal>,
17503 however only superusers can terminate superuser backends.
17511 Each of these functions returns <literal>true</literal> if
17512 successful and <literal>false</literal> otherwise.
17516 <function>pg_cancel_backend</> and <function>pg_terminate_backend</>
17517 send signals (<systemitem>SIGINT</> or <systemitem>SIGTERM</>
17518 respectively) to backend processes identified by process ID.
17519 The process ID of an active backend can be found from
17520 the <structfield>pid</structfield> column of the
17521 <structname>pg_stat_activity</structname> view, or by listing the
17522 <command>postgres</command> processes on the server (using
17523 <application>ps</> on Unix or the <application>Task
17524 Manager</> on <productname>Windows</>).
17525 The role of an active backend can be found from the
17526 <structfield>usename</structfield> column of the
17527 <structname>pg_stat_activity</structname> view.
17531 <function>pg_reload_conf</> sends a <systemitem>SIGHUP</> signal
17532 to the server, causing configuration files
17533 to be reloaded by all server processes.
17537 <function>pg_rotate_logfile</> signals the log-file manager to switch
17538 to a new output file immediately. This works only when the built-in
17539 log collector is running, since otherwise there is no log-file manager
17545 <sect2 id="functions-admin-backup">
17546 <title>Backup Control Functions</title>
17549 <primary>backup</primary>
17552 <primary>pg_create_restore_point</primary>
17555 <primary>pg_current_xlog_flush_location</primary>
17558 <primary>pg_current_xlog_insert_location</primary>
17561 <primary>pg_current_xlog_location</primary>
17564 <primary>pg_start_backup</primary>
17567 <primary>pg_stop_backup</primary>
17570 <primary>pg_is_in_backup</primary>
17573 <primary>pg_backup_start_time</primary>
17576 <primary>pg_switch_xlog</primary>
17579 <primary>pg_xlogfile_name</primary>
17582 <primary>pg_xlogfile_name_offset</primary>
17585 <primary>pg_xlog_location_diff</primary>
17589 The functions shown in <xref
17590 linkend="functions-admin-backup-table"> assist in making on-line backups.
17591 These functions cannot be executed during recovery (except
17592 <function>pg_is_in_backup</function>, <function>pg_backup_start_time</function>
17593 and <function>pg_xlog_location_diff</function>).
17596 <table id="functions-admin-backup-table">
17597 <title>Backup Control Functions</title>
17600 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
17607 <literal><function>pg_create_restore_point(<parameter>name</> <type>text</>)</function></literal>
17609 <entry><type>pg_lsn</type></entry>
17610 <entry>Create a named point for performing restore (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17614 <literal><function>pg_current_xlog_flush_location()</function></literal>
17616 <entry><type>pg_lsn</type></entry>
17617 <entry>Get current transaction log flush location</entry>
17621 <literal><function>pg_current_xlog_insert_location()</function></literal>
17623 <entry><type>pg_lsn</type></entry>
17624 <entry>Get current transaction log insert location</entry>
17628 <literal><function>pg_current_xlog_location()</function></literal>
17630 <entry><type>pg_lsn</type></entry>
17631 <entry>Get current transaction log write location</entry>
17635 <literal><function>pg_start_backup(<parameter>label</> <type>text</> <optional>, <parameter>fast</> <type>boolean</> <optional>, <parameter>exclusive</> <type>boolean</> </optional></optional>)</function></literal>
17637 <entry><type>pg_lsn</type></entry>
17638 <entry>Prepare for performing on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17642 <literal><function>pg_stop_backup()</function></literal>
17644 <entry><type>pg_lsn</type></entry>
17645 <entry>Finish performing exclusive on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17649 <literal><function>pg_stop_backup(<parameter>exclusive</> <type>boolean</>)</function></literal>
17651 <entry><type>setof record</type></entry>
17652 <entry>Finish performing exclusive or non-exclusive on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17656 <literal><function>pg_is_in_backup()</function></literal>
17658 <entry><type>bool</type></entry>
17659 <entry>True if an on-line exclusive backup is still in progress.</entry>
17663 <literal><function>pg_backup_start_time()</function></literal>
17665 <entry><type>timestamp with time zone</type></entry>
17666 <entry>Get start time of an on-line exclusive backup in progress.</entry>
17670 <literal><function>pg_switch_xlog()</function></literal>
17672 <entry><type>pg_lsn</type></entry>
17673 <entry>Force switch to a new transaction log file (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17677 <literal><function>pg_xlogfile_name(<parameter>location</> <type>pg_lsn</>)</function></literal>
17679 <entry><type>text</type></entry>
17680 <entry>Convert transaction log location string to file name</entry>
17684 <literal><function>pg_xlogfile_name_offset(<parameter>location</> <type>pg_lsn</>)</function></literal>
17686 <entry><type>text</>, <type>integer</></entry>
17687 <entry>Convert transaction log location string to file name and decimal byte offset within file</entry>
17691 <literal><function>pg_xlog_location_diff(<parameter>location</> <type>pg_lsn</>, <parameter>location</> <type>pg_lsn</>)</function></literal>
17693 <entry><type>numeric</></entry>
17694 <entry>Calculate the difference between two transaction log locations</entry>
17701 <function>pg_start_backup</> accepts an arbitrary user-defined label for
17702 the backup. (Typically this would be the name under which the backup dump
17703 file will be stored.) When used in exclusive mode, the function writes a
17704 backup label file (<filename>backup_label</>) and, if there are any links
17705 in the <filename>pg_tblspc/</> directory, a tablespace map file
17706 (<filename>tablespace_map</>) into the database cluster's data directory,
17707 performs a checkpoint, and then returns the backup's starting transaction
17708 log location as text. The user can ignore this result value, but it is
17709 provided in case it is useful. When used in non-exclusive mode, the
17710 contents of these files are instead returned by the
17711 <function>pg_stop_backup</> function, and should be written to the backup
17715 postgres=# select pg_start_backup('label_goes_here');
17721 There is an optional second parameter of type <type>boolean</type>. If <literal>true</>,
17722 it specifies executing <function>pg_start_backup</> as quickly as
17723 possible. This forces an immediate checkpoint which will cause a
17724 spike in I/O operations, slowing any concurrently executing queries.
17728 In an exclusive backup, <function>pg_stop_backup</> removes the label file
17729 and, if it exists, the <filename>tablespace_map</> file created by
17730 <function>pg_start_backup</>. In a non-exclusive backup, the contents of
17731 the <filename>backup_label</> and <filename>tablespace_map</> are returned
17732 in the result of the function, and should be written to files in the
17733 backup (and not in the data directory).
17737 The function also creates a backup history file in the transaction log
17738 archive area. The history file includes the label given to
17739 <function>pg_start_backup</>, the starting and ending transaction log locations for
17740 the backup, and the starting and ending times of the backup. The return
17741 value is the backup's ending transaction log location (which again
17742 can be ignored). After recording the ending location, the current
17743 transaction log insertion
17744 point is automatically advanced to the next transaction log file, so that the
17745 ending transaction log file can be archived immediately to complete the backup.
17749 <function>pg_switch_xlog</> moves to the next transaction log file, allowing the
17750 current file to be archived (assuming you are using continuous archiving).
17751 The return value is the ending transaction log location + 1 within the just-completed transaction log file.
17752 If there has been no transaction log activity since the last transaction log switch,
17753 <function>pg_switch_xlog</> does nothing and returns the start location
17754 of the transaction log file currently in use.
17758 <function>pg_create_restore_point</> creates a named transaction log
17759 record that can be used as recovery target, and returns the corresponding
17760 transaction log location. The given name can then be used with
17761 <xref linkend="recovery-target-name"> to specify the point up to which
17762 recovery will proceed. Avoid creating multiple restore points with the
17763 same name, since recovery will stop at the first one whose name matches
17764 the recovery target.
17768 <function>pg_current_xlog_location</> displays the current transaction log write
17769 location in the same format used by the above functions. Similarly,
17770 <function>pg_current_xlog_insert_location</> displays the current transaction log
17771 insertion point and <function>pg_current_xlog_flush_location</> displays the
17772 current transaction log flush point. The insertion point is the <quote>logical</>
17773 end of the transaction log at any instant, while the write location is the end of
17774 what has actually been written out from the server's internal buffers and flush
17775 location is the location guaranteed to be written to durable storage. The write
17776 location is the end of what can be examined from outside the server, and is usually
17777 what you want if you are interested in archiving partially-complete transaction log
17778 files. The insertion and flush points are made available primarily for server
17779 debugging purposes. These are both read-only operations and do not
17780 require superuser permissions.
17784 You can use <function>pg_xlogfile_name_offset</> to extract the
17785 corresponding transaction log file name and byte offset from the results of any of the
17786 above functions. For example:
17788 postgres=# SELECT * FROM pg_xlogfile_name_offset(pg_stop_backup());
17789 file_name | file_offset
17790 --------------------------+-------------
17791 00000001000000000000000D | 4039624
17794 Similarly, <function>pg_xlogfile_name</> extracts just the transaction log file name.
17795 When the given transaction log location is exactly at a transaction log file boundary, both
17796 these functions return the name of the preceding transaction log file.
17797 This is usually the desired behavior for managing transaction log archiving
17798 behavior, since the preceding file is the last one that currently
17799 needs to be archived.
17803 <function>pg_xlog_location_diff</> calculates the difference in bytes
17804 between two transaction log locations. It can be used with
17805 <structname>pg_stat_replication</structname> or some functions shown in
17806 <xref linkend="functions-admin-backup-table"> to get the replication lag.
17810 For details about proper usage of these functions, see
17811 <xref linkend="continuous-archiving">.
17816 <sect2 id="functions-recovery-control">
17817 <title>Recovery Control Functions</title>
17820 <primary>pg_is_in_recovery</primary>
17823 <primary>pg_last_xlog_receive_location</primary>
17826 <primary>pg_last_xlog_replay_location</primary>
17829 <primary>pg_last_xact_replay_timestamp</primary>
17833 The functions shown in <xref
17834 linkend="functions-recovery-info-table"> provide information
17835 about the current status of the standby.
17836 These functions may be executed both during recovery and in normal running.
17839 <table id="functions-recovery-info-table">
17840 <title>Recovery Information Functions</title>
17843 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
17850 <literal><function>pg_is_in_recovery()</function></literal>
17852 <entry><type>bool</type></entry>
17853 <entry>True if recovery is still in progress.
17858 <literal><function>pg_last_xlog_receive_location()</function></literal>
17860 <entry><type>pg_lsn</type></entry>
17861 <entry>Get last transaction log location received and synced to disk by
17862 streaming replication. While streaming replication is in progress
17863 this will increase monotonically. If recovery has completed this will
17865 the value of the last WAL record received and synced to disk during
17866 recovery. If streaming replication is disabled, or if it has not yet
17867 started, the function returns NULL.
17872 <literal><function>pg_last_xlog_replay_location()</function></literal>
17874 <entry><type>pg_lsn</type></entry>
17875 <entry>Get last transaction log location replayed during recovery.
17876 If recovery is still in progress this will increase monotonically.
17877 If recovery has completed then this value will remain static at
17878 the value of the last WAL record applied during that recovery.
17879 When the server has been started normally without recovery
17880 the function returns NULL.
17885 <literal><function>pg_last_xact_replay_timestamp()</function></literal>
17887 <entry><type>timestamp with time zone</type></entry>
17888 <entry>Get time stamp of last transaction replayed during recovery.
17889 This is the time at which the commit or abort WAL record for that
17890 transaction was generated on the primary.
17891 If no transactions have been replayed during recovery, this function
17892 returns NULL. Otherwise, if recovery is still in progress this will
17893 increase monotonically. If recovery has completed then this value will
17894 remain static at the value of the last transaction applied during that
17895 recovery. When the server has been started normally without recovery
17896 the function returns NULL.
17904 <primary>pg_is_xlog_replay_paused</primary>
17907 <primary>pg_xlog_replay_pause</primary>
17910 <primary>pg_xlog_replay_resume</primary>
17914 The functions shown in <xref
17915 linkend="functions-recovery-control-table"> control the progress of recovery.
17916 These functions may be executed only during recovery.
17919 <table id="functions-recovery-control-table">
17920 <title>Recovery Control Functions</title>
17923 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
17930 <literal><function>pg_is_xlog_replay_paused()</function></literal>
17932 <entry><type>bool</type></entry>
17933 <entry>True if recovery is paused.
17938 <literal><function>pg_xlog_replay_pause()</function></literal>
17940 <entry><type>void</type></entry>
17941 <entry>Pauses recovery immediately (restricted to superusers by default, but other users can be granted EXECUTE to run the function).
17946 <literal><function>pg_xlog_replay_resume()</function></literal>
17948 <entry><type>void</type></entry>
17949 <entry>Restarts recovery if it was paused (restricted to superusers by default, but other users can be granted EXECUTE to run the function).
17957 While recovery is paused no further database changes are applied.
17958 If in hot standby, all new queries will see the same consistent snapshot
17959 of the database, and no further query conflicts will be generated until
17960 recovery is resumed.
17964 If streaming replication is disabled, the paused state may continue
17965 indefinitely without problem. While streaming replication is in
17966 progress WAL records will continue to be received, which will
17967 eventually fill available disk space, depending upon the duration of
17968 the pause, the rate of WAL generation and available disk space.
17973 <sect2 id="functions-snapshot-synchronization">
17974 <title>Snapshot Synchronization Functions</title>
17977 <primary>pg_export_snapshot</primary>
17981 <productname>PostgreSQL</> allows database sessions to synchronize their
17982 snapshots. A <firstterm>snapshot</> determines which data is visible to the
17983 transaction that is using the snapshot. Synchronized snapshots are
17984 necessary when two or more sessions need to see identical content in the
17985 database. If two sessions just start their transactions independently,
17986 there is always a possibility that some third transaction commits
17987 between the executions of the two <command>START TRANSACTION</> commands,
17988 so that one session sees the effects of that transaction and the other
17993 To solve this problem, <productname>PostgreSQL</> allows a transaction to
17994 <firstterm>export</> the snapshot it is using. As long as the exporting
17995 transaction remains open, other transactions can <firstterm>import</> its
17996 snapshot, and thereby be guaranteed that they see exactly the same view
17997 of the database that the first transaction sees. But note that any
17998 database changes made by any one of these transactions remain invisible
17999 to the other transactions, as is usual for changes made by uncommitted
18000 transactions. So the transactions are synchronized with respect to
18001 pre-existing data, but act normally for changes they make themselves.
18005 Snapshots are exported with the <function>pg_export_snapshot</> function,
18006 shown in <xref linkend="functions-snapshot-synchronization-table">, and
18007 imported with the <xref linkend="sql-set-transaction"> command.
18010 <table id="functions-snapshot-synchronization-table">
18011 <title>Snapshot Synchronization Functions</title>
18014 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18021 <literal><function>pg_export_snapshot()</function></literal>
18023 <entry><type>text</type></entry>
18024 <entry>Save the current snapshot and return its identifier</entry>
18031 The function <function>pg_export_snapshot</> saves the current snapshot
18032 and returns a <type>text</> string identifying the snapshot. This string
18033 must be passed (outside the database) to clients that want to import the
18034 snapshot. The snapshot is available for import only until the end of the
18035 transaction that exported it. A transaction can export more than one
18036 snapshot, if needed. Note that doing so is only useful in <literal>READ
18037 COMMITTED</> transactions, since in <literal>REPEATABLE READ</> and
18038 higher isolation levels, transactions use the same snapshot throughout
18039 their lifetime. Once a transaction has exported any snapshots, it cannot
18040 be prepared with <xref linkend="sql-prepare-transaction">.
18044 See <xref linkend="sql-set-transaction"> for details of how to use an
18049 <sect2 id="functions-replication">
18050 <title>Replication Functions</title>
18053 The functions shown
18054 in <xref linkend="functions-replication-table"> are for
18055 controlling and interacting with replication features.
18056 See <xref linkend="streaming-replication">,
18057 <xref linkend="streaming-replication-slots">, and
18058 <xref linkend="replication-origins">
18059 for information about the underlying features. Use of these
18060 functions is restricted to superusers.
18064 Many of these functions have equivalent commands in the replication
18065 protocol; see <xref linkend="protocol-replication">.
18069 The functions described in
18070 <xref linkend="functions-admin-backup">,
18071 <xref linkend="functions-recovery-control">, and
18072 <xref linkend="functions-snapshot-synchronization">
18073 are also relevant for replication.
18076 <table id="functions-replication-table">
18077 <title>Replication <acronym>SQL</acronym> Functions</title>
18081 <entry>Function</entry>
18082 <entry>Return Type</entry>
18083 <entry>Description</entry>
18090 <primary>pg_create_physical_replication_slot</primary>
18092 <literal><function>pg_create_physical_replication_slot(<parameter>slot_name</parameter> <type>name</type> <optional>, <parameter>immediately_reserve</> <type>boolean</> </optional>)</function></literal>
18095 (<parameter>slot_name</parameter> <type>name</type>, <parameter>xlog_position</parameter> <type>pg_lsn</type>)
18098 Creates a new physical replication slot named
18099 <parameter>slot_name</parameter>. The optional second parameter,
18100 when <literal>true</>, specifies that the <acronym>LSN</> for this
18101 replication slot be reserved immediately; otherwise
18102 the <acronym>LSN</> is reserved on first connection from a streaming
18103 replication client. Streaming changes from a physical slot is only
18104 possible with the streaming-replication protocol —
18105 see <xref linkend="protocol-replication">. This function corresponds
18106 to the replication protocol command <literal>CREATE_REPLICATION_SLOT
18107 ... PHYSICAL</literal>.
18113 <primary>pg_drop_replication_slot</primary>
18115 <literal><function>pg_drop_replication_slot(<parameter>slot_name</parameter> <type>name</type>)</function></literal>
18121 Drops the physical or logical replication slot
18122 named <parameter>slot_name</parameter>. Same as replication protocol
18123 command <literal>DROP_REPLICATION_SLOT</>.
18130 <primary>pg_create_logical_replication_slot</primary>
18132 <literal><function>pg_create_logical_replication_slot(<parameter>slot_name</parameter> <type>name</type>, <parameter>plugin</parameter> <type>name</type>)</function></literal>
18135 (<parameter>slot_name</parameter> <type>name</type>, <parameter>xlog_position</parameter> <type>pg_lsn</type>)
18138 Creates a new logical (decoding) replication slot named
18139 <parameter>slot_name</parameter> using the output plugin
18140 <parameter>plugin</parameter>. A call to this function has the same
18141 effect as the replication protocol command
18142 <literal>CREATE_REPLICATION_SLOT ... LOGICAL</literal>.
18149 <primary>pg_logical_slot_get_changes</primary>
18151 <literal><function>pg_logical_slot_get_changes(<parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>int</type>, VARIADIC <parameter>options</parameter> <type>text[]</type>)</function></literal>
18154 (<parameter>location</parameter> <type>pg_lsn</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>text</type>)
18157 Returns changes in the slot <parameter>slot_name</parameter>, starting
18158 from the point at which since changes have been consumed last. If
18159 <parameter>upto_lsn</> and <parameter>upto_nchanges</> are NULL,
18160 logical decoding will continue until end of WAL. If
18161 <parameter>upto_lsn</> is non-NULL, decoding will include only
18162 those transactions which commit prior to the specified LSN. If
18163 <parameter>upto_nchanges</parameter> is non-NULL, decoding will
18164 stop when the number of rows produced by decoding exceeds
18165 the specified value. Note, however, that the actual number of
18166 rows returned may be larger, since this limit is only checked after
18167 adding the rows produced when decoding each new transaction commit.
18174 <primary>pg_logical_slot_peek_changes</primary>
18176 <literal><function>pg_logical_slot_peek_changes(<parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>int</type>, VARIADIC <parameter>options</parameter> <type>text[]</type>)</function></literal>
18179 (<parameter>location</parameter> <type>text</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>text</type>)
18183 the <function>pg_logical_slot_get_changes()</function> function,
18184 except that changes are not consumed; that is, they will be returned
18185 again on future calls.
18192 <primary>pg_logical_slot_get_binary_changes</primary>
18194 <literal><function>pg_logical_slot_get_binary_changes(<parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>int</type>, VARIADIC <parameter>options</parameter> <type>text[]</type>)</function></literal>
18197 (<parameter>location</parameter> <type>pg_lsn</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>bytea</type>)
18201 the <function>pg_logical_slot_get_changes()</function> function,
18202 except that changes are returned as <type>bytea</type>.
18209 <primary>pg_logical_slot_peek_binary_changes</primary>
18211 <literal><function>pg_logical_slot_peek_binary_changes(<parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>int</type>, VARIADIC <parameter>options</parameter> <type>text[]</type>)</function></literal>
18214 (<parameter>location</parameter> <type>pg_lsn</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>bytea</type>)
18218 the <function>pg_logical_slot_get_changes()</function> function,
18219 except that changes are returned as <type>bytea</type> and that
18220 changes are not consumed; that is, they will be returned again
18226 <entry id="pg-replication-origin-create">
18228 <primary>pg_replication_origin_create</primary>
18230 <literal><function>pg_replication_origin_create(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18236 Create a replication origin with the given external
18237 name, and return the internal id assigned to it.
18242 <entry id="pg-replication-origin-drop">
18244 <primary>pg_replication_origin_drop</primary>
18246 <literal><function>pg_replication_origin_drop(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18252 Delete a previously created replication origin, including any
18253 associated replay progress.
18260 <primary>pg_replication_origin_oid</primary>
18262 <literal><function>pg_replication_origin_oid(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18268 Lookup a replication origin by name and return the internal id. If no
18269 corresponding replication origin is found an error is thrown.
18274 <entry id="pg-replication-origin-session-setup">
18276 <primary>pg_replication_origin_session_setup</primary>
18278 <literal><function>pg_replication_origin_session_setup(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18284 Mark the current session as replaying from the given
18285 origin, allowing replay progress to be tracked. Use
18286 <function>pg_replication_origin_session_reset</function> to revert.
18287 Can only be used if no previous origin is configured.
18294 <primary>pg_replication_origin_session_reset</primary>
18296 <literal><function>pg_replication_origin_session_reset()</function></literal>
18303 of <function>pg_replication_origin_session_setup()</function>.
18310 <primary>pg_replication_origin_session_is_setup</primary>
18312 <literal><function>pg_replication_origin_session_is_setup()</function></literal>
18318 Has a replication origin been configured in the current session?
18323 <entry id="pg-replication-origin-session-progress">
18325 <primary>pg_replication_origin_session_progress</primary>
18327 <literal><function>pg_replication_origin_session_progress(<parameter>flush</parameter> <type>bool</type>)</function></literal>
18330 <type>pg_lsn</type>
18333 Return the replay position for the replication origin configured in
18334 the current session. The parameter <parameter>flush</parameter>
18335 determines whether the corresponding local transaction will be
18336 guaranteed to have been flushed to disk or not.
18341 <entry id="pg-replication-origin-xact-setup">
18343 <primary>pg_replication_origin_xact_setup</primary>
18345 <literal><function>pg_replication_origin_xact_setup(<parameter>origin_lsn</parameter> <type>pg_lsn</type>, <parameter>origin_timestamp</parameter> <type>timestamptz</type>)</function></literal>
18351 Mark the current transaction as replaying a transaction that has
18352 committed at the given <acronym>LSN</acronym> and timestamp. Can
18353 only be called when a replication origin has previously been
18355 <function>pg_replication_origin_session_setup()</function>.
18360 <entry id="pg-replication-origin-xact-reset">
18362 <primary>pg_replication_origin_xact_reset</primary>
18364 <literal><function>pg_replication_origin_xact_reset()</function></literal>
18370 Cancel the effects of
18371 <function>pg_replication_origin_xact_setup()</function>.
18378 <primary>pg_replication_origin_advance</primary>
18380 <literal>pg_replication_origin_advance<function>(<parameter>node_name</parameter> <type>text</type>, <parameter>pos</parameter> <type>pg_lsn</type>)</function></literal>
18386 Set replication progress for the given node to the given
18387 position. This primarily is useful for setting up the initial position
18388 or a new position after configuration changes and similar. Be aware
18389 that careless use of this function can lead to inconsistently
18395 <entry id="pg-replication-origin-progress">
18397 <primary>pg_replication_origin_progress</primary>
18399 <literal><function>pg_replication_origin_progress(<parameter>node_name</parameter> <type>text</type>, <parameter>flush</parameter> <type>bool</type>)</function></literal>
18402 <type>pg_lsn</type>
18405 Return the replay position for the given replication origin. The
18406 parameter <parameter>flush</parameter> determines whether the
18407 corresponding local transaction will be guaranteed to have been
18408 flushed to disk or not.
18413 <entry id="pg-logical-emit-message-text">
18415 <primary>pg_logical_emit_message</primary>
18417 <literal><function>pg_logical_emit_message(<parameter>transactional</parameter> <type>bool</type>, <parameter>prefix</parameter> <type>text</type>, <parameter>content</parameter> <type>text</type>)</function></literal>
18420 <type>pg_lsn</type>
18423 Emit text logical decoding message. This can be used to pass generic
18424 messages to logical decoding plugins through WAL. The parameter
18425 <parameter>transactional</parameter> specifies if the message should
18426 be part of current transaction or if it should be written immediately
18427 and decoded as soon as the logical decoding reads the record. The
18428 <parameter>prefix</parameter> is textual prefix used by the logical
18429 decoding plugins to easily recognize interesting messages for them.
18430 The <parameter>content</parameter> is the text of the message.
18435 <entry id="pg-logical-emit-message-bytea">
18436 <literal><function>pg_logical_emit_message(<parameter>transactional</parameter> <type>bool</type>, <parameter>prefix</parameter> <type>text</type>, <parameter>content</parameter> <type>bytea</type>)</function></literal>
18439 <type>pg_lsn</type>
18442 Emit binary logical decoding message. This can be used to pass generic
18443 messages to logical decoding plugins through WAL. The parameter
18444 <parameter>transactional</parameter> specifies if the message should
18445 be part of current transaction or if it should be written immediately
18446 and decoded as soon as the logical decoding reads the record. The
18447 <parameter>prefix</parameter> is textual prefix used by the logical
18448 decoding plugins to easily recognize interesting messages for them.
18449 The <parameter>content</parameter> is the binary content of the
18460 <sect2 id="functions-admin-dbobject">
18461 <title>Database Object Management Functions</title>
18464 The functions shown in <xref linkend="functions-admin-dbsize"> calculate
18465 the disk space usage of database objects.
18469 <primary>pg_column_size</primary>
18472 <primary>pg_database_size</primary>
18475 <primary>pg_indexes_size</primary>
18478 <primary>pg_relation_size</primary>
18481 <primary>pg_size_bytes</primary>
18484 <primary>pg_size_pretty</primary>
18487 <primary>pg_table_size</primary>
18490 <primary>pg_tablespace_size</primary>
18493 <primary>pg_total_relation_size</primary>
18496 <table id="functions-admin-dbsize">
18497 <title>Database Object Size Functions</title>
18500 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18506 <entry><literal><function>pg_column_size(<type>any</type>)</function></literal></entry>
18507 <entry><type>int</type></entry>
18508 <entry>Number of bytes used to store a particular value (possibly compressed)</entry>
18512 <literal><function>pg_database_size(<type>oid</type>)</function></literal>
18514 <entry><type>bigint</type></entry>
18515 <entry>Disk space used by the database with the specified OID</entry>
18519 <literal><function>pg_database_size(<type>name</type>)</function></literal>
18521 <entry><type>bigint</type></entry>
18522 <entry>Disk space used by the database with the specified name</entry>
18526 <literal><function>pg_indexes_size(<type>regclass</type>)</function></literal>
18528 <entry><type>bigint</type></entry>
18530 Total disk space used by indexes attached to the specified table
18535 <literal><function>pg_relation_size(<parameter>relation</parameter> <type>regclass</type>, <parameter>fork</parameter> <type>text</type>)</function></literal>
18537 <entry><type>bigint</type></entry>
18539 Disk space used by the specified fork (<literal>'main'</literal>,
18540 <literal>'fsm'</literal>, <literal>'vm'</>, or <literal>'init'</>)
18541 of the specified table or index
18546 <literal><function>pg_relation_size(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
18548 <entry><type>bigint</type></entry>
18550 Shorthand for <literal>pg_relation_size(..., 'main')</literal>
18555 <literal><function>pg_size_bytes(<type>text</type>)</function></literal>
18557 <entry><type>bigint</type></entry>
18559 Converts a size in human-readable format with size units into bytes
18564 <literal><function>pg_size_pretty(<type>bigint</type>)</function></literal>
18566 <entry><type>text</type></entry>
18568 Converts a size in bytes expressed as a 64-bit integer into a
18569 human-readable format with size units
18574 <literal><function>pg_size_pretty(<type>numeric</type>)</function></literal>
18576 <entry><type>text</type></entry>
18578 Converts a size in bytes expressed as a numeric value into a
18579 human-readable format with size units
18584 <literal><function>pg_table_size(<type>regclass</type>)</function></literal>
18586 <entry><type>bigint</type></entry>
18588 Disk space used by the specified table, excluding indexes
18589 (but including TOAST, free space map, and visibility map)
18594 <literal><function>pg_tablespace_size(<type>oid</type>)</function></literal>
18596 <entry><type>bigint</type></entry>
18597 <entry>Disk space used by the tablespace with the specified OID</entry>
18601 <literal><function>pg_tablespace_size(<type>name</type>)</function></literal>
18603 <entry><type>bigint</type></entry>
18604 <entry>Disk space used by the tablespace with the specified name</entry>
18608 <literal><function>pg_total_relation_size(<type>regclass</type>)</function></literal>
18610 <entry><type>bigint</type></entry>
18612 Total disk space used by the specified table,
18613 including all indexes and <acronym>TOAST</> data
18621 <function>pg_column_size</> shows the space used to store any individual
18626 <function>pg_total_relation_size</> accepts the OID or name of a
18627 table or toast table, and returns the total on-disk space used for
18628 that table, including all associated indexes. This function is
18629 equivalent to <function>pg_table_size</function>
18630 <literal>+</> <function>pg_indexes_size</function>.
18634 <function>pg_table_size</> accepts the OID or name of a table and
18635 returns the disk space needed for that table, exclusive of indexes.
18636 (TOAST space, free space map, and visibility map are included.)
18640 <function>pg_indexes_size</> accepts the OID or name of a table and
18641 returns the total disk space used by all the indexes attached to that
18646 <function>pg_database_size</function> and <function>pg_tablespace_size</>
18647 accept the OID or name of a database or tablespace, and return the total
18648 disk space used therein. To use <function>pg_database_size</function>,
18649 you must have <literal>CONNECT</> permission on the specified database
18650 (which is granted by default). To use <function>pg_tablespace_size</>,
18651 you must have <literal>CREATE</> permission on the specified tablespace,
18652 unless it is the default tablespace for the current database.
18656 <function>pg_relation_size</> accepts the OID or name of a table, index
18657 or toast table, and returns the on-disk size in bytes of one fork of
18658 that relation. (Note that for most purposes it is more convenient to
18659 use the higher-level functions <function>pg_total_relation_size</>
18660 or <function>pg_table_size</>, which sum the sizes of all forks.)
18661 With one argument, it returns the size of the main data fork of the
18662 relation. The second argument can be provided to specify which fork
18664 <itemizedlist spacing="compact">
18667 <literal>'main'</literal> returns the size of the main
18668 data fork of the relation.
18673 <literal>'fsm'</literal> returns the size of the Free Space Map
18674 (see <xref linkend="storage-fsm">) associated with the relation.
18679 <literal>'vm'</literal> returns the size of the Visibility Map
18680 (see <xref linkend="storage-vm">) associated with the relation.
18685 <literal>'init'</literal> returns the size of the initialization
18686 fork, if any, associated with the relation.
18693 <function>pg_size_pretty</> can be used to format the result of one of
18694 the other functions in a human-readable way, using bytes, kB, MB, GB or TB
18699 <function>pg_size_bytes</> can be used to get the size in bytes from a
18700 string in human-readable format. The input may have units of bytes, kB,
18701 MB, GB or TB, and is parsed case-insensitively. If no units are specified,
18707 The units kB, MB, GB and TB used by the functions
18708 <function>pg_size_pretty</> and <function>pg_size_bytes</> are defined
18709 using powers of 2 rather than powers of 10, so 1kB is 1024 bytes, 1MB is
18710 1024<superscript>2</> = 1048576 bytes, and so on.
18715 The functions above that operate on tables or indexes accept a
18716 <type>regclass</> argument, which is simply the OID of the table or index
18717 in the <structname>pg_class</> system catalog. You do not have to look up
18718 the OID by hand, however, since the <type>regclass</> data type's input
18719 converter will do the work for you. Just write the table name enclosed in
18720 single quotes so that it looks like a literal constant. For compatibility
18721 with the handling of ordinary <acronym>SQL</acronym> names, the string
18722 will be converted to lower case unless it contains double quotes around
18727 If an OID that does not represent an existing object is passed as
18728 argument to one of the above functions, NULL is returned.
18732 The functions shown in <xref linkend="functions-admin-dblocation"> assist
18733 in identifying the specific disk files associated with database objects.
18737 <primary>pg_relation_filenode</primary>
18740 <primary>pg_relation_filepath</primary>
18743 <primary>pg_filenode_relation</primary>
18746 <table id="functions-admin-dblocation">
18747 <title>Database Object Location Functions</title>
18750 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18757 <literal><function>pg_relation_filenode(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
18759 <entry><type>oid</type></entry>
18761 Filenode number of the specified relation
18766 <literal><function>pg_relation_filepath(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
18768 <entry><type>text</type></entry>
18770 File path name of the specified relation
18775 <literal><function>pg_filenode_relation(<parameter>tablespace</parameter> <type>oid</type>, <parameter>filenode</parameter> <type>oid</type>)</function></literal>
18777 <entry><type>regclass</type></entry>
18779 Find the relation associated with a given tablespace and filenode
18787 <function>pg_relation_filenode</> accepts the OID or name of a table,
18788 index, sequence, or toast table, and returns the <quote>filenode</> number
18789 currently assigned to it. The filenode is the base component of the file
18790 name(s) used for the relation (see <xref linkend="storage-file-layout">
18791 for more information). For most tables the result is the same as
18792 <structname>pg_class</>.<structfield>relfilenode</>, but for certain
18793 system catalogs <structfield>relfilenode</> is zero and this function must
18794 be used to get the correct value. The function returns NULL if passed
18795 a relation that does not have storage, such as a view.
18799 <function>pg_relation_filepath</> is similar to
18800 <function>pg_relation_filenode</>, but it returns the entire file path name
18801 (relative to the database cluster's data directory <varname>PGDATA</>) of
18806 <function>pg_filenode_relation</> is the reverse of
18807 <function>pg_relation_filenode</>. Given a <quote>tablespace</> OID and
18808 a <quote>filenode</>, it returns the associated relation's OID. For a table
18809 in the database's default tablespace, the tablespace can be specified as 0.
18814 <sect2 id="functions-admin-index">
18815 <title>Index Maintenance Functions</title>
18818 <primary>brin_summarize_new_values</primary>
18822 <primary>gin_clean_pending_list</primary>
18826 <xref linkend="functions-admin-index-table"> shows the functions
18827 available for index maintenance tasks.
18828 These functions cannot be executed during recovery.
18829 Use of these functions is restricted to superusers and the owner
18830 of the given index.
18833 <table id="functions-admin-index-table">
18834 <title>Index Maintenance Functions</title>
18837 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
18843 <literal><function>brin_summarize_new_values(<parameter>index_oid</> <type>regclass</>)</function></literal>
18845 <entry><type>integer</type></entry>
18846 <entry>summarize page ranges not already summarized</entry>
18850 <literal><function>gin_clean_pending_list(<parameter>index</> <type>regclass</>)</function></literal>
18852 <entry><type>bigint</type></entry>
18853 <entry>move GIN pending list entries into main index structure</entry>
18860 <function>brin_summarize_new_values</> receives a BRIN index OID as
18861 argument and inspects the index to find page ranges in the base table
18862 that are not currently summarized by the index; for any such range
18863 it creates a new summary index tuple by scanning the table pages.
18864 It returns the number of new page range summaries that were inserted
18869 <function>gin_clean_pending_list</> accepts the OID or name of
18870 a GIN index and cleans up the pending list of the specified GIN index
18871 by moving entries in it to the main GIN data structure in bulk.
18872 It returns the number of pages cleaned up from the pending list.
18873 Note that if the argument is a GIN index built with <literal>fastupdate</>
18874 option disabled, the cleanup does not happen and the return value is 0
18875 because the index doesn't have a pending list.
18876 Please see <xref linkend="gin-fast-update"> and <xref linkend="gin-tips">
18877 for details of the pending list and <literal>fastupdate</> option.
18882 <sect2 id="functions-admin-genfile">
18883 <title>Generic File Access Functions</title>
18886 The functions shown in <xref
18887 linkend="functions-admin-genfile-table"> provide native access to
18888 files on the machine hosting the server. Only files within the
18889 database cluster directory and the <varname>log_directory</> can be
18890 accessed. Use a relative path for files in the cluster directory,
18891 and a path matching the <varname>log_directory</> configuration setting
18892 for log files. Use of these functions is restricted to superusers.
18895 <table id="functions-admin-genfile-table">
18896 <title>Generic File Access Functions</title>
18899 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18906 <literal><function>pg_ls_dir(<parameter>dirname</> <type>text</> [, <parameter>missing_ok</> <type>boolean</>, <parameter>include_dot_dirs</> <type>boolean</>])</function></literal>
18908 <entry><type>setof text</type></entry>
18910 List the contents of a directory.
18915 <literal><function>pg_read_file(<parameter>filename</> <type>text</> [, <parameter>offset</> <type>bigint</>, <parameter>length</> <type>bigint</> [, <parameter>missing_ok</> <type>boolean</>] ])</function></literal>
18917 <entry><type>text</type></entry>
18919 Return the contents of a text file.
18924 <literal><function>pg_read_binary_file(<parameter>filename</> <type>text</> [, <parameter>offset</> <type>bigint</>, <parameter>length</> <type>bigint</> [, <parameter>missing_ok</> <type>boolean</>] ])</function></literal>
18926 <entry><type>bytea</type></entry>
18928 Return the contents of a file.
18933 <literal><function>pg_stat_file(<parameter>filename</> <type>text</>[, <parameter>missing_ok</> <type>boolean</type>])</function></literal>
18935 <entry><type>record</type></entry>
18937 Return information about a file.
18945 All of these functions take an optional <parameter>missing_ok</> parameter,
18946 which specifies the behavior when the file or directory does not exist.
18947 If <literal>true</literal>, the function returns NULL (except
18948 <function>pg_ls_dir</>, which returns an empty result set). If
18949 <literal>false</>, an error is raised. The default is <literal>false</>.
18953 <primary>pg_ls_dir</primary>
18956 <function>pg_ls_dir</> returns the names of all files (and directories
18957 and other special files) in the specified directory. The <parameter>
18958 include_dot_dirs</> indicates whether <quote>.</> and <quote>..</> are
18959 included in the result set. The default is to exclude them
18960 (<literal>false</>), but including them can be useful when
18961 <parameter>missing_ok</> is <literal>true</literal>, to distinguish an
18962 empty directory from an non-existent directory.
18966 <primary>pg_read_file</primary>
18969 <function>pg_read_file</> returns part of a text file, starting
18970 at the given <parameter>offset</>, returning at most <parameter>length</>
18971 bytes (less if the end of file is reached first). If <parameter>offset</>
18972 is negative, it is relative to the end of the file.
18973 If <parameter>offset</> and <parameter>length</> are omitted, the entire
18974 file is returned. The bytes read from the file are interpreted as a string
18975 in the server encoding; an error is thrown if they are not valid in that
18980 <primary>pg_read_binary_file</primary>
18983 <function>pg_read_binary_file</> is similar to
18984 <function>pg_read_file</>, except that the result is a <type>bytea</type> value;
18985 accordingly, no encoding checks are performed.
18986 In combination with the <function>convert_from</> function, this function
18987 can be used to read a file in a specified encoding:
18989 SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');
18994 <primary>pg_stat_file</primary>
18997 <function>pg_stat_file</> returns a record containing the file
18998 size, last accessed time stamp, last modified time stamp,
18999 last file status change time stamp (Unix platforms only),
19000 file creation time stamp (Windows only), and a <type>boolean</type>
19001 indicating if it is a directory. Typical usages include:
19003 SELECT * FROM pg_stat_file('filename');
19004 SELECT (pg_stat_file('filename')).modification;
19010 <sect2 id="functions-advisory-locks">
19011 <title>Advisory Lock Functions</title>
19014 The functions shown in <xref linkend="functions-advisory-locks-table">
19015 manage advisory locks. For details about proper use of these functions,
19016 see <xref linkend="advisory-locks">.
19019 <table id="functions-advisory-locks-table">
19020 <title>Advisory Lock Functions</title>
19023 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
19030 <literal><function>pg_advisory_lock(<parameter>key</> <type>bigint</>)</function></literal>
19032 <entry><type>void</type></entry>
19033 <entry>Obtain exclusive session level advisory lock</entry>
19037 <literal><function>pg_advisory_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19039 <entry><type>void</type></entry>
19040 <entry>Obtain exclusive session level advisory lock</entry>
19044 <literal><function>pg_advisory_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19046 <entry><type>void</type></entry>
19047 <entry>Obtain shared session level advisory lock</entry>
19051 <literal><function>pg_advisory_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19053 <entry><type>void</type></entry>
19054 <entry>Obtain shared session level advisory lock</entry>
19058 <literal><function>pg_advisory_unlock(<parameter>key</> <type>bigint</>)</function></literal>
19060 <entry><type>boolean</type></entry>
19061 <entry>Release an exclusive session level advisory lock</entry>
19065 <literal><function>pg_advisory_unlock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19067 <entry><type>boolean</type></entry>
19068 <entry>Release an exclusive session level advisory lock</entry>
19072 <literal><function>pg_advisory_unlock_all()</function></literal>
19074 <entry><type>void</type></entry>
19075 <entry>Release all session level advisory locks held by the current session</entry>
19079 <literal><function>pg_advisory_unlock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19081 <entry><type>boolean</type></entry>
19082 <entry>Release a shared session level advisory lock</entry>
19086 <literal><function>pg_advisory_unlock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19088 <entry><type>boolean</type></entry>
19089 <entry>Release a shared session level advisory lock</entry>
19093 <literal><function>pg_advisory_xact_lock(<parameter>key</> <type>bigint</>)</function></literal>
19095 <entry><type>void</type></entry>
19096 <entry>Obtain exclusive transaction level advisory lock</entry>
19100 <literal><function>pg_advisory_xact_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19102 <entry><type>void</type></entry>
19103 <entry>Obtain exclusive transaction level advisory lock</entry>
19107 <literal><function>pg_advisory_xact_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19109 <entry><type>void</type></entry>
19110 <entry>Obtain shared transaction level advisory lock</entry>
19114 <literal><function>pg_advisory_xact_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19116 <entry><type>void</type></entry>
19117 <entry>Obtain shared transaction level advisory lock</entry>
19121 <literal><function>pg_try_advisory_lock(<parameter>key</> <type>bigint</>)</function></literal>
19123 <entry><type>boolean</type></entry>
19124 <entry>Obtain exclusive session level advisory lock if available</entry>
19128 <literal><function>pg_try_advisory_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19130 <entry><type>boolean</type></entry>
19131 <entry>Obtain exclusive session level advisory lock if available</entry>
19135 <literal><function>pg_try_advisory_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19137 <entry><type>boolean</type></entry>
19138 <entry>Obtain shared session level advisory lock if available</entry>
19142 <literal><function>pg_try_advisory_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19144 <entry><type>boolean</type></entry>
19145 <entry>Obtain shared session level advisory lock if available</entry>
19149 <literal><function>pg_try_advisory_xact_lock(<parameter>key</> <type>bigint</>)</function></literal>
19151 <entry><type>boolean</type></entry>
19152 <entry>Obtain exclusive transaction level advisory lock if available</entry>
19156 <literal><function>pg_try_advisory_xact_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19158 <entry><type>boolean</type></entry>
19159 <entry>Obtain exclusive transaction level advisory lock if available</entry>
19163 <literal><function>pg_try_advisory_xact_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19165 <entry><type>boolean</type></entry>
19166 <entry>Obtain shared transaction level advisory lock if available</entry>
19170 <literal><function>pg_try_advisory_xact_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19172 <entry><type>boolean</type></entry>
19173 <entry>Obtain shared transaction level advisory lock if available</entry>
19180 <primary>pg_advisory_lock</primary>
19183 <function>pg_advisory_lock</> locks an application-defined resource,
19184 which can be identified either by a single 64-bit key value or two
19185 32-bit key values (note that these two key spaces do not overlap).
19186 If another session already holds a lock on the same resource identifier,
19187 this function will wait until the resource becomes available. The lock
19188 is exclusive. Multiple lock requests stack, so that if the same resource
19189 is locked three times it must then be unlocked three times to be
19190 released for other sessions' use.
19194 <primary>pg_advisory_lock_shared</primary>
19197 <function>pg_advisory_lock_shared</> works the same as
19198 <function>pg_advisory_lock</>,
19199 except the lock can be shared with other sessions requesting shared locks.
19200 Only would-be exclusive lockers are locked out.
19204 <primary>pg_try_advisory_lock</primary>
19207 <function>pg_try_advisory_lock</> is similar to
19208 <function>pg_advisory_lock</>, except the function will not wait for the
19209 lock to become available. It will either obtain the lock immediately and
19210 return <literal>true</>, or return <literal>false</> if the lock cannot be
19211 acquired immediately.
19215 <primary>pg_try_advisory_lock_shared</primary>
19218 <function>pg_try_advisory_lock_shared</> works the same as
19219 <function>pg_try_advisory_lock</>, except it attempts to acquire
19220 a shared rather than an exclusive lock.
19224 <primary>pg_advisory_unlock</primary>
19227 <function>pg_advisory_unlock</> will release a previously-acquired
19228 exclusive session level advisory lock. It
19229 returns <literal>true</> if the lock is successfully released.
19230 If the lock was not held, it will return <literal>false</>,
19231 and in addition, an SQL warning will be reported by the server.
19235 <primary>pg_advisory_unlock_shared</primary>
19238 <function>pg_advisory_unlock_shared</> works the same as
19239 <function>pg_advisory_unlock</>,
19240 except it releases a shared session level advisory lock.
19244 <primary>pg_advisory_unlock_all</primary>
19247 <function>pg_advisory_unlock_all</> will release all session level advisory
19248 locks held by the current session. (This function is implicitly invoked
19249 at session end, even if the client disconnects ungracefully.)
19253 <primary>pg_advisory_xact_lock</primary>
19256 <function>pg_advisory_xact_lock</> works the same as
19257 <function>pg_advisory_lock</>, except the lock is automatically released
19258 at the end of the current transaction and cannot be released explicitly.
19262 <primary>pg_advisory_xact_lock_shared</primary>
19265 <function>pg_advisory_xact_lock_shared</> works the same as
19266 <function>pg_advisory_lock_shared</>, except the lock is automatically released
19267 at the end of the current transaction and cannot be released explicitly.
19271 <primary>pg_try_advisory_xact_lock</primary>
19274 <function>pg_try_advisory_xact_lock</> works the same as
19275 <function>pg_try_advisory_lock</>, except the lock, if acquired,
19276 is automatically released at the end of the current transaction and
19277 cannot be released explicitly.
19281 <primary>pg_try_advisory_xact_lock_shared</primary>
19284 <function>pg_try_advisory_xact_lock_shared</> works the same as
19285 <function>pg_try_advisory_lock_shared</>, except the lock, if acquired,
19286 is automatically released at the end of the current transaction and
19287 cannot be released explicitly.
19294 <sect1 id="functions-trigger">
19295 <title>Trigger Functions</title>
19298 <primary>suppress_redundant_updates_trigger</primary>
19302 Currently <productname>PostgreSQL</> provides one built in trigger
19303 function, <function>suppress_redundant_updates_trigger</>,
19304 which will prevent any update
19305 that does not actually change the data in the row from taking place, in
19306 contrast to the normal behavior which always performs the update
19307 regardless of whether or not the data has changed. (This normal behavior
19308 makes updates run faster, since no checking is required, and is also
19309 useful in certain cases.)
19313 Ideally, you should normally avoid running updates that don't actually
19314 change the data in the record. Redundant updates can cost considerable
19315 unnecessary time, especially if there are lots of indexes to alter,
19316 and space in dead rows that will eventually have to be vacuumed.
19317 However, detecting such situations in client code is not
19318 always easy, or even possible, and writing expressions to detect
19319 them can be error-prone. An alternative is to use
19320 <function>suppress_redundant_updates_trigger</>, which will skip
19321 updates that don't change the data. You should use this with care,
19322 however. The trigger takes a small but non-trivial time for each record,
19323 so if most of the records affected by an update are actually changed,
19324 use of this trigger will actually make the update run slower.
19328 The <function>suppress_redundant_updates_trigger</> function can be
19329 added to a table like this:
19331 CREATE TRIGGER z_min_update
19332 BEFORE UPDATE ON tablename
19333 FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger();
19335 In most cases, you would want to fire this trigger last for each row.
19336 Bearing in mind that triggers fire in name order, you would then
19337 choose a trigger name that comes after the name of any other trigger
19338 you might have on the table.
19341 For more information about creating triggers, see
19342 <xref linkend="SQL-CREATETRIGGER">.
19346 <sect1 id="functions-event-triggers">
19347 <title>Event Trigger Functions</title>
19350 <productname>PostgreSQL</> provides these helper functions
19351 to retrieve information from event triggers.
19355 For more information about event triggers,
19356 see <xref linkend="event-triggers">.
19359 <sect2 id="pg-event-trigger-ddl-command-end-functions">
19360 <title>Capturing Changes at Command End</title>
19363 <primary>pg_event_trigger_ddl_commands</primary>
19367 <function>pg_event_trigger_ddl_commands</> returns a list of
19368 <acronym>DDL</acronym> commands executed by each user action,
19369 when invoked in a function attached to a
19370 <literal>ddl_command_end</> event trigger. If called in any other
19371 context, an error is raised.
19372 <function>pg_event_trigger_ddl_commands</> returns one row for each
19373 base command executed; some commands that are a single SQL sentence
19374 may return more than one row. This function returns the following
19381 <entry>Name</entry>
19382 <entry>Type</entry>
19383 <entry>Description</entry>
19389 <entry><literal>classid</literal></entry>
19390 <entry><type>Oid</type></entry>
19391 <entry>OID of catalog the object belongs in</entry>
19394 <entry><literal>objid</literal></entry>
19395 <entry><type>Oid</type></entry>
19396 <entry>OID of the object in the catalog</entry>
19399 <entry><literal>objsubid</literal></entry>
19400 <entry><type>integer</type></entry>
19401 <entry>Object sub-id (e.g. attribute number for columns)</entry>
19404 <entry><literal>command_tag</literal></entry>
19405 <entry><type>text</type></entry>
19406 <entry>command tag</entry>
19409 <entry><literal>object_type</literal></entry>
19410 <entry><type>text</type></entry>
19411 <entry>Type of the object</entry>
19414 <entry><literal>schema_name</literal></entry>
19415 <entry><type>text</type></entry>
19417 Name of the schema the object belongs in, if any; otherwise <literal>NULL</>.
19418 No quoting is applied.
19422 <entry><literal>object_identity</literal></entry>
19423 <entry><type>text</type></entry>
19425 Text rendering of the object identity, schema-qualified. Each and every
19426 identifier present in the identity is quoted if necessary.
19430 <entry><literal>in_extension</literal></entry>
19431 <entry><type>bool</type></entry>
19432 <entry>whether the command is part of an extension script</entry>
19435 <entry><literal>command</literal></entry>
19436 <entry><type>pg_ddl_command</type></entry>
19438 A complete representation of the command, in internal format.
19439 This cannot be output directly, but it can be passed to other
19440 functions to obtain different pieces of information about the
19450 <sect2 id="pg-event-trigger-sql-drop-functions">
19451 <title>Processing Objects Dropped by a DDL Command</title>
19454 <primary>pg_event_trigger_dropped_objects</primary>
19458 <function>pg_event_trigger_dropped_objects</> returns a list of all objects
19459 dropped by the command in whose <literal>sql_drop</> event it is called.
19460 If called in any other context,
19461 <function>pg_event_trigger_dropped_objects</> raises an error.
19462 <function>pg_event_trigger_dropped_objects</> returns the following columns:
19468 <entry>Name</entry>
19469 <entry>Type</entry>
19470 <entry>Description</entry>
19476 <entry><literal>classid</literal></entry>
19477 <entry><type>Oid</type></entry>
19478 <entry>OID of catalog the object belonged in</entry>
19481 <entry><literal>objid</literal></entry>
19482 <entry><type>Oid</type></entry>
19483 <entry>OID the object had within the catalog</entry>
19486 <entry><literal>objsubid</literal></entry>
19487 <entry><type>int32</type></entry>
19488 <entry>Object sub-id (e.g. attribute number for columns)</entry>
19491 <entry><literal>original</literal></entry>
19492 <entry><type>bool</type></entry>
19493 <entry>Flag used to identify the root object(s) of the deletion</entry>
19496 <entry><literal>normal</literal></entry>
19497 <entry><type>bool</type></entry>
19499 Flag indicating that there's a normal dependency relationship
19500 in the dependency graph leading to this object
19504 <entry><literal>is_temporary</literal></entry>
19505 <entry><type>bool</type></entry>
19507 Flag indicating that the object was a temporary object.
19511 <entry><literal>object_type</literal></entry>
19512 <entry><type>text</type></entry>
19513 <entry>Type of the object</entry>
19516 <entry><literal>schema_name</literal></entry>
19517 <entry><type>text</type></entry>
19519 Name of the schema the object belonged in, if any; otherwise <literal>NULL</>.
19520 No quoting is applied.
19524 <entry><literal>object_name</literal></entry>
19525 <entry><type>text</type></entry>
19527 Name of the object, if the combination of schema and name can be
19528 used as a unique identifier for the object; otherwise <literal>NULL</>.
19529 No quoting is applied, and name is never schema-qualified.
19533 <entry><literal>object_identity</literal></entry>
19534 <entry><type>text</type></entry>
19536 Text rendering of the object identity, schema-qualified. Each and every
19537 identifier present in the identity is quoted if necessary.
19541 <entry><literal>address_names</literal></entry>
19542 <entry><type>text[]</type></entry>
19544 An array that, together with <literal>object_type</literal> and
19545 <literal>address_args</literal>,
19546 can be used by the <function>pg_get_object_address()</function> to
19547 recreate the object address in a remote server containing an
19548 identically named object of the same kind.
19552 <entry><literal>address_args</literal></entry>
19553 <entry><type>text[]</type></entry>
19555 Complement for <literal>address_names</literal> above.
19564 The <function>pg_event_trigger_dropped_objects</> function can be used
19565 in an event trigger like this:
19567 CREATE FUNCTION test_event_trigger_for_drops()
19568 RETURNS event_trigger LANGUAGE plpgsql AS $$
19572 FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects()
19574 RAISE NOTICE '% dropped object: % %.% %',
19579 obj.object_identity;
19583 CREATE EVENT TRIGGER test_event_trigger_for_drops
19585 EXECUTE PROCEDURE test_event_trigger_for_drops();
19590 <sect2 id="pg-event-trigger-table-rewrite-functions">
19591 <title>Handling a Table Rewrite Event</title>
19594 The functions shown in
19595 <xref linkend="functions-event-trigger-table-rewrite">
19596 provide information about a table for which a
19597 <literal>table_rewrite</> event has just been called.
19598 If called in any other context, an error is raised.
19601 <table id="functions-event-trigger-table-rewrite">
19602 <title>Table Rewrite information</title>
19605 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
19611 <indexterm><primary>pg_event_trigger_table_rewrite_oid</primary></indexterm>
19612 <literal><function>pg_event_trigger_table_rewrite_oid()</function></literal>
19614 <entry><type>Oid</type></entry>
19615 <entry>The OID of the table about to be rewritten.</entry>
19620 <indexterm><primary>pg_event_trigger_table_rewrite_reason</primary></indexterm>
19621 <literal><function>pg_event_trigger_table_rewrite_reason()</function></literal>
19623 <entry><type>int</type></entry>
19625 The reason code(s) explaining the reason for rewriting. The exact
19626 meaning of the codes is release dependent.
19634 The <function>pg_event_trigger_table_rewrite_oid</> function can be used
19635 in an event trigger like this:
19637 CREATE FUNCTION test_event_trigger_table_rewrite_oid()
19638 RETURNS event_trigger
19639 LANGUAGE plpgsql AS
19642 RAISE NOTICE 'rewriting table % for reason %',
19643 pg_event_trigger_table_rewrite_oid()::regclass,
19644 pg_event_trigger_table_rewrite_reason();
19648 CREATE EVENT TRIGGER test_table_rewrite_oid
19650 EXECUTE PROCEDURE test_event_trigger_table_rewrite_oid();