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>).
260 There are also some comparison predicates, as shown in <xref
261 linkend="functions-comparison-pred-table">. These behave much like
262 operators, but have special syntax mandated by the SQL standard.
265 <table id="functions-comparison-pred-table">
266 <title>Comparison Predicates</title>
270 <entry>Predicate</entry>
271 <entry>Description</entry>
277 <entry> <replaceable>a</> <literal>BETWEEN</> <replaceable>x</> <literal>AND</> <replaceable>y</> </entry>
278 <entry>between</entry>
282 <entry> <replaceable>a</> <literal>NOT BETWEEN</> <replaceable>x</> <literal>AND</> <replaceable>y</> </entry>
283 <entry>not between</entry>
287 <entry> <replaceable>a</> <literal>BETWEEN SYMMETRIC</> <replaceable>x</> <literal>AND</> <replaceable>y</> </entry>
288 <entry>between, after sorting the comparison values</entry>
292 <entry> <replaceable>a</> <literal>NOT BETWEEN SYMMETRIC</> <replaceable>x</> <literal>AND</> <replaceable>y</> </entry>
293 <entry>not between, after sorting the comparison values</entry>
297 <entry> <replaceable>a</> <literal>IS DISTINCT FROM</> <replaceable>b</> </entry>
298 <entry>not equal, treating null like an ordinary value</entry>
302 <entry><replaceable>a</> <literal>IS NOT DISTINCT FROM</> <replaceable>b</></entry>
303 <entry>equal, treating null like an ordinary value</entry>
307 <entry> <replaceable>expression</> <literal>IS NULL</> </entry>
308 <entry>is null</entry>
312 <entry> <replaceable>expression</> <literal>IS NOT NULL</> </entry>
313 <entry>is not null</entry>
317 <entry> <replaceable>expression</> <literal>ISNULL</> </entry>
318 <entry>is null (nonstandard syntax)</entry>
322 <entry> <replaceable>expression</> <literal>NOTNULL</> </entry>
323 <entry>is not null (nonstandard syntax)</entry>
327 <entry> <replaceable>boolean_expression</> <literal>IS TRUE</> </entry>
328 <entry>is true</entry>
332 <entry> <replaceable>boolean_expression</> <literal>IS NOT TRUE</> </entry>
333 <entry>is false or unknown</entry>
337 <entry> <replaceable>boolean_expression</> <literal>IS FALSE</> </entry>
338 <entry>is false</entry>
342 <entry> <replaceable>boolean_expression</> <literal>IS NOT FALSE</> </entry>
343 <entry>is true or unknown</entry>
347 <entry> <replaceable>boolean_expression</> <literal>IS UNKNOWN</> </entry>
348 <entry>is unknown</entry>
352 <entry> <replaceable>boolean_expression</> <literal>IS NOT UNKNOWN</> </entry>
353 <entry>is true or false</entry>
361 <primary>BETWEEN</primary>
363 The <token>BETWEEN</token> predicate simplifies range tests:
365 <replaceable>a</replaceable> BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
369 <replaceable>a</replaceable> >= <replaceable>x</replaceable> AND <replaceable>a</replaceable> <= <replaceable>y</replaceable>
371 Notice that <token>BETWEEN</token> treats the endpoint values as included
373 <literal>NOT BETWEEN</literal> does the opposite comparison:
375 <replaceable>a</replaceable> NOT BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
379 <replaceable>a</replaceable> < <replaceable>x</replaceable> OR <replaceable>a</replaceable> > <replaceable>y</replaceable>
382 <primary>BETWEEN SYMMETRIC</primary>
384 <literal>BETWEEN SYMMETRIC</> is like <literal>BETWEEN</>
385 except there is no requirement that the argument to the left of
386 <literal>AND</> be less than or equal to the argument on the right.
387 If it is not, those two arguments are automatically swapped, so that
388 a nonempty range is always implied.
393 <primary>IS DISTINCT FROM</primary>
396 <primary>IS NOT DISTINCT FROM</primary>
398 Ordinary comparison operators yield null (signifying <quote>unknown</>),
399 not true or false, when either input is null. For example,
400 <literal>7 = NULL</> yields null, as does <literal>7 <> NULL</>. When
401 this behavior is not suitable, use the
402 <literal>IS <optional> NOT </> DISTINCT FROM</literal> predicates:
404 <replaceable>a</replaceable> IS DISTINCT FROM <replaceable>b</replaceable>
405 <replaceable>a</replaceable> IS NOT DISTINCT FROM <replaceable>b</replaceable>
407 For non-null inputs, <literal>IS DISTINCT FROM</literal> is
408 the same as the <literal><></> operator. However, if both
409 inputs are null it returns false, and if only one input is
410 null it returns true. Similarly, <literal>IS NOT DISTINCT
411 FROM</literal> is identical to <literal>=</literal> for non-null
412 inputs, but it returns true when both inputs are null, and false when only
413 one input is null. Thus, these predicates effectively act as though null
414 were a normal data value, rather than <quote>unknown</>.
419 <primary>IS NULL</primary>
422 <primary>IS NOT NULL</primary>
425 <primary>ISNULL</primary>
428 <primary>NOTNULL</primary>
430 To check whether a value is or is not null, use the predicates:
432 <replaceable>expression</replaceable> IS NULL
433 <replaceable>expression</replaceable> IS NOT NULL
435 or the equivalent, but nonstandard, predicates:
437 <replaceable>expression</replaceable> ISNULL
438 <replaceable>expression</replaceable> NOTNULL
440 <indexterm><primary>null value</primary><secondary>comparing</secondary></indexterm>
444 Do <emphasis>not</emphasis> write
445 <literal><replaceable>expression</replaceable> = NULL</literal>
446 because <literal>NULL</> is not <quote>equal to</quote>
447 <literal>NULL</>. (The null value represents an unknown value,
448 and it is not known whether two unknown values are equal.)
453 Some applications might expect that
454 <literal><replaceable>expression</replaceable> = NULL</literal>
455 returns true if <replaceable>expression</replaceable> evaluates to
456 the null value. It is highly recommended that these applications
457 be modified to comply with the SQL standard. However, if that
458 cannot be done the <xref linkend="guc-transform-null-equals">
459 configuration variable is available. If it is enabled,
460 <productname>PostgreSQL</productname> will convert <literal>x =
461 NULL</literal> clauses to <literal>x IS NULL</literal>.
466 If the <replaceable>expression</replaceable> is row-valued, then
467 <literal>IS NULL</> is true when the row expression itself is null
468 or when all the row's fields are null, while
469 <literal>IS NOT NULL</> is true when the row expression itself is non-null
470 and all the row's fields are non-null. Because of this behavior,
471 <literal>IS NULL</> and <literal>IS NOT NULL</> do not always return
472 inverse results for row-valued expressions; in particular, a row-valued
473 expression that contains both null and non-null fields will return false
474 for both tests. In some cases, it may be preferable to
475 write <replaceable>row</replaceable> <literal>IS DISTINCT FROM NULL</>
476 or <replaceable>row</replaceable> <literal>IS NOT DISTINCT FROM NULL</>,
477 which will simply check whether the overall row value is null without any
478 additional tests on the row fields.
483 <primary>IS TRUE</primary>
486 <primary>IS NOT TRUE</primary>
489 <primary>IS FALSE</primary>
492 <primary>IS NOT FALSE</primary>
495 <primary>IS UNKNOWN</primary>
498 <primary>IS NOT UNKNOWN</primary>
500 Boolean values can also be tested using the predicates
502 <replaceable>boolean_expression</replaceable> IS TRUE
503 <replaceable>boolean_expression</replaceable> IS NOT TRUE
504 <replaceable>boolean_expression</replaceable> IS FALSE
505 <replaceable>boolean_expression</replaceable> IS NOT FALSE
506 <replaceable>boolean_expression</replaceable> IS UNKNOWN
507 <replaceable>boolean_expression</replaceable> IS NOT UNKNOWN
509 These will always return true or false, never a null value, even when the
511 A null input is treated as the logical value <quote>unknown</>.
512 Notice that <literal>IS UNKNOWN</> and <literal>IS NOT UNKNOWN</> are
513 effectively the same as <literal>IS NULL</literal> and
514 <literal>IS NOT NULL</literal>, respectively, except that the input
515 expression must be of Boolean type.
518 <!-- IS OF does not conform to the ISO SQL behavior, so it is undocumented here
521 <primary>IS OF</primary>
524 <primary>IS NOT OF</primary>
526 It is possible to check the data type of an expression using the
529 <replaceable>expression</replaceable> IS OF (typename, ...)
530 <replaceable>expression</replaceable> IS NOT OF (typename, ...)
532 They return a boolean value based on whether the expression's data
533 type is one of the listed data types.
538 Some comparison-related functions are also available, as shown in <xref
539 linkend="functions-comparison-func-table">.
542 <table id="functions-comparison-func-table">
543 <title>Comparison Functions</title>
547 <entry>Function</entry>
548 <entry>Description</entry>
549 <entry>Example</entry>
550 <entry>Example Result</entry>
557 <primary>num_nonnulls</primary>
559 <literal>num_nonnulls(VARIADIC "any")</literal>
561 <entry>returns the number of non-null arguments</entry>
562 <entry><literal>num_nonnulls(1, NULL, 2)</literal></entry>
563 <entry><literal>2</literal></entry>
568 <primary>num_nulls</primary>
570 <literal>num_nulls(VARIADIC "any")</literal>
572 <entry>returns the number of null arguments</entry>
573 <entry><literal>num_nulls(1, NULL, 2)</literal></entry>
574 <entry><literal>1</literal></entry>
582 <sect1 id="functions-math">
583 <title>Mathematical Functions and Operators</title>
586 Mathematical operators are provided for many
587 <productname>PostgreSQL</productname> types. For types without
588 standard mathematical conventions
589 (e.g., date/time types) we
590 describe the actual behavior in subsequent sections.
594 <xref linkend="functions-math-op-table"> shows the available mathematical operators.
597 <table id="functions-math-op-table">
598 <title>Mathematical Operators</title>
603 <entry>Operator</entry>
604 <entry>Description</entry>
605 <entry>Example</entry>
606 <entry>Result</entry>
612 <entry> <literal>+</literal> </entry>
613 <entry>addition</entry>
614 <entry><literal>2 + 3</literal></entry>
615 <entry><literal>5</literal></entry>
619 <entry> <literal>-</literal> </entry>
620 <entry>subtraction</entry>
621 <entry><literal>2 - 3</literal></entry>
622 <entry><literal>-1</literal></entry>
626 <entry> <literal>*</literal> </entry>
627 <entry>multiplication</entry>
628 <entry><literal>2 * 3</literal></entry>
629 <entry><literal>6</literal></entry>
633 <entry> <literal>/</literal> </entry>
634 <entry>division (integer division truncates the result)</entry>
635 <entry><literal>4 / 2</literal></entry>
636 <entry><literal>2</literal></entry>
640 <entry> <literal>%</literal> </entry>
641 <entry>modulo (remainder)</entry>
642 <entry><literal>5 % 4</literal></entry>
643 <entry><literal>1</literal></entry>
647 <entry> <literal>^</literal> </entry>
648 <entry>exponentiation (associates left to right)</entry>
649 <entry><literal>2.0 ^ 3.0</literal></entry>
650 <entry><literal>8</literal></entry>
654 <entry> <literal>|/</literal> </entry>
655 <entry>square root</entry>
656 <entry><literal>|/ 25.0</literal></entry>
657 <entry><literal>5</literal></entry>
661 <entry> <literal>||/</literal> </entry>
662 <entry>cube root</entry>
663 <entry><literal>||/ 27.0</literal></entry>
664 <entry><literal>3</literal></entry>
668 <entry> <literal>!</literal> </entry>
669 <entry>factorial</entry>
670 <entry><literal>5 !</literal></entry>
671 <entry><literal>120</literal></entry>
675 <entry> <literal>!!</literal> </entry>
676 <entry>factorial (prefix operator)</entry>
677 <entry><literal>!! 5</literal></entry>
678 <entry><literal>120</literal></entry>
682 <entry> <literal>@</literal> </entry>
683 <entry>absolute value</entry>
684 <entry><literal>@ -5.0</literal></entry>
685 <entry><literal>5</literal></entry>
689 <entry> <literal>&</literal> </entry>
690 <entry>bitwise AND</entry>
691 <entry><literal>91 & 15</literal></entry>
692 <entry><literal>11</literal></entry>
696 <entry> <literal>|</literal> </entry>
697 <entry>bitwise OR</entry>
698 <entry><literal>32 | 3</literal></entry>
699 <entry><literal>35</literal></entry>
703 <entry> <literal>#</literal> </entry>
704 <entry>bitwise XOR</entry>
705 <entry><literal>17 # 5</literal></entry>
706 <entry><literal>20</literal></entry>
710 <entry> <literal>~</literal> </entry>
711 <entry>bitwise NOT</entry>
712 <entry><literal>~1</literal></entry>
713 <entry><literal>-2</literal></entry>
717 <entry> <literal><<</literal> </entry>
718 <entry>bitwise shift left</entry>
719 <entry><literal>1 << 4</literal></entry>
720 <entry><literal>16</literal></entry>
724 <entry> <literal>>></literal> </entry>
725 <entry>bitwise shift right</entry>
726 <entry><literal>8 >> 2</literal></entry>
727 <entry><literal>2</literal></entry>
735 The bitwise operators work only on integral data types, whereas
736 the others are available for all numeric data types. The bitwise
737 operators are also available for the bit
738 string types <type>bit</type> and <type>bit varying</type>, as
739 shown in <xref linkend="functions-bit-string-op-table">.
743 <xref linkend="functions-math-func-table"> shows the available
744 mathematical functions. In the table, <literal>dp</literal>
745 indicates <type>double precision</type>. Many of these functions
746 are provided in multiple forms with different argument types.
747 Except where noted, any given form of a function returns the same
748 data type as its argument.
749 The functions working with <type>double precision</type> data are mostly
750 implemented on top of the host system's C library; accuracy and behavior in
751 boundary cases can therefore vary depending on the host system.
754 <table id="functions-math-func-table">
755 <title>Mathematical Functions</title>
759 <entry>Function</entry>
760 <entry>Return Type</entry>
761 <entry>Description</entry>
762 <entry>Example</entry>
763 <entry>Result</entry>
771 <primary>abs</primary>
773 <literal><function>abs(<replaceable>x</replaceable>)</function></literal>
775 <entry>(same as input)</entry>
776 <entry>absolute value</entry>
777 <entry><literal>abs(-17.4)</literal></entry>
778 <entry><literal>17.4</literal></entry>
784 <primary>cbrt</primary>
786 <literal><function>cbrt(<type>dp</type>)</function></literal>
788 <entry><type>dp</type></entry>
789 <entry>cube root</entry>
790 <entry><literal>cbrt(27.0)</literal></entry>
791 <entry><literal>3</literal></entry>
797 <primary>ceil</primary>
799 <literal><function>ceil(<type>dp</type> or <type>numeric</type>)</function></literal>
801 <entry>(same as input)</entry>
802 <entry>nearest integer greater than or equal to argument</entry>
803 <entry><literal>ceil(-42.8)</literal></entry>
804 <entry><literal>-42</literal></entry>
810 <primary>ceiling</primary>
812 <literal><function>ceiling(<type>dp</type> or <type>numeric</type>)</function></literal>
814 <entry>(same as input)</entry>
815 <entry>nearest integer greater than or equal to argument (same as <function>ceil</function>)</entry>
816 <entry><literal>ceiling(-95.3)</literal></entry>
817 <entry><literal>-95</literal></entry>
823 <primary>degrees</primary>
825 <literal><function>degrees(<type>dp</type>)</function></literal>
827 <entry><type>dp</type></entry>
828 <entry>radians to degrees</entry>
829 <entry><literal>degrees(0.5)</literal></entry>
830 <entry><literal>28.6478897565412</literal></entry>
836 <primary>div</primary>
838 <literal><function>div(<parameter>y</parameter> <type>numeric</>,
839 <parameter>x</parameter> <type>numeric</>)</function></literal>
841 <entry><type>numeric</></entry>
842 <entry>integer quotient of <parameter>y</parameter>/<parameter>x</parameter></entry>
843 <entry><literal>div(9,4)</literal></entry>
844 <entry><literal>2</literal></entry>
850 <primary>exp</primary>
852 <literal><function>exp(<type>dp</type> or <type>numeric</type>)</function></literal>
854 <entry>(same as input)</entry>
855 <entry>exponential</entry>
856 <entry><literal>exp(1.0)</literal></entry>
857 <entry><literal>2.71828182845905</literal></entry>
863 <primary>floor</primary>
865 <literal><function>floor(<type>dp</type> or <type>numeric</type>)</function></literal>
867 <entry>(same as input)</entry>
868 <entry>nearest integer less than or equal to argument</entry>
869 <entry><literal>floor(-42.8)</literal></entry>
870 <entry><literal>-43</literal></entry>
876 <primary>ln</primary>
878 <literal><function>ln(<type>dp</type> or <type>numeric</type>)</function></literal>
880 <entry>(same as input)</entry>
881 <entry>natural logarithm</entry>
882 <entry><literal>ln(2.0)</literal></entry>
883 <entry><literal>0.693147180559945</literal></entry>
889 <primary>log</primary>
891 <literal><function>log(<type>dp</type> or <type>numeric</type>)</function></literal>
893 <entry>(same as input)</entry>
894 <entry>base 10 logarithm</entry>
895 <entry><literal>log(100.0)</literal></entry>
896 <entry><literal>2</literal></entry>
900 <entry><literal><function>log(<parameter>b</parameter> <type>numeric</type>,
901 <parameter>x</parameter> <type>numeric</type>)</function></literal></entry>
902 <entry><type>numeric</type></entry>
903 <entry>logarithm to base <parameter>b</parameter></entry>
904 <entry><literal>log(2.0, 64.0)</literal></entry>
905 <entry><literal>6.0000000000</literal></entry>
911 <primary>mod</primary>
913 <literal><function>mod(<parameter>y</parameter>,
914 <parameter>x</parameter>)</function></literal>
916 <entry>(same as argument types)</entry>
917 <entry>remainder of <parameter>y</parameter>/<parameter>x</parameter></entry>
918 <entry><literal>mod(9,4)</literal></entry>
919 <entry><literal>1</literal></entry>
925 <primary>pi</primary>
927 <literal><function>pi()</function></literal>
929 <entry><type>dp</type></entry>
930 <entry><quote>π</quote> constant</entry>
931 <entry><literal>pi()</literal></entry>
932 <entry><literal>3.14159265358979</literal></entry>
938 <primary>power</primary>
940 <literal><function>power(<parameter>a</parameter> <type>dp</type>,
941 <parameter>b</parameter> <type>dp</type>)</function></literal>
943 <entry><type>dp</type></entry>
944 <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
945 <entry><literal>power(9.0, 3.0)</literal></entry>
946 <entry><literal>729</literal></entry>
950 <entry><literal><function>power(<parameter>a</parameter> <type>numeric</type>,
951 <parameter>b</parameter> <type>numeric</type>)</function></literal></entry>
952 <entry><type>numeric</type></entry>
953 <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
954 <entry><literal>power(9.0, 3.0)</literal></entry>
955 <entry><literal>729</literal></entry>
961 <primary>radians</primary>
963 <literal><function>radians(<type>dp</type>)</function></literal>
965 <entry><type>dp</type></entry>
966 <entry>degrees to radians</entry>
967 <entry><literal>radians(45.0)</literal></entry>
968 <entry><literal>0.785398163397448</literal></entry>
974 <primary>round</primary>
976 <literal><function>round(<type>dp</type> or <type>numeric</type>)</function></literal>
978 <entry>(same as input)</entry>
979 <entry>round to nearest integer</entry>
980 <entry><literal>round(42.4)</literal></entry>
981 <entry><literal>42</literal></entry>
985 <entry><literal><function>round(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</function></literal></entry>
986 <entry><type>numeric</type></entry>
987 <entry>round to <parameter>s</parameter> decimal places</entry>
988 <entry><literal>round(42.4382, 2)</literal></entry>
989 <entry><literal>42.44</literal></entry>
995 <primary>scale</primary>
997 <literal><function>scale(<type>numeric</type>)</function></literal>
999 <entry><type>numeric</type></entry>
1000 <entry>scale of the argument (the number of decimal digits in the fractional part)</entry>
1001 <entry><literal>scale(8.41)</literal></entry>
1002 <entry><literal>2</literal></entry>
1008 <primary>sign</primary>
1010 <literal><function>sign(<type>dp</type> or <type>numeric</type>)</function></literal>
1012 <entry>(same as input)</entry>
1013 <entry>sign of the argument (-1, 0, +1)</entry>
1014 <entry><literal>sign(-8.4)</literal></entry>
1015 <entry><literal>-1</literal></entry>
1021 <primary>sqrt</primary>
1023 <literal><function>sqrt(<type>dp</type> or <type>numeric</type>)</function></literal>
1025 <entry>(same as input)</entry>
1026 <entry>square root</entry>
1027 <entry><literal>sqrt(2.0)</literal></entry>
1028 <entry><literal>1.4142135623731</literal></entry>
1034 <primary>trunc</primary>
1036 <literal><function>trunc(<type>dp</type> or <type>numeric</type>)</function></literal>
1038 <entry>(same as input)</entry>
1039 <entry>truncate toward zero</entry>
1040 <entry><literal>trunc(42.8)</literal></entry>
1041 <entry><literal>42</literal></entry>
1045 <entry><literal><function>trunc(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</function></literal></entry>
1046 <entry><type>numeric</type></entry>
1047 <entry>truncate to <parameter>s</parameter> decimal places</entry>
1048 <entry><literal>trunc(42.4382, 2)</literal></entry>
1049 <entry><literal>42.43</literal></entry>
1055 <primary>width_bucket</primary>
1057 <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>
1058 <entry><type>int</type></entry>
1059 <entry>return the bucket number to which <parameter>operand</> would
1060 be assigned in a histogram having <parameter>count</> equal-width
1061 buckets spanning the range <parameter>b1</> to <parameter>b2</>;
1062 returns <literal>0</> or <literal><parameter>count</>+1</literal> for
1063 an input outside the range</entry>
1064 <entry><literal>width_bucket(5.35, 0.024, 10.06, 5)</literal></entry>
1065 <entry><literal>3</literal></entry>
1069 <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>
1070 <entry><type>int</type></entry>
1071 <entry>return the bucket number to which <parameter>operand</> would
1072 be assigned in a histogram having <parameter>count</> equal-width
1073 buckets spanning the range <parameter>b1</> to <parameter>b2</>;
1074 returns <literal>0</> or <literal><parameter>count</>+1</literal> for
1075 an input outside the range</entry>
1076 <entry><literal>width_bucket(5.35, 0.024, 10.06, 5)</literal></entry>
1077 <entry><literal>3</literal></entry>
1081 <entry><literal><function>width_bucket(<parameter>operand</parameter> <type>anyelement</type>, <parameter>thresholds</parameter> <type>anyarray</type>)</function></literal></entry>
1082 <entry><type>int</type></entry>
1083 <entry>return the bucket number to which <parameter>operand</> would
1084 be assigned given an array listing the lower bounds of the buckets;
1085 returns <literal>0</> for an input less than the first lower bound;
1086 the <parameter>thresholds</> array <emphasis>must be sorted</>,
1087 smallest first, or unexpected results will be obtained</entry>
1088 <entry><literal>width_bucket(now(), array['yesterday', 'today', 'tomorrow']::timestamptz[])</literal></entry>
1089 <entry><literal>2</literal></entry>
1096 <xref linkend="functions-math-random-table"> shows functions for
1097 generating random numbers.
1100 <table id="functions-math-random-table">
1101 <title>Random Functions</title>
1106 <entry>Function</entry>
1107 <entry>Return Type</entry>
1108 <entry>Description</entry>
1115 <primary>random</primary>
1117 <literal><function>random()</function></literal>
1119 <entry><type>dp</type></entry>
1120 <entry>random value in the range 0.0 <= x < 1.0</entry>
1126 <primary>setseed</primary>
1128 <literal><function>setseed(<type>dp</type>)</function></literal>
1130 <entry><type>void</type></entry>
1131 <entry>set seed for subsequent <literal>random()</literal> calls (value between -1.0 and
1132 1.0, inclusive)</entry>
1139 The characteristics of the values returned by
1140 <literal><function>random()</function></literal> depend
1141 on the system implementation. It is not suitable for cryptographic
1142 applications; see <xref linkend="pgcrypto"> module for an alternative.
1146 Finally, <xref linkend="functions-math-trig-table"> shows the
1147 available trigonometric functions. All trigonometric functions
1148 take arguments and return values of type <type>double
1149 precision</type>. Each of the trigonometric functions comes in
1150 two variants, one that measures angles in radians and one that
1151 measures angles in degrees.
1154 <table id="functions-math-trig-table">
1155 <title>Trigonometric Functions</title>
1160 <entry>Function (radians)</entry>
1161 <entry>Function (degrees)</entry>
1162 <entry>Description</entry>
1170 <primary>acos</primary>
1171 </indexterm><literal><function>acos(<replaceable>x</replaceable>)</function></literal>
1175 <primary>acosd</primary>
1176 </indexterm><literal><function>acosd(<replaceable>x</replaceable>)</function></literal>
1178 <entry>inverse cosine</entry>
1184 <primary>asin</primary>
1186 <literal><function>asin(<replaceable>x</replaceable>)</function></literal>
1190 <primary>asind</primary>
1192 <literal><function>asind(<replaceable>x</replaceable>)</function></literal>
1194 <entry>inverse sine</entry>
1200 <primary>atan</primary>
1202 <literal><function>atan(<replaceable>x</replaceable>)</function></literal>
1206 <primary>atand</primary>
1208 <literal><function>atand(<replaceable>x</replaceable>)</function></literal>
1210 <entry>inverse tangent</entry>
1216 <primary>atan2</primary>
1218 <literal><function>atan2(<replaceable>y</replaceable>,
1219 <replaceable>x</replaceable>)</function></literal>
1223 <primary>atan2d</primary>
1225 <literal><function>atan2d(<replaceable>y</replaceable>,
1226 <replaceable>x</replaceable>)</function></literal>
1228 <entry>inverse tangent of
1229 <literal><replaceable>y</replaceable>/<replaceable>x</replaceable></literal></entry>
1235 <primary>cos</primary>
1237 <literal><function>cos(<replaceable>x</replaceable>)</function></literal>
1241 <primary>cosd</primary>
1243 <literal><function>cosd(<replaceable>x</replaceable>)</function></literal>
1245 <entry>cosine</entry>
1251 <primary>cot</primary>
1253 <literal><function>cot(<replaceable>x</replaceable>)</function></literal>
1257 <primary>cotd</primary>
1259 <literal><function>cotd(<replaceable>x</replaceable>)</function></literal>
1261 <entry>cotangent</entry>
1267 <primary>sin</primary>
1269 <literal><function>sin(<replaceable>x</replaceable>)</function></literal>
1273 <primary>sind</primary>
1275 <literal><function>sind(<replaceable>x</replaceable>)</function></literal>
1283 <primary>tan</primary>
1285 <literal><function>tan(<replaceable>x</replaceable>)</function></literal>
1289 <primary>tand</primary>
1291 <literal><function>tand(<replaceable>x</replaceable>)</function></literal>
1293 <entry>tangent</entry>
1301 Another way to work with angles measured in degrees is to use the unit
1302 transformation functions <literal><function>radians()</function></literal>
1303 and <literal><function>degrees()</function></literal> shown earlier.
1304 However, using the degree-based trigonometric functions is preferred,
1305 as that way avoids roundoff error for special cases such
1306 as <literal>sind(30)</>.
1313 <sect1 id="functions-string">
1314 <title>String Functions and Operators</title>
1317 This section describes functions and operators for examining and
1318 manipulating string values. Strings in this context include values
1319 of the types <type>character</type>, <type>character varying</type>,
1320 and <type>text</type>. Unless otherwise noted, all
1321 of the functions listed below work on all of these types, but be
1322 wary of potential effects of automatic space-padding when using the
1323 <type>character</type> type. Some functions also exist
1324 natively for the bit-string types.
1328 <acronym>SQL</acronym> defines some string functions that use
1329 key words, rather than commas, to separate
1330 arguments. Details are in
1331 <xref linkend="functions-string-sql">.
1332 <productname>PostgreSQL</> also provides versions of these functions
1333 that use the regular function invocation syntax
1334 (see <xref linkend="functions-string-other">).
1339 Before <productname>PostgreSQL</productname> 8.3, these functions would
1340 silently accept values of several non-string data types as well, due to
1341 the presence of implicit coercions from those data types to
1342 <type>text</>. Those coercions have been removed because they frequently
1343 caused surprising behaviors. However, the string concatenation operator
1344 (<literal>||</>) still accepts non-string input, so long as at least one
1345 input is of a string type, as shown in <xref
1346 linkend="functions-string-sql">. For other cases, insert an explicit
1347 coercion to <type>text</> if you need to duplicate the previous behavior.
1351 <table id="functions-string-sql">
1352 <title><acronym>SQL</acronym> String Functions and Operators</title>
1356 <entry>Function</entry>
1357 <entry>Return Type</entry>
1358 <entry>Description</entry>
1359 <entry>Example</entry>
1360 <entry>Result</entry>
1366 <entry><literal><parameter>string</parameter> <literal>||</literal>
1367 <parameter>string</parameter></literal></entry>
1368 <entry> <type>text</type> </entry>
1370 String concatenation
1372 <primary>character string</primary>
1373 <secondary>concatenation</secondary>
1376 <entry><literal>'Post' || 'greSQL'</literal></entry>
1377 <entry><literal>PostgreSQL</literal></entry>
1382 <literal><parameter>string</parameter> <literal>||</literal>
1383 <parameter>non-string</parameter></literal>
1385 <literal><parameter>non-string</parameter> <literal>||</literal>
1386 <parameter>string</parameter></literal>
1388 <entry> <type>text</type> </entry>
1390 String concatenation with one non-string input
1392 <entry><literal>'Value: ' || 42</literal></entry>
1393 <entry><literal>Value: 42</literal></entry>
1399 <primary>bit_length</primary>
1401 <literal><function>bit_length(<parameter>string</parameter>)</function></literal>
1403 <entry><type>int</type></entry>
1404 <entry>Number of bits in string</entry>
1405 <entry><literal>bit_length('jose')</literal></entry>
1406 <entry><literal>32</literal></entry>
1412 <primary>char_length</primary>
1414 <literal><function>char_length(<parameter>string</parameter>)</function></literal> or <literal><function>character_length(<parameter>string</parameter>)</function></literal>
1416 <entry><type>int</type></entry>
1418 Number of characters in string
1420 <primary>character string</primary>
1421 <secondary>length</secondary>
1424 <primary>length</primary>
1425 <secondary sortas="character string">of a character string</secondary>
1426 <see>character string, length</see>
1429 <entry><literal>char_length('jose')</literal></entry>
1430 <entry><literal>4</literal></entry>
1436 <primary>lower</primary>
1438 <literal><function>lower(<parameter>string</parameter>)</function></literal>
1440 <entry><type>text</type></entry>
1441 <entry>Convert string to lower case</entry>
1442 <entry><literal>lower('TOM')</literal></entry>
1443 <entry><literal>tom</literal></entry>
1449 <primary>octet_length</primary>
1451 <literal><function>octet_length(<parameter>string</parameter>)</function></literal>
1453 <entry><type>int</type></entry>
1454 <entry>Number of bytes in string</entry>
1455 <entry><literal>octet_length('jose')</literal></entry>
1456 <entry><literal>4</literal></entry>
1462 <primary>overlay</primary>
1464 <literal><function>overlay(<parameter>string</parameter> placing <parameter>string</parameter> from <type>int</type> <optional>for <type>int</type></optional>)</function></literal>
1466 <entry><type>text</type></entry>
1470 <entry><literal>overlay('Txxxxas' placing 'hom' from 2 for 4)</literal></entry>
1471 <entry><literal>Thomas</literal></entry>
1477 <primary>position</primary>
1479 <literal><function>position(<parameter>substring</parameter> in <parameter>string</parameter>)</function></literal>
1481 <entry><type>int</type></entry>
1482 <entry>Location of specified substring</entry>
1483 <entry><literal>position('om' in 'Thomas')</literal></entry>
1484 <entry><literal>3</literal></entry>
1490 <primary>substring</primary>
1492 <literal><function>substring(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</function></literal>
1494 <entry><type>text</type></entry>
1498 <entry><literal>substring('Thomas' from 2 for 3)</literal></entry>
1499 <entry><literal>hom</literal></entry>
1503 <entry><literal><function>substring(<parameter>string</parameter> from <replaceable>pattern</replaceable>)</function></literal></entry>
1504 <entry><type>text</type></entry>
1506 Extract substring matching POSIX regular expression. See
1507 <xref linkend="functions-matching"> for more information on pattern
1510 <entry><literal>substring('Thomas' from '...$')</literal></entry>
1511 <entry><literal>mas</literal></entry>
1515 <entry><literal><function>substring(<parameter>string</parameter> from <replaceable>pattern</replaceable> for <replaceable>escape</replaceable>)</function></literal></entry>
1516 <entry><type>text</type></entry>
1518 Extract substring matching <acronym>SQL</acronym> regular expression.
1519 See <xref linkend="functions-matching"> for more information on
1522 <entry><literal>substring('Thomas' from '%#"o_a#"_' for '#')</literal></entry>
1523 <entry><literal>oma</literal></entry>
1529 <primary>trim</primary>
1531 <literal><function>trim(<optional>leading | trailing | both</optional>
1532 <optional><parameter>characters</parameter></optional> from
1533 <parameter>string</parameter>)</function></literal>
1535 <entry><type>text</type></entry>
1537 Remove the longest string containing only characters from
1538 <parameter>characters</parameter> (a space by default) from the
1539 start, end, or both ends (<literal>both</> is the default)
1540 of <parameter>string</parameter>
1542 <entry><literal>trim(both 'xyz' from 'yxTomxx')</literal></entry>
1543 <entry><literal>Tom</literal></entry>
1548 <literal><function>trim(<optional>leading | trailing
1549 | both</optional> <optional>from</optional>
1550 <parameter>string</parameter>
1551 <optional>, <parameter>characters</parameter></optional>
1552 )</function></literal>
1554 <entry><type>text</type></entry>
1556 Non-standard syntax for <function>trim()</>
1558 <entry><literal>trim(both from 'yxTomxx', 'xyz')</literal></entry>
1559 <entry><literal>Tom</literal></entry>
1565 <primary>upper</primary>
1567 <literal><function>upper(<parameter>string</parameter>)</function></literal>
1569 <entry><type>text</type></entry>
1570 <entry>Convert string to upper case</entry>
1571 <entry><literal>upper('tom')</literal></entry>
1572 <entry><literal>TOM</literal></entry>
1579 Additional string manipulation functions are available and are
1580 listed in <xref linkend="functions-string-other">. Some of them are used internally to implement the
1581 <acronym>SQL</acronym>-standard string functions listed in <xref linkend="functions-string-sql">.
1584 <table id="functions-string-other">
1585 <title>Other String Functions</title>
1589 <entry>Function</entry>
1590 <entry>Return Type</entry>
1591 <entry>Description</entry>
1592 <entry>Example</entry>
1593 <entry>Result</entry>
1601 <primary>ascii</primary>
1603 <literal><function>ascii(<parameter>string</parameter>)</function></literal>
1605 <entry><type>int</type></entry>
1607 <acronym>ASCII</acronym> code of the first character of the
1608 argument. For <acronym>UTF8</acronym> returns the Unicode code
1609 point of the character. For other multibyte encodings, the
1610 argument must be an <acronym>ASCII</acronym> character.
1612 <entry><literal>ascii('x')</literal></entry>
1613 <entry><literal>120</literal></entry>
1619 <primary>btrim</primary>
1621 <literal><function>btrim(<parameter>string</parameter> <type>text</type>
1622 <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
1624 <entry><type>text</type></entry>
1626 Remove the longest string consisting only of characters
1627 in <parameter>characters</parameter> (a space by default)
1628 from the start and end of <parameter>string</parameter>
1630 <entry><literal>btrim('xyxtrimyyx', 'xyz')</literal></entry>
1631 <entry><literal>trim</literal></entry>
1637 <primary>chr</primary>
1639 <literal><function>chr(<type>int</type>)</function></literal>
1641 <entry><type>text</type></entry>
1643 Character with the given code. For <acronym>UTF8</acronym> the
1644 argument is treated as a Unicode code point. For other multibyte
1645 encodings the argument must designate an
1646 <acronym>ASCII</acronym> character. The NULL (0) character is not
1647 allowed because text data types cannot store such bytes.
1649 <entry><literal>chr(65)</literal></entry>
1650 <entry><literal>A</literal></entry>
1656 <primary>concat</primary>
1658 <literal><function>concat(<parameter>str</parameter> <type>"any"</type>
1659 [, <parameter>str</parameter> <type>"any"</type> [, ...] ])</function></literal>
1661 <entry><type>text</type></entry>
1663 Concatenate the text representations of all the arguments.
1664 NULL arguments are ignored.
1666 <entry><literal>concat('abcde', 2, NULL, 22)</literal></entry>
1667 <entry><literal>abcde222</literal></entry>
1673 <primary>concat_ws</primary>
1675 <literal><function>concat_ws(<parameter>sep</parameter> <type>text</type>,
1676 <parameter>str</parameter> <type>"any"</type>
1677 [, <parameter>str</parameter> <type>"any"</type> [, ...] ])</function></literal>
1679 <entry><type>text</type></entry>
1681 Concatenate all but the first argument with separators. The first
1682 argument is used as the separator string. NULL arguments are ignored.
1684 <entry><literal>concat_ws(',', 'abcde', 2, NULL, 22)</literal></entry>
1685 <entry><literal>abcde,2,22</literal></entry>
1691 <primary>convert</primary>
1693 <literal><function>convert(<parameter>string</parameter> <type>bytea</type>,
1694 <parameter>src_encoding</parameter> <type>name</type>,
1695 <parameter>dest_encoding</parameter> <type>name</type>)</function></literal>
1697 <entry><type>bytea</type></entry>
1699 Convert string to <parameter>dest_encoding</parameter>. The
1700 original encoding is specified by
1701 <parameter>src_encoding</parameter>. The
1702 <parameter>string</parameter> must be valid in this encoding.
1703 Conversions can be defined by <command>CREATE CONVERSION</command>.
1704 Also there are some predefined conversions. See <xref
1705 linkend="conversion-names"> for available conversions.
1707 <entry><literal>convert('text_in_utf8', 'UTF8', 'LATIN1')</literal></entry>
1708 <entry><literal>text_in_utf8</literal> represented in Latin-1
1709 encoding (ISO 8859-1)</entry>
1715 <primary>convert_from</primary>
1717 <literal><function>convert_from(<parameter>string</parameter> <type>bytea</type>,
1718 <parameter>src_encoding</parameter> <type>name</type>)</function></literal>
1720 <entry><type>text</type></entry>
1722 Convert string to the database encoding. The original encoding
1723 is specified by <parameter>src_encoding</parameter>. The
1724 <parameter>string</parameter> must be valid in this encoding.
1726 <entry><literal>convert_from('text_in_utf8', 'UTF8')</literal></entry>
1727 <entry><literal>text_in_utf8</literal> represented in the current database encoding</entry>
1733 <primary>convert_to</primary>
1735 <literal><function>convert_to(<parameter>string</parameter> <type>text</type>,
1736 <parameter>dest_encoding</parameter> <type>name</type>)</function></literal>
1738 <entry><type>bytea</type></entry>
1740 Convert string to <parameter>dest_encoding</parameter>.
1742 <entry><literal>convert_to('some text', 'UTF8')</literal></entry>
1743 <entry><literal>some text</literal> represented in the UTF8 encoding</entry>
1749 <primary>decode</primary>
1751 <literal><function>decode(<parameter>string</parameter> <type>text</type>,
1752 <parameter>format</parameter> <type>text</type>)</function></literal>
1754 <entry><type>bytea</type></entry>
1756 Decode binary data from textual representation in <parameter>string</>.
1757 Options for <parameter>format</> are same as in <function>encode</>.
1759 <entry><literal>decode('MTIzAAE=', 'base64')</literal></entry>
1760 <entry><literal>\x3132330001</literal></entry>
1766 <primary>encode</primary>
1768 <literal><function>encode(<parameter>data</parameter> <type>bytea</type>,
1769 <parameter>format</parameter> <type>text</type>)</function></literal>
1771 <entry><type>text</type></entry>
1773 Encode binary data into a textual representation. Supported
1774 formats are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
1775 <literal>escape</> converts zero bytes and high-bit-set bytes to
1776 octal sequences (<literal>\</><replaceable>nnn</>) and
1777 doubles backslashes.
1779 <entry><literal>encode(E'123\\000\\001', 'base64')</literal></entry>
1780 <entry><literal>MTIzAAE=</literal></entry>
1786 <primary>format</primary>
1788 <literal><function>format</function>(<parameter>formatstr</parameter> <type>text</type>
1789 [, <parameter>formatarg</parameter> <type>"any"</type> [, ...] ])</literal>
1791 <entry><type>text</type></entry>
1793 Format arguments according to a format string.
1794 This function is similar to the C function <function>sprintf</>.
1795 See <xref linkend="functions-string-format">.
1797 <entry><literal>format('Hello %s, %1$s', 'World')</literal></entry>
1798 <entry><literal>Hello World, World</literal></entry>
1804 <primary>initcap</primary>
1806 <literal><function>initcap(<parameter>string</parameter>)</function></literal>
1808 <entry><type>text</type></entry>
1810 Convert the first letter of each word to upper case and the
1811 rest to lower case. Words are sequences of alphanumeric
1812 characters separated by non-alphanumeric characters.
1814 <entry><literal>initcap('hi THOMAS')</literal></entry>
1815 <entry><literal>Hi Thomas</literal></entry>
1821 <primary>left</primary>
1823 <literal><function>left(<parameter>str</parameter> <type>text</type>,
1824 <parameter>n</parameter> <type>int</type>)</function></literal>
1826 <entry><type>text</type></entry>
1828 Return first <replaceable>n</> characters in the string. When <replaceable>n</>
1829 is negative, return all but last |<replaceable>n</>| characters.
1831 <entry><literal>left('abcde', 2)</literal></entry>
1832 <entry><literal>ab</literal></entry>
1838 <primary>length</primary>
1840 <literal><function>length(<parameter>string</parameter>)</function></literal>
1842 <entry><type>int</type></entry>
1844 Number of characters in <parameter>string</parameter>
1846 <entry><literal>length('jose')</literal></entry>
1847 <entry><literal>4</literal></entry>
1851 <entry><literal><function>length(<parameter>string</parameter> <type>bytea</type>,
1852 <parameter>encoding</parameter> <type>name</type> )</function></literal></entry>
1853 <entry><type>int</type></entry>
1855 Number of characters in <parameter>string</parameter> in the given
1856 <parameter>encoding</parameter>. The <parameter>string</parameter>
1857 must be valid in this encoding.
1859 <entry><literal>length('jose', 'UTF8')</literal></entry>
1860 <entry><literal>4</literal></entry>
1866 <primary>lpad</primary>
1868 <literal><function>lpad(<parameter>string</parameter> <type>text</type>,
1869 <parameter>length</parameter> <type>int</type>
1870 <optional>, <parameter>fill</parameter> <type>text</type></optional>)</function></literal>
1872 <entry><type>text</type></entry>
1874 Fill up the <parameter>string</parameter> to length
1875 <parameter>length</parameter> by prepending the characters
1876 <parameter>fill</parameter> (a space by default). If the
1877 <parameter>string</parameter> is already longer than
1878 <parameter>length</parameter> then it is truncated (on the
1881 <entry><literal>lpad('hi', 5, 'xy')</literal></entry>
1882 <entry><literal>xyxhi</literal></entry>
1888 <primary>ltrim</primary>
1890 <literal><function>ltrim(<parameter>string</parameter> <type>text</type>
1891 <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
1893 <entry><type>text</type></entry>
1895 Remove the longest string containing only characters from
1896 <parameter>characters</parameter> (a space by default) from the start of
1897 <parameter>string</parameter>
1899 <entry><literal>ltrim('zzzytest', 'xyz')</literal></entry>
1900 <entry><literal>test</literal></entry>
1906 <primary>md5</primary>
1908 <literal><function>md5(<parameter>string</parameter>)</function></literal>
1910 <entry><type>text</type></entry>
1912 Calculates the MD5 hash of <parameter>string</parameter>,
1913 returning the result in hexadecimal
1915 <entry><literal>md5('abc')</literal></entry>
1916 <entry><literal>900150983cd24fb0 d6963f7d28e17f72</literal></entry>
1922 <primary>parse_ident</primary>
1924 <literal><function>parse_ident(<parameter>qualified_identifier</parameter> <type>text</type>
1925 [, <parameter>strictmode</parameter> <type>boolean</type> DEFAULT true ] )</function></literal>
1927 <entry><type>text[]</type></entry>
1929 Split <parameter>qualified_identifier</parameter> into an array of
1930 identifiers, removing any quoting of individual identifiers. By
1931 default, extra characters after the last identifier are considered an
1932 error; but if the second parameter is <literal>false</>, then such
1933 extra characters are ignored. (This behavior is useful for parsing
1934 names for objects like functions.) Note that this function does not
1935 truncate over-length identifiers. If you want truncation you can cast
1936 the result to <type>name[]</>.
1938 <entry><literal>parse_ident('"SomeSchema".someTable')</literal></entry>
1939 <entry><literal>{SomeSchema,sometable}</literal></entry>
1945 <primary>pg_client_encoding</primary>
1947 <literal><function>pg_client_encoding()</function></literal>
1949 <entry><type>name</type></entry>
1951 Current client encoding name
1953 <entry><literal>pg_client_encoding()</literal></entry>
1954 <entry><literal>SQL_ASCII</literal></entry>
1960 <primary>quote_ident</primary>
1962 <literal><function>quote_ident(<parameter>string</parameter> <type>text</type>)</function></literal>
1964 <entry><type>text</type></entry>
1966 Return the given string suitably quoted to be used as an identifier
1967 in an <acronym>SQL</acronym> statement string.
1968 Quotes are added only if necessary (i.e., if the string contains
1969 non-identifier characters or would be case-folded).
1970 Embedded quotes are properly doubled.
1971 See also <xref linkend="plpgsql-quote-literal-example">.
1973 <entry><literal>quote_ident('Foo bar')</literal></entry>
1974 <entry><literal>"Foo bar"</literal></entry>
1980 <primary>quote_literal</primary>
1982 <literal><function>quote_literal(<parameter>string</parameter> <type>text</type>)</function></literal>
1984 <entry><type>text</type></entry>
1986 Return the given string suitably quoted to be used as a string literal
1987 in an <acronym>SQL</acronym> statement string.
1988 Embedded single-quotes and backslashes are properly doubled.
1989 Note that <function>quote_literal</function> returns null on null
1990 input; if the argument might be null,
1991 <function>quote_nullable</function> is often more suitable.
1992 See also <xref linkend="plpgsql-quote-literal-example">.
1994 <entry><literal>quote_literal(E'O\'Reilly')</literal></entry>
1995 <entry><literal>'O''Reilly'</literal></entry>
1999 <entry><literal><function>quote_literal(<parameter>value</parameter> <type>anyelement</type>)</function></literal></entry>
2000 <entry><type>text</type></entry>
2002 Coerce the given value to text and then quote it as a literal.
2003 Embedded single-quotes and backslashes are properly doubled.
2005 <entry><literal>quote_literal(42.5)</literal></entry>
2006 <entry><literal>'42.5'</literal></entry>
2012 <primary>quote_nullable</primary>
2014 <literal><function>quote_nullable(<parameter>string</parameter> <type>text</type>)</function></literal>
2016 <entry><type>text</type></entry>
2018 Return the given string suitably quoted to be used as a string literal
2019 in an <acronym>SQL</acronym> statement string; or, if the argument
2020 is null, return <literal>NULL</>.
2021 Embedded single-quotes and backslashes are properly doubled.
2022 See also <xref linkend="plpgsql-quote-literal-example">.
2024 <entry><literal>quote_nullable(NULL)</literal></entry>
2025 <entry><literal>NULL</literal></entry>
2029 <entry><literal><function>quote_nullable(<parameter>value</parameter> <type>anyelement</type>)</function></literal></entry>
2030 <entry><type>text</type></entry>
2032 Coerce the given value to text and then quote it as a literal;
2033 or, if the argument is null, return <literal>NULL</>.
2034 Embedded single-quotes and backslashes are properly doubled.
2036 <entry><literal>quote_nullable(42.5)</literal></entry>
2037 <entry><literal>'42.5'</literal></entry>
2043 <primary>regexp_match</primary>
2045 <literal><function>regexp_match(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
2047 <entry><type>text[]</type></entry>
2049 Return captured substring(s) resulting from the first match of a POSIX
2050 regular expression to the <parameter>string</parameter>. See
2051 <xref linkend="functions-posix-regexp"> for more information.
2053 <entry><literal>regexp_match('foobarbequebaz', '(bar)(beque)')</literal></entry>
2054 <entry><literal>{bar,beque}</literal></entry>
2060 <primary>regexp_matches</primary>
2062 <literal><function>regexp_matches(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
2064 <entry><type>setof text[]</type></entry>
2066 Return captured substring(s) resulting from matching a POSIX regular
2067 expression to the <parameter>string</parameter>. See
2068 <xref linkend="functions-posix-regexp"> for more information.
2070 <entry><literal>regexp_matches('foobarbequebaz', 'ba.', 'g')</literal></entry>
2071 <entry><literal>{bar}</literal><para><literal>{baz}</literal></para> (2 rows)</entry>
2077 <primary>regexp_replace</primary>
2079 <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>
2081 <entry><type>text</type></entry>
2083 Replace substring(s) matching a POSIX regular expression. See
2084 <xref linkend="functions-posix-regexp"> for more information.
2086 <entry><literal>regexp_replace('Thomas', '.[mN]a.', 'M')</literal></entry>
2087 <entry><literal>ThM</literal></entry>
2093 <primary>regexp_split_to_array</primary>
2095 <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>
2097 <entry><type>text[]</type></entry>
2099 Split <parameter>string</parameter> using a POSIX regular expression as
2100 the delimiter. See <xref linkend="functions-posix-regexp"> for more
2103 <entry><literal>regexp_split_to_array('hello world', E'\\s+')</literal></entry>
2104 <entry><literal>{hello,world}</literal></entry>
2110 <primary>regexp_split_to_table</primary>
2112 <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>
2114 <entry><type>setof text</type></entry>
2116 Split <parameter>string</parameter> using a POSIX regular expression as
2117 the delimiter. See <xref linkend="functions-posix-regexp"> for more
2120 <entry><literal>regexp_split_to_table('hello world', E'\\s+')</literal></entry>
2121 <entry><literal>hello</literal><para><literal>world</literal></para> (2 rows)</entry>
2127 <primary>repeat</primary>
2129 <literal><function>repeat(<parameter>string</parameter> <type>text</type>, <parameter>number</parameter> <type>int</type>)</function></literal>
2131 <entry><type>text</type></entry>
2132 <entry>Repeat <parameter>string</parameter> the specified
2133 <parameter>number</parameter> of times</entry>
2134 <entry><literal>repeat('Pg', 4)</literal></entry>
2135 <entry><literal>PgPgPgPg</literal></entry>
2141 <primary>replace</primary>
2143 <literal><function>replace(<parameter>string</parameter> <type>text</type>,
2144 <parameter>from</parameter> <type>text</type>,
2145 <parameter>to</parameter> <type>text</type>)</function></literal>
2147 <entry><type>text</type></entry>
2148 <entry>Replace all occurrences in <parameter>string</parameter> of substring
2149 <parameter>from</parameter> with substring <parameter>to</parameter>
2151 <entry><literal>replace('abcdefabcdef', 'cd', 'XX')</literal></entry>
2152 <entry><literal>abXXefabXXef</literal></entry>
2158 <primary>reverse</primary>
2160 <literal><function>reverse(<parameter>str</parameter>)</function></literal>
2162 <entry><type>text</type></entry>
2164 Return reversed string.
2166 <entry><literal>reverse('abcde')</literal></entry>
2167 <entry><literal>edcba</literal></entry>
2173 <primary>right</primary>
2175 <literal><function>right(<parameter>str</parameter> <type>text</type>,
2176 <parameter>n</parameter> <type>int</type>)</function></literal>
2178 <entry><type>text</type></entry>
2180 Return last <replaceable>n</> characters in the string. When <replaceable>n</>
2181 is negative, return all but first |<replaceable>n</>| characters.
2183 <entry><literal>right('abcde', 2)</literal></entry>
2184 <entry><literal>de</literal></entry>
2190 <primary>rpad</primary>
2192 <literal><function>rpad(<parameter>string</parameter> <type>text</type>,
2193 <parameter>length</parameter> <type>int</type>
2194 <optional>, <parameter>fill</parameter> <type>text</type></optional>)</function></literal>
2196 <entry><type>text</type></entry>
2198 Fill up the <parameter>string</parameter> to length
2199 <parameter>length</parameter> by appending the characters
2200 <parameter>fill</parameter> (a space by default). If the
2201 <parameter>string</parameter> is already longer than
2202 <parameter>length</parameter> then it is truncated.
2204 <entry><literal>rpad('hi', 5, 'xy')</literal></entry>
2205 <entry><literal>hixyx</literal></entry>
2211 <primary>rtrim</primary>
2213 <literal><function>rtrim(<parameter>string</parameter> <type>text</type>
2214 <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
2216 <entry><type>text</type></entry>
2218 Remove the longest string containing only characters from
2219 <parameter>characters</parameter> (a space by default) from the end of
2220 <parameter>string</parameter>
2222 <entry><literal>rtrim('testxxzx', 'xyz')</literal></entry>
2223 <entry><literal>test</literal></entry>
2229 <primary>split_part</primary>
2231 <literal><function>split_part(<parameter>string</parameter> <type>text</type>,
2232 <parameter>delimiter</parameter> <type>text</type>,
2233 <parameter>field</parameter> <type>int</type>)</function></literal>
2235 <entry><type>text</type></entry>
2236 <entry>Split <parameter>string</parameter> on <parameter>delimiter</parameter>
2237 and return the given field (counting from one)
2239 <entry><literal>split_part('abc~@~def~@~ghi', '~@~', 2)</literal></entry>
2240 <entry><literal>def</literal></entry>
2246 <primary>strpos</primary>
2248 <literal><function>strpos(<parameter>string</parameter>, <parameter>substring</parameter>)</function></literal>
2250 <entry><type>int</type></entry>
2252 Location of specified substring (same as
2253 <literal>position(<parameter>substring</parameter> in
2254 <parameter>string</parameter>)</literal>, but note the reversed
2257 <entry><literal>strpos('high', 'ig')</literal></entry>
2258 <entry><literal>2</literal></entry>
2264 <primary>substr</primary>
2266 <literal><function>substr(<parameter>string</parameter>, <parameter>from</parameter> <optional>, <parameter>count</parameter></optional>)</function></literal>
2268 <entry><type>text</type></entry>
2270 Extract substring (same as
2271 <literal>substring(<parameter>string</parameter> from <parameter>from</parameter> for <parameter>count</parameter>)</literal>)
2273 <entry><literal>substr('alphabet', 3, 2)</literal></entry>
2274 <entry><literal>ph</literal></entry>
2280 <primary>to_ascii</primary>
2282 <literal><function>to_ascii(<parameter>string</parameter> <type>text</type>
2283 <optional>, <parameter>encoding</parameter> <type>text</type></optional>)</function></literal>
2285 <entry><type>text</type></entry>
2287 Convert <parameter>string</parameter> to <acronym>ASCII</acronym> from another encoding
2288 (only supports conversion from <literal>LATIN1</>, <literal>LATIN2</>, <literal>LATIN9</>,
2289 and <literal>WIN1250</> encodings)
2291 <entry><literal>to_ascii('Karel')</literal></entry>
2292 <entry><literal>Karel</literal></entry>
2298 <primary>to_hex</primary>
2300 <literal><function>to_hex(<parameter>number</parameter> <type>int</type>
2301 or <type>bigint</type>)</function></literal>
2303 <entry><type>text</type></entry>
2304 <entry>Convert <parameter>number</parameter> to its equivalent hexadecimal
2307 <entry><literal>to_hex(2147483647)</literal></entry>
2308 <entry><literal>7fffffff</literal></entry>
2314 <primary>translate</primary>
2316 <literal><function>translate(<parameter>string</parameter> <type>text</type>,
2317 <parameter>from</parameter> <type>text</type>,
2318 <parameter>to</parameter> <type>text</type>)</function></literal>
2320 <entry><type>text</type></entry>
2322 Any character in <parameter>string</parameter> that matches a
2323 character in the <parameter>from</parameter> set is replaced by
2324 the corresponding character in the <parameter>to</parameter>
2325 set. If <parameter>from</parameter> is longer than
2326 <parameter>to</parameter>, occurrences of the extra characters in
2327 <parameter>from</parameter> are removed.
2329 <entry><literal>translate('12345', '143', 'ax')</literal></entry>
2330 <entry><literal>a2x5</literal></entry>
2338 The <function>concat</function>, <function>concat_ws</function> and
2339 <function>format</function> functions are variadic, so it is possible to
2340 pass the values to be concatenated or formatted as an array marked with
2341 the <literal>VARIADIC</literal> keyword (see <xref
2342 linkend="xfunc-sql-variadic-functions">). The array's elements are
2343 treated as if they were separate ordinary arguments to the function.
2344 If the variadic array argument is NULL, <function>concat</function>
2345 and <function>concat_ws</function> return NULL, but
2346 <function>format</function> treats a NULL as a zero-element array.
2350 See also the aggregate function <function>string_agg</function> in
2351 <xref linkend="functions-aggregate">.
2354 <table id="conversion-names">
2355 <title>Built-in Conversions</title>
2359 <entry>Conversion Name
2362 The conversion names follow a standard naming scheme: The
2363 official name of the source encoding with all
2364 non-alphanumeric characters replaced by underscores, followed
2365 by <literal>_to_</literal>, followed by the similarly processed
2366 destination encoding name. Therefore, the names might deviate
2367 from the customary encoding names.
2371 <entry>Source Encoding</entry>
2372 <entry>Destination Encoding</entry>
2378 <entry><literal>ascii_to_mic</literal></entry>
2379 <entry><literal>SQL_ASCII</literal></entry>
2380 <entry><literal>MULE_INTERNAL</literal></entry>
2384 <entry><literal>ascii_to_utf8</literal></entry>
2385 <entry><literal>SQL_ASCII</literal></entry>
2386 <entry><literal>UTF8</literal></entry>
2390 <entry><literal>big5_to_euc_tw</literal></entry>
2391 <entry><literal>BIG5</literal></entry>
2392 <entry><literal>EUC_TW</literal></entry>
2396 <entry><literal>big5_to_mic</literal></entry>
2397 <entry><literal>BIG5</literal></entry>
2398 <entry><literal>MULE_INTERNAL</literal></entry>
2402 <entry><literal>big5_to_utf8</literal></entry>
2403 <entry><literal>BIG5</literal></entry>
2404 <entry><literal>UTF8</literal></entry>
2408 <entry><literal>euc_cn_to_mic</literal></entry>
2409 <entry><literal>EUC_CN</literal></entry>
2410 <entry><literal>MULE_INTERNAL</literal></entry>
2414 <entry><literal>euc_cn_to_utf8</literal></entry>
2415 <entry><literal>EUC_CN</literal></entry>
2416 <entry><literal>UTF8</literal></entry>
2420 <entry><literal>euc_jp_to_mic</literal></entry>
2421 <entry><literal>EUC_JP</literal></entry>
2422 <entry><literal>MULE_INTERNAL</literal></entry>
2426 <entry><literal>euc_jp_to_sjis</literal></entry>
2427 <entry><literal>EUC_JP</literal></entry>
2428 <entry><literal>SJIS</literal></entry>
2432 <entry><literal>euc_jp_to_utf8</literal></entry>
2433 <entry><literal>EUC_JP</literal></entry>
2434 <entry><literal>UTF8</literal></entry>
2438 <entry><literal>euc_kr_to_mic</literal></entry>
2439 <entry><literal>EUC_KR</literal></entry>
2440 <entry><literal>MULE_INTERNAL</literal></entry>
2444 <entry><literal>euc_kr_to_utf8</literal></entry>
2445 <entry><literal>EUC_KR</literal></entry>
2446 <entry><literal>UTF8</literal></entry>
2450 <entry><literal>euc_tw_to_big5</literal></entry>
2451 <entry><literal>EUC_TW</literal></entry>
2452 <entry><literal>BIG5</literal></entry>
2456 <entry><literal>euc_tw_to_mic</literal></entry>
2457 <entry><literal>EUC_TW</literal></entry>
2458 <entry><literal>MULE_INTERNAL</literal></entry>
2462 <entry><literal>euc_tw_to_utf8</literal></entry>
2463 <entry><literal>EUC_TW</literal></entry>
2464 <entry><literal>UTF8</literal></entry>
2468 <entry><literal>gb18030_to_utf8</literal></entry>
2469 <entry><literal>GB18030</literal></entry>
2470 <entry><literal>UTF8</literal></entry>
2474 <entry><literal>gbk_to_utf8</literal></entry>
2475 <entry><literal>GBK</literal></entry>
2476 <entry><literal>UTF8</literal></entry>
2480 <entry><literal>iso_8859_10_to_utf8</literal></entry>
2481 <entry><literal>LATIN6</literal></entry>
2482 <entry><literal>UTF8</literal></entry>
2486 <entry><literal>iso_8859_13_to_utf8</literal></entry>
2487 <entry><literal>LATIN7</literal></entry>
2488 <entry><literal>UTF8</literal></entry>
2492 <entry><literal>iso_8859_14_to_utf8</literal></entry>
2493 <entry><literal>LATIN8</literal></entry>
2494 <entry><literal>UTF8</literal></entry>
2498 <entry><literal>iso_8859_15_to_utf8</literal></entry>
2499 <entry><literal>LATIN9</literal></entry>
2500 <entry><literal>UTF8</literal></entry>
2504 <entry><literal>iso_8859_16_to_utf8</literal></entry>
2505 <entry><literal>LATIN10</literal></entry>
2506 <entry><literal>UTF8</literal></entry>
2510 <entry><literal>iso_8859_1_to_mic</literal></entry>
2511 <entry><literal>LATIN1</literal></entry>
2512 <entry><literal>MULE_INTERNAL</literal></entry>
2516 <entry><literal>iso_8859_1_to_utf8</literal></entry>
2517 <entry><literal>LATIN1</literal></entry>
2518 <entry><literal>UTF8</literal></entry>
2522 <entry><literal>iso_8859_2_to_mic</literal></entry>
2523 <entry><literal>LATIN2</literal></entry>
2524 <entry><literal>MULE_INTERNAL</literal></entry>
2528 <entry><literal>iso_8859_2_to_utf8</literal></entry>
2529 <entry><literal>LATIN2</literal></entry>
2530 <entry><literal>UTF8</literal></entry>
2534 <entry><literal>iso_8859_2_to_windows_1250</literal></entry>
2535 <entry><literal>LATIN2</literal></entry>
2536 <entry><literal>WIN1250</literal></entry>
2540 <entry><literal>iso_8859_3_to_mic</literal></entry>
2541 <entry><literal>LATIN3</literal></entry>
2542 <entry><literal>MULE_INTERNAL</literal></entry>
2546 <entry><literal>iso_8859_3_to_utf8</literal></entry>
2547 <entry><literal>LATIN3</literal></entry>
2548 <entry><literal>UTF8</literal></entry>
2552 <entry><literal>iso_8859_4_to_mic</literal></entry>
2553 <entry><literal>LATIN4</literal></entry>
2554 <entry><literal>MULE_INTERNAL</literal></entry>
2558 <entry><literal>iso_8859_4_to_utf8</literal></entry>
2559 <entry><literal>LATIN4</literal></entry>
2560 <entry><literal>UTF8</literal></entry>
2564 <entry><literal>iso_8859_5_to_koi8_r</literal></entry>
2565 <entry><literal>ISO_8859_5</literal></entry>
2566 <entry><literal>KOI8R</literal></entry>
2570 <entry><literal>iso_8859_5_to_mic</literal></entry>
2571 <entry><literal>ISO_8859_5</literal></entry>
2572 <entry><literal>MULE_INTERNAL</literal></entry>
2576 <entry><literal>iso_8859_5_to_utf8</literal></entry>
2577 <entry><literal>ISO_8859_5</literal></entry>
2578 <entry><literal>UTF8</literal></entry>
2582 <entry><literal>iso_8859_5_to_windows_1251</literal></entry>
2583 <entry><literal>ISO_8859_5</literal></entry>
2584 <entry><literal>WIN1251</literal></entry>
2588 <entry><literal>iso_8859_5_to_windows_866</literal></entry>
2589 <entry><literal>ISO_8859_5</literal></entry>
2590 <entry><literal>WIN866</literal></entry>
2594 <entry><literal>iso_8859_6_to_utf8</literal></entry>
2595 <entry><literal>ISO_8859_6</literal></entry>
2596 <entry><literal>UTF8</literal></entry>
2600 <entry><literal>iso_8859_7_to_utf8</literal></entry>
2601 <entry><literal>ISO_8859_7</literal></entry>
2602 <entry><literal>UTF8</literal></entry>
2606 <entry><literal>iso_8859_8_to_utf8</literal></entry>
2607 <entry><literal>ISO_8859_8</literal></entry>
2608 <entry><literal>UTF8</literal></entry>
2612 <entry><literal>iso_8859_9_to_utf8</literal></entry>
2613 <entry><literal>LATIN5</literal></entry>
2614 <entry><literal>UTF8</literal></entry>
2618 <entry><literal>johab_to_utf8</literal></entry>
2619 <entry><literal>JOHAB</literal></entry>
2620 <entry><literal>UTF8</literal></entry>
2624 <entry><literal>koi8_r_to_iso_8859_5</literal></entry>
2625 <entry><literal>KOI8R</literal></entry>
2626 <entry><literal>ISO_8859_5</literal></entry>
2630 <entry><literal>koi8_r_to_mic</literal></entry>
2631 <entry><literal>KOI8R</literal></entry>
2632 <entry><literal>MULE_INTERNAL</literal></entry>
2636 <entry><literal>koi8_r_to_utf8</literal></entry>
2637 <entry><literal>KOI8R</literal></entry>
2638 <entry><literal>UTF8</literal></entry>
2642 <entry><literal>koi8_r_to_windows_1251</literal></entry>
2643 <entry><literal>KOI8R</literal></entry>
2644 <entry><literal>WIN1251</literal></entry>
2648 <entry><literal>koi8_r_to_windows_866</literal></entry>
2649 <entry><literal>KOI8R</literal></entry>
2650 <entry><literal>WIN866</literal></entry>
2654 <entry><literal>koi8_u_to_utf8</literal></entry>
2655 <entry><literal>KOI8U</literal></entry>
2656 <entry><literal>UTF8</literal></entry>
2660 <entry><literal>mic_to_ascii</literal></entry>
2661 <entry><literal>MULE_INTERNAL</literal></entry>
2662 <entry><literal>SQL_ASCII</literal></entry>
2666 <entry><literal>mic_to_big5</literal></entry>
2667 <entry><literal>MULE_INTERNAL</literal></entry>
2668 <entry><literal>BIG5</literal></entry>
2672 <entry><literal>mic_to_euc_cn</literal></entry>
2673 <entry><literal>MULE_INTERNAL</literal></entry>
2674 <entry><literal>EUC_CN</literal></entry>
2678 <entry><literal>mic_to_euc_jp</literal></entry>
2679 <entry><literal>MULE_INTERNAL</literal></entry>
2680 <entry><literal>EUC_JP</literal></entry>
2684 <entry><literal>mic_to_euc_kr</literal></entry>
2685 <entry><literal>MULE_INTERNAL</literal></entry>
2686 <entry><literal>EUC_KR</literal></entry>
2690 <entry><literal>mic_to_euc_tw</literal></entry>
2691 <entry><literal>MULE_INTERNAL</literal></entry>
2692 <entry><literal>EUC_TW</literal></entry>
2696 <entry><literal>mic_to_iso_8859_1</literal></entry>
2697 <entry><literal>MULE_INTERNAL</literal></entry>
2698 <entry><literal>LATIN1</literal></entry>
2702 <entry><literal>mic_to_iso_8859_2</literal></entry>
2703 <entry><literal>MULE_INTERNAL</literal></entry>
2704 <entry><literal>LATIN2</literal></entry>
2708 <entry><literal>mic_to_iso_8859_3</literal></entry>
2709 <entry><literal>MULE_INTERNAL</literal></entry>
2710 <entry><literal>LATIN3</literal></entry>
2714 <entry><literal>mic_to_iso_8859_4</literal></entry>
2715 <entry><literal>MULE_INTERNAL</literal></entry>
2716 <entry><literal>LATIN4</literal></entry>
2720 <entry><literal>mic_to_iso_8859_5</literal></entry>
2721 <entry><literal>MULE_INTERNAL</literal></entry>
2722 <entry><literal>ISO_8859_5</literal></entry>
2726 <entry><literal>mic_to_koi8_r</literal></entry>
2727 <entry><literal>MULE_INTERNAL</literal></entry>
2728 <entry><literal>KOI8R</literal></entry>
2732 <entry><literal>mic_to_sjis</literal></entry>
2733 <entry><literal>MULE_INTERNAL</literal></entry>
2734 <entry><literal>SJIS</literal></entry>
2738 <entry><literal>mic_to_windows_1250</literal></entry>
2739 <entry><literal>MULE_INTERNAL</literal></entry>
2740 <entry><literal>WIN1250</literal></entry>
2744 <entry><literal>mic_to_windows_1251</literal></entry>
2745 <entry><literal>MULE_INTERNAL</literal></entry>
2746 <entry><literal>WIN1251</literal></entry>
2750 <entry><literal>mic_to_windows_866</literal></entry>
2751 <entry><literal>MULE_INTERNAL</literal></entry>
2752 <entry><literal>WIN866</literal></entry>
2756 <entry><literal>sjis_to_euc_jp</literal></entry>
2757 <entry><literal>SJIS</literal></entry>
2758 <entry><literal>EUC_JP</literal></entry>
2762 <entry><literal>sjis_to_mic</literal></entry>
2763 <entry><literal>SJIS</literal></entry>
2764 <entry><literal>MULE_INTERNAL</literal></entry>
2768 <entry><literal>sjis_to_utf8</literal></entry>
2769 <entry><literal>SJIS</literal></entry>
2770 <entry><literal>UTF8</literal></entry>
2774 <entry><literal>tcvn_to_utf8</literal></entry>
2775 <entry><literal>WIN1258</literal></entry>
2776 <entry><literal>UTF8</literal></entry>
2780 <entry><literal>uhc_to_utf8</literal></entry>
2781 <entry><literal>UHC</literal></entry>
2782 <entry><literal>UTF8</literal></entry>
2786 <entry><literal>utf8_to_ascii</literal></entry>
2787 <entry><literal>UTF8</literal></entry>
2788 <entry><literal>SQL_ASCII</literal></entry>
2792 <entry><literal>utf8_to_big5</literal></entry>
2793 <entry><literal>UTF8</literal></entry>
2794 <entry><literal>BIG5</literal></entry>
2798 <entry><literal>utf8_to_euc_cn</literal></entry>
2799 <entry><literal>UTF8</literal></entry>
2800 <entry><literal>EUC_CN</literal></entry>
2804 <entry><literal>utf8_to_euc_jp</literal></entry>
2805 <entry><literal>UTF8</literal></entry>
2806 <entry><literal>EUC_JP</literal></entry>
2810 <entry><literal>utf8_to_euc_kr</literal></entry>
2811 <entry><literal>UTF8</literal></entry>
2812 <entry><literal>EUC_KR</literal></entry>
2816 <entry><literal>utf8_to_euc_tw</literal></entry>
2817 <entry><literal>UTF8</literal></entry>
2818 <entry><literal>EUC_TW</literal></entry>
2822 <entry><literal>utf8_to_gb18030</literal></entry>
2823 <entry><literal>UTF8</literal></entry>
2824 <entry><literal>GB18030</literal></entry>
2828 <entry><literal>utf8_to_gbk</literal></entry>
2829 <entry><literal>UTF8</literal></entry>
2830 <entry><literal>GBK</literal></entry>
2834 <entry><literal>utf8_to_iso_8859_1</literal></entry>
2835 <entry><literal>UTF8</literal></entry>
2836 <entry><literal>LATIN1</literal></entry>
2840 <entry><literal>utf8_to_iso_8859_10</literal></entry>
2841 <entry><literal>UTF8</literal></entry>
2842 <entry><literal>LATIN6</literal></entry>
2846 <entry><literal>utf8_to_iso_8859_13</literal></entry>
2847 <entry><literal>UTF8</literal></entry>
2848 <entry><literal>LATIN7</literal></entry>
2852 <entry><literal>utf8_to_iso_8859_14</literal></entry>
2853 <entry><literal>UTF8</literal></entry>
2854 <entry><literal>LATIN8</literal></entry>
2858 <entry><literal>utf8_to_iso_8859_15</literal></entry>
2859 <entry><literal>UTF8</literal></entry>
2860 <entry><literal>LATIN9</literal></entry>
2864 <entry><literal>utf8_to_iso_8859_16</literal></entry>
2865 <entry><literal>UTF8</literal></entry>
2866 <entry><literal>LATIN10</literal></entry>
2870 <entry><literal>utf8_to_iso_8859_2</literal></entry>
2871 <entry><literal>UTF8</literal></entry>
2872 <entry><literal>LATIN2</literal></entry>
2876 <entry><literal>utf8_to_iso_8859_3</literal></entry>
2877 <entry><literal>UTF8</literal></entry>
2878 <entry><literal>LATIN3</literal></entry>
2882 <entry><literal>utf8_to_iso_8859_4</literal></entry>
2883 <entry><literal>UTF8</literal></entry>
2884 <entry><literal>LATIN4</literal></entry>
2888 <entry><literal>utf8_to_iso_8859_5</literal></entry>
2889 <entry><literal>UTF8</literal></entry>
2890 <entry><literal>ISO_8859_5</literal></entry>
2894 <entry><literal>utf8_to_iso_8859_6</literal></entry>
2895 <entry><literal>UTF8</literal></entry>
2896 <entry><literal>ISO_8859_6</literal></entry>
2900 <entry><literal>utf8_to_iso_8859_7</literal></entry>
2901 <entry><literal>UTF8</literal></entry>
2902 <entry><literal>ISO_8859_7</literal></entry>
2906 <entry><literal>utf8_to_iso_8859_8</literal></entry>
2907 <entry><literal>UTF8</literal></entry>
2908 <entry><literal>ISO_8859_8</literal></entry>
2912 <entry><literal>utf8_to_iso_8859_9</literal></entry>
2913 <entry><literal>UTF8</literal></entry>
2914 <entry><literal>LATIN5</literal></entry>
2918 <entry><literal>utf8_to_johab</literal></entry>
2919 <entry><literal>UTF8</literal></entry>
2920 <entry><literal>JOHAB</literal></entry>
2924 <entry><literal>utf8_to_koi8_r</literal></entry>
2925 <entry><literal>UTF8</literal></entry>
2926 <entry><literal>KOI8R</literal></entry>
2930 <entry><literal>utf8_to_koi8_u</literal></entry>
2931 <entry><literal>UTF8</literal></entry>
2932 <entry><literal>KOI8U</literal></entry>
2936 <entry><literal>utf8_to_sjis</literal></entry>
2937 <entry><literal>UTF8</literal></entry>
2938 <entry><literal>SJIS</literal></entry>
2942 <entry><literal>utf8_to_tcvn</literal></entry>
2943 <entry><literal>UTF8</literal></entry>
2944 <entry><literal>WIN1258</literal></entry>
2948 <entry><literal>utf8_to_uhc</literal></entry>
2949 <entry><literal>UTF8</literal></entry>
2950 <entry><literal>UHC</literal></entry>
2954 <entry><literal>utf8_to_windows_1250</literal></entry>
2955 <entry><literal>UTF8</literal></entry>
2956 <entry><literal>WIN1250</literal></entry>
2960 <entry><literal>utf8_to_windows_1251</literal></entry>
2961 <entry><literal>UTF8</literal></entry>
2962 <entry><literal>WIN1251</literal></entry>
2966 <entry><literal>utf8_to_windows_1252</literal></entry>
2967 <entry><literal>UTF8</literal></entry>
2968 <entry><literal>WIN1252</literal></entry>
2972 <entry><literal>utf8_to_windows_1253</literal></entry>
2973 <entry><literal>UTF8</literal></entry>
2974 <entry><literal>WIN1253</literal></entry>
2978 <entry><literal>utf8_to_windows_1254</literal></entry>
2979 <entry><literal>UTF8</literal></entry>
2980 <entry><literal>WIN1254</literal></entry>
2984 <entry><literal>utf8_to_windows_1255</literal></entry>
2985 <entry><literal>UTF8</literal></entry>
2986 <entry><literal>WIN1255</literal></entry>
2990 <entry><literal>utf8_to_windows_1256</literal></entry>
2991 <entry><literal>UTF8</literal></entry>
2992 <entry><literal>WIN1256</literal></entry>
2996 <entry><literal>utf8_to_windows_1257</literal></entry>
2997 <entry><literal>UTF8</literal></entry>
2998 <entry><literal>WIN1257</literal></entry>
3002 <entry><literal>utf8_to_windows_866</literal></entry>
3003 <entry><literal>UTF8</literal></entry>
3004 <entry><literal>WIN866</literal></entry>
3008 <entry><literal>utf8_to_windows_874</literal></entry>
3009 <entry><literal>UTF8</literal></entry>
3010 <entry><literal>WIN874</literal></entry>
3014 <entry><literal>windows_1250_to_iso_8859_2</literal></entry>
3015 <entry><literal>WIN1250</literal></entry>
3016 <entry><literal>LATIN2</literal></entry>
3020 <entry><literal>windows_1250_to_mic</literal></entry>
3021 <entry><literal>WIN1250</literal></entry>
3022 <entry><literal>MULE_INTERNAL</literal></entry>
3026 <entry><literal>windows_1250_to_utf8</literal></entry>
3027 <entry><literal>WIN1250</literal></entry>
3028 <entry><literal>UTF8</literal></entry>
3032 <entry><literal>windows_1251_to_iso_8859_5</literal></entry>
3033 <entry><literal>WIN1251</literal></entry>
3034 <entry><literal>ISO_8859_5</literal></entry>
3038 <entry><literal>windows_1251_to_koi8_r</literal></entry>
3039 <entry><literal>WIN1251</literal></entry>
3040 <entry><literal>KOI8R</literal></entry>
3044 <entry><literal>windows_1251_to_mic</literal></entry>
3045 <entry><literal>WIN1251</literal></entry>
3046 <entry><literal>MULE_INTERNAL</literal></entry>
3050 <entry><literal>windows_1251_to_utf8</literal></entry>
3051 <entry><literal>WIN1251</literal></entry>
3052 <entry><literal>UTF8</literal></entry>
3056 <entry><literal>windows_1251_to_windows_866</literal></entry>
3057 <entry><literal>WIN1251</literal></entry>
3058 <entry><literal>WIN866</literal></entry>
3062 <entry><literal>windows_1252_to_utf8</literal></entry>
3063 <entry><literal>WIN1252</literal></entry>
3064 <entry><literal>UTF8</literal></entry>
3068 <entry><literal>windows_1256_to_utf8</literal></entry>
3069 <entry><literal>WIN1256</literal></entry>
3070 <entry><literal>UTF8</literal></entry>
3074 <entry><literal>windows_866_to_iso_8859_5</literal></entry>
3075 <entry><literal>WIN866</literal></entry>
3076 <entry><literal>ISO_8859_5</literal></entry>
3080 <entry><literal>windows_866_to_koi8_r</literal></entry>
3081 <entry><literal>WIN866</literal></entry>
3082 <entry><literal>KOI8R</literal></entry>
3086 <entry><literal>windows_866_to_mic</literal></entry>
3087 <entry><literal>WIN866</literal></entry>
3088 <entry><literal>MULE_INTERNAL</literal></entry>
3092 <entry><literal>windows_866_to_utf8</literal></entry>
3093 <entry><literal>WIN866</literal></entry>
3094 <entry><literal>UTF8</literal></entry>
3098 <entry><literal>windows_866_to_windows_1251</literal></entry>
3099 <entry><literal>WIN866</literal></entry>
3100 <entry><literal>WIN</literal></entry>
3104 <entry><literal>windows_874_to_utf8</literal></entry>
3105 <entry><literal>WIN874</literal></entry>
3106 <entry><literal>UTF8</literal></entry>
3110 <entry><literal>euc_jis_2004_to_utf8</literal></entry>
3111 <entry><literal>EUC_JIS_2004</literal></entry>
3112 <entry><literal>UTF8</literal></entry>
3116 <entry><literal>utf8_to_euc_jis_2004</literal></entry>
3117 <entry><literal>UTF8</literal></entry>
3118 <entry><literal>EUC_JIS_2004</literal></entry>
3122 <entry><literal>shift_jis_2004_to_utf8</literal></entry>
3123 <entry><literal>SHIFT_JIS_2004</literal></entry>
3124 <entry><literal>UTF8</literal></entry>
3128 <entry><literal>utf8_to_shift_jis_2004</literal></entry>
3129 <entry><literal>UTF8</literal></entry>
3130 <entry><literal>SHIFT_JIS_2004</literal></entry>
3134 <entry><literal>euc_jis_2004_to_shift_jis_2004</literal></entry>
3135 <entry><literal>EUC_JIS_2004</literal></entry>
3136 <entry><literal>SHIFT_JIS_2004</literal></entry>
3140 <entry><literal>shift_jis_2004_to_euc_jis_2004</literal></entry>
3141 <entry><literal>SHIFT_JIS_2004</literal></entry>
3142 <entry><literal>EUC_JIS_2004</literal></entry>
3149 <sect2 id="functions-string-format">
3150 <title><function>format</function></title>
3153 <primary>format</primary>
3157 The function <function>format</> produces output formatted according to
3158 a format string, in a style similar to the C function
3159 <function>sprintf</>.
3164 <function>format</>(<parameter>formatstr</> <type>text</> [, <parameter>formatarg</> <type>"any"</> [, ...] ])
3166 <replaceable>formatstr</> is a format string that specifies how the
3167 result should be formatted. Text in the format string is copied
3168 directly to the result, except where <firstterm>format specifiers</> are
3169 used. Format specifiers act as placeholders in the string, defining how
3170 subsequent function arguments should be formatted and inserted into the
3171 result. Each <replaceable>formatarg</> argument is converted to text
3172 according to the usual output rules for its data type, and then formatted
3173 and inserted into the result string according to the format specifier(s).
3177 Format specifiers are introduced by a <literal>%</> character and have
3180 %[<replaceable>position</>][<replaceable>flags</>][<replaceable>width</>]<replaceable>type</>
3182 where the component fields are:
3186 <term><replaceable>position</replaceable> (optional)</term>
3189 A string of the form <literal><replaceable>n</>$</> where
3190 <replaceable>n</> is the index of the argument to print.
3191 Index 1 means the first argument after
3192 <replaceable>formatstr</>. If the <replaceable>position</> is
3193 omitted, the default is to use the next argument in sequence.
3199 <term><replaceable>flags</replaceable> (optional)</term>
3202 Additional options controlling how the format specifier's output is
3203 formatted. Currently the only supported flag is a minus sign
3204 (<literal>-</>) which will cause the format specifier's output to be
3205 left-justified. This has no effect unless the <replaceable>width</>
3206 field is also specified.
3212 <term><replaceable>width</replaceable> (optional)</term>
3215 Specifies the <emphasis>minimum</> number of characters to use to
3216 display the format specifier's output. The output is padded on the
3217 left or right (depending on the <literal>-</> flag) with spaces as
3218 needed to fill the width. A too-small width does not cause
3219 truncation of the output, but is simply ignored. The width may be
3220 specified using any of the following: a positive integer; an
3221 asterisk (<literal>*</>) to use the next function argument as the
3222 width; or a string of the form <literal>*<replaceable>n</>$</> to
3223 use the <replaceable>n</>th function argument as the width.
3227 If the width comes from a function argument, that argument is
3228 consumed before the argument that is used for the format specifier's
3229 value. If the width argument is negative, the result is left
3230 aligned (as if the <literal>-</> flag had been specified) within a
3231 field of length <function>abs</>(<replaceable>width</replaceable>).
3237 <term><replaceable>type</replaceable> (required)</term>
3240 The type of format conversion to use to produce the format
3241 specifier's output. The following types are supported:
3245 <literal>s</literal> formats the argument value as a simple
3246 string. A null value is treated as an empty string.
3251 <literal>I</literal> treats the argument value as an SQL
3252 identifier, double-quoting it if necessary.
3253 It is an error for the value to be null (equivalent to
3254 <function>quote_ident</>).
3259 <literal>L</literal> quotes the argument value as an SQL literal.
3260 A null value is displayed as the string <literal>NULL</>, without
3261 quotes (equivalent to <function>quote_nullable</function>).
3272 In addition to the format specifiers described above, the special sequence
3273 <literal>%%</> may be used to output a literal <literal>%</> character.
3277 Here are some examples of the basic format conversions:
3280 SELECT format('Hello %s', 'World');
3281 <lineannotation>Result: </lineannotation><computeroutput>Hello World</computeroutput>
3283 SELECT format('Testing %s, %s, %s, %%', 'one', 'two', 'three');
3284 <lineannotation>Result: </><computeroutput>Testing one, two, three, %</>
3286 SELECT format('INSERT INTO %I VALUES(%L)', 'Foo bar', E'O\'Reilly');
3287 <lineannotation>Result: </lineannotation><computeroutput>INSERT INTO "Foo bar" VALUES('O''Reilly')</computeroutput>
3289 SELECT format('INSERT INTO %I VALUES(%L)', 'locations', E'C:\\Program Files');
3290 <lineannotation>Result: </lineannotation><computeroutput>INSERT INTO locations VALUES(E'C:\\Program Files')</computeroutput>
3295 Here are examples using <replaceable>width</replaceable> fields
3296 and the <literal>-</> flag:
3299 SELECT format('|%10s|', 'foo');
3300 <lineannotation>Result: </><computeroutput>| foo|</>
3302 SELECT format('|%-10s|', 'foo');
3303 <lineannotation>Result: </><computeroutput>|foo |</>
3305 SELECT format('|%*s|', 10, 'foo');
3306 <lineannotation>Result: </><computeroutput>| foo|</>
3308 SELECT format('|%*s|', -10, 'foo');
3309 <lineannotation>Result: </><computeroutput>|foo |</>
3311 SELECT format('|%-*s|', 10, 'foo');
3312 <lineannotation>Result: </><computeroutput>|foo |</>
3314 SELECT format('|%-*s|', -10, 'foo');
3315 <lineannotation>Result: </><computeroutput>|foo |</>
3320 These examples show use of <replaceable>position</> fields:
3323 SELECT format('Testing %3$s, %2$s, %1$s', 'one', 'two', 'three');
3324 <lineannotation>Result: </><computeroutput>Testing three, two, one</>
3326 SELECT format('|%*2$s|', 'foo', 10, 'bar');
3327 <lineannotation>Result: </><computeroutput>| bar|</>
3329 SELECT format('|%1$*2$s|', 'foo', 10, 'bar');
3330 <lineannotation>Result: </><computeroutput>| foo|</>
3335 Unlike the standard C function <function>sprintf</>,
3336 <productname>PostgreSQL</>'s <function>format</> function allows format
3337 specifiers with and without <replaceable>position</> fields to be mixed
3338 in the same format string. A format specifier without a
3339 <replaceable>position</> field always uses the next argument after the
3340 last argument consumed.
3341 In addition, the <function>format</> function does not require all
3342 function arguments to be used in the format string.
3346 SELECT format('Testing %3$s, %2$s, %s', 'one', 'two', 'three');
3347 <lineannotation>Result: </><computeroutput>Testing three, two, three</>
3352 The <literal>%I</> and <literal>%L</> format specifiers are particularly
3353 useful for safely constructing dynamic SQL statements. See
3354 <xref linkend="plpgsql-quote-literal-example">.
3361 <sect1 id="functions-binarystring">
3362 <title>Binary String Functions and Operators</title>
3364 <indexterm zone="functions-binarystring">
3365 <primary>binary data</primary>
3366 <secondary>functions</secondary>
3370 This section describes functions and operators for examining and
3371 manipulating values of type <type>bytea</type>.
3375 <acronym>SQL</acronym> defines some string functions that use
3376 key words, rather than commas, to separate
3377 arguments. Details are in
3378 <xref linkend="functions-binarystring-sql">.
3379 <productname>PostgreSQL</> also provides versions of these functions
3380 that use the regular function invocation syntax
3381 (see <xref linkend="functions-binarystring-other">).
3386 The sample results shown on this page assume that the server parameter
3387 <link linkend="guc-bytea-output"><varname>bytea_output</></link> is set
3388 to <literal>escape</literal> (the traditional PostgreSQL format).
3392 <table id="functions-binarystring-sql">
3393 <title><acronym>SQL</acronym> Binary String Functions and Operators</title>
3397 <entry>Function</entry>
3398 <entry>Return Type</entry>
3399 <entry>Description</entry>
3400 <entry>Example</entry>
3401 <entry>Result</entry>
3407 <entry><literal><parameter>string</parameter> <literal>||</literal>
3408 <parameter>string</parameter></literal></entry>
3409 <entry> <type>bytea</type> </entry>
3411 String concatenation
3413 <primary>binary string</primary>
3414 <secondary>concatenation</secondary>
3417 <entry><literal>E'\\\\Post'::bytea || E'\\047gres\\000'::bytea</literal></entry>
3418 <entry><literal>\\Post'gres\000</literal></entry>
3424 <primary>octet_length</primary>
3426 <literal><function>octet_length(<parameter>string</parameter>)</function></literal>
3428 <entry><type>int</type></entry>
3429 <entry>Number of bytes in binary string</entry>
3430 <entry><literal>octet_length(E'jo\\000se'::bytea)</literal></entry>
3431 <entry><literal>5</literal></entry>
3437 <primary>overlay</primary>
3439 <literal><function>overlay(<parameter>string</parameter> placing <parameter>string</parameter> from <type>int</type> <optional>for <type>int</type></optional>)</function></literal>
3441 <entry><type>bytea</type></entry>
3445 <entry><literal>overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 2 for 3)</literal></entry>
3446 <entry><literal>T\\002\\003mas</literal></entry>
3452 <primary>position</primary>
3454 <literal><function>position(<parameter>substring</parameter> in <parameter>string</parameter>)</function></literal>
3456 <entry><type>int</type></entry>
3457 <entry>Location of specified substring</entry>
3458 <entry><literal>position(E'\\000om'::bytea in E'Th\\000omas'::bytea)</literal></entry>
3459 <entry><literal>3</literal></entry>
3465 <primary>substring</primary>
3467 <literal><function>substring(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</function></literal>
3469 <entry><type>bytea</type></entry>
3473 <entry><literal>substring(E'Th\\000omas'::bytea from 2 for 3)</literal></entry>
3474 <entry><literal>h\000o</literal></entry>
3480 <primary>trim</primary>
3482 <literal><function>trim(<optional>both</optional>
3483 <parameter>bytes</parameter> from
3484 <parameter>string</parameter>)</function></literal>
3486 <entry><type>bytea</type></entry>
3488 Remove the longest string containing only bytes appearing in
3489 <parameter>bytes</parameter> from the start
3490 and end of <parameter>string</parameter>
3492 <entry><literal>trim(E'\\000\\001'::bytea from E'\\000Tom\\001'::bytea)</literal></entry>
3493 <entry><literal>Tom</literal></entry>
3500 Additional binary string manipulation functions are available and
3501 are listed in <xref linkend="functions-binarystring-other">. Some
3502 of them are used internally to implement the
3503 <acronym>SQL</acronym>-standard string functions listed in <xref
3504 linkend="functions-binarystring-sql">.
3507 <table id="functions-binarystring-other">
3508 <title>Other Binary String Functions</title>
3512 <entry>Function</entry>
3513 <entry>Return Type</entry>
3514 <entry>Description</entry>
3515 <entry>Example</entry>
3516 <entry>Result</entry>
3524 <primary>btrim</primary>
3526 <literal><function>btrim(<parameter>string</parameter>
3527 <type>bytea</type>, <parameter>bytes</parameter> <type>bytea</type>)</function></literal>
3529 <entry><type>bytea</type></entry>
3531 Remove the longest string containing only bytes appearing in
3532 <parameter>bytes</parameter> from the start and end of
3533 <parameter>string</parameter>
3535 <entry><literal>btrim(E'\\000trim\\001'::bytea, E'\\000\\001'::bytea)</literal></entry>
3536 <entry><literal>trim</literal></entry>
3542 <primary>decode</primary>
3544 <literal><function>decode(<parameter>string</parameter> <type>text</type>,
3545 <parameter>format</parameter> <type>text</type>)</function></literal>
3547 <entry><type>bytea</type></entry>
3549 Decode binary data from textual representation in <parameter>string</>.
3550 Options for <parameter>format</> are same as in <function>encode</>.
3552 <entry><literal>decode(E'123\\000456', 'escape')</literal></entry>
3553 <entry><literal>123\000456</literal></entry>
3559 <primary>encode</primary>
3561 <literal><function>encode(<parameter>data</parameter> <type>bytea</type>,
3562 <parameter>format</parameter> <type>text</type>)</function></literal>
3564 <entry><type>text</type></entry>
3566 Encode binary data into a textual representation. Supported
3567 formats are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
3568 <literal>escape</> converts zero bytes and high-bit-set bytes to
3569 octal sequences (<literal>\</><replaceable>nnn</>) and
3570 doubles backslashes.
3572 <entry><literal>encode(E'123\\000456'::bytea, 'escape')</literal></entry>
3573 <entry><literal>123\000456</literal></entry>
3579 <primary>get_bit</primary>
3581 <literal><function>get_bit(<parameter>string</parameter>, <parameter>offset</parameter>)</function></literal>
3583 <entry><type>int</type></entry>
3585 Extract bit from string
3587 <entry><literal>get_bit(E'Th\\000omas'::bytea, 45)</literal></entry>
3588 <entry><literal>1</literal></entry>
3594 <primary>get_byte</primary>
3596 <literal><function>get_byte(<parameter>string</parameter>, <parameter>offset</parameter>)</function></literal>
3598 <entry><type>int</type></entry>
3600 Extract byte from string
3602 <entry><literal>get_byte(E'Th\\000omas'::bytea, 4)</literal></entry>
3603 <entry><literal>109</literal></entry>
3609 <primary>length</primary>
3611 <literal><function>length(<parameter>string</parameter>)</function></literal>
3613 <entry><type>int</type></entry>
3615 Length of binary string
3617 <primary>binary string</primary>
3618 <secondary>length</secondary>
3621 <primary>length</primary>
3622 <secondary sortas="binary string">of a binary string</secondary>
3623 <see>binary strings, length</see>
3626 <entry><literal>length(E'jo\\000se'::bytea)</literal></entry>
3627 <entry><literal>5</literal></entry>
3633 <primary>md5</primary>
3635 <literal><function>md5(<parameter>string</parameter>)</function></literal>
3637 <entry><type>text</type></entry>
3639 Calculates the MD5 hash of <parameter>string</parameter>,
3640 returning the result in hexadecimal
3642 <entry><literal>md5(E'Th\\000omas'::bytea)</literal></entry>
3643 <entry><literal>8ab2d3c9689aaf18 b4958c334c82d8b1</literal></entry>
3649 <primary>set_bit</primary>
3651 <literal><function>set_bit(<parameter>string</parameter>,
3652 <parameter>offset</parameter>, <parameter>newvalue</>)</function></literal>
3654 <entry><type>bytea</type></entry>
3658 <entry><literal>set_bit(E'Th\\000omas'::bytea, 45, 0)</literal></entry>
3659 <entry><literal>Th\000omAs</literal></entry>
3665 <primary>set_byte</primary>
3667 <literal><function>set_byte(<parameter>string</parameter>,
3668 <parameter>offset</parameter>, <parameter>newvalue</>)</function></literal>
3670 <entry><type>bytea</type></entry>
3674 <entry><literal>set_byte(E'Th\\000omas'::bytea, 4, 64)</literal></entry>
3675 <entry><literal>Th\000o@as</literal></entry>
3682 <function>get_byte</> and <function>set_byte</> number the first byte
3683 of a binary string as byte 0.
3684 <function>get_bit</> and <function>set_bit</> number bits from the
3685 right within each byte; for example bit 0 is the least significant bit of
3686 the first byte, and bit 15 is the most significant bit of the second byte.
3690 See also the aggregate function <function>string_agg</function> in
3691 <xref linkend="functions-aggregate"> and the large object functions
3692 in <xref linkend="lo-funcs">.
3697 <sect1 id="functions-bitstring">
3698 <title>Bit String Functions and Operators</title>
3700 <indexterm zone="functions-bitstring">
3701 <primary>bit strings</primary>
3702 <secondary>functions</secondary>
3706 This section describes functions and operators for examining and
3707 manipulating bit strings, that is values of the types
3708 <type>bit</type> and <type>bit varying</type>. Aside from the
3709 usual comparison operators, the operators
3710 shown in <xref linkend="functions-bit-string-op-table"> can be used.
3711 Bit string operands of <literal>&</literal>, <literal>|</literal>,
3712 and <literal>#</literal> must be of equal length. When bit
3713 shifting, the original length of the string is preserved, as shown
3717 <table id="functions-bit-string-op-table">
3718 <title>Bit String Operators</title>
3723 <entry>Operator</entry>
3724 <entry>Description</entry>
3725 <entry>Example</entry>
3726 <entry>Result</entry>
3732 <entry> <literal>||</literal> </entry>
3733 <entry>concatenation</entry>
3734 <entry><literal>B'10001' || B'011'</literal></entry>
3735 <entry><literal>10001011</literal></entry>
3739 <entry> <literal>&</literal> </entry>
3740 <entry>bitwise AND</entry>
3741 <entry><literal>B'10001' & B'01101'</literal></entry>
3742 <entry><literal>00001</literal></entry>
3746 <entry> <literal>|</literal> </entry>
3747 <entry>bitwise OR</entry>
3748 <entry><literal>B'10001' | B'01101'</literal></entry>
3749 <entry><literal>11101</literal></entry>
3753 <entry> <literal>#</literal> </entry>
3754 <entry>bitwise XOR</entry>
3755 <entry><literal>B'10001' # B'01101'</literal></entry>
3756 <entry><literal>11100</literal></entry>
3760 <entry> <literal>~</literal> </entry>
3761 <entry>bitwise NOT</entry>
3762 <entry><literal>~ B'10001'</literal></entry>
3763 <entry><literal>01110</literal></entry>
3767 <entry> <literal><<</literal> </entry>
3768 <entry>bitwise shift left</entry>
3769 <entry><literal>B'10001' << 3</literal></entry>
3770 <entry><literal>01000</literal></entry>
3774 <entry> <literal>>></literal> </entry>
3775 <entry>bitwise shift right</entry>
3776 <entry><literal>B'10001' >> 2</literal></entry>
3777 <entry><literal>00100</literal></entry>
3784 The following <acronym>SQL</acronym>-standard functions work on bit
3785 strings as well as character strings:
3786 <literal><function>length</function></literal>,
3787 <literal><function>bit_length</function></literal>,
3788 <literal><function>octet_length</function></literal>,
3789 <literal><function>position</function></literal>,
3790 <literal><function>substring</function></literal>,
3791 <literal><function>overlay</function></literal>.
3795 The following functions work on bit strings as well as binary
3797 <literal><function>get_bit</function></literal>,
3798 <literal><function>set_bit</function></literal>.
3799 When working with a bit string, these functions number the first
3800 (leftmost) bit of the string as bit 0.
3804 In addition, it is possible to cast integral values to and from type
3808 44::bit(10) <lineannotation>0000101100</lineannotation>
3809 44::bit(3) <lineannotation>100</lineannotation>
3810 cast(-44 as bit(12)) <lineannotation>111111010100</lineannotation>
3811 '1110'::bit(4)::integer <lineannotation>14</lineannotation>
3813 Note that casting to just <quote>bit</> means casting to
3814 <literal>bit(1)</>, and so will deliver only the least significant
3820 Casting an integer to <type>bit(n)</> copies the rightmost
3821 <literal>n</> bits. Casting an integer to a bit string width wider
3822 than the integer itself will sign-extend on the left.
3829 <sect1 id="functions-matching">
3830 <title>Pattern Matching</title>
3832 <indexterm zone="functions-matching">
3833 <primary>pattern matching</primary>
3837 There are three separate approaches to pattern matching provided
3838 by <productname>PostgreSQL</productname>: the traditional
3839 <acronym>SQL</acronym> <function>LIKE</function> operator, the
3840 more recent <function>SIMILAR TO</function> operator (added in
3841 SQL:1999), and <acronym>POSIX</acronym>-style regular
3842 expressions. Aside from the basic <quote>does this string match
3843 this pattern?</> operators, functions are available to extract
3844 or replace matching substrings and to split a string at matching
3850 If you have pattern matching needs that go beyond this,
3851 consider writing a user-defined function in Perl or Tcl.
3857 While most regular-expression searches can be executed very quickly,
3858 regular expressions can be contrived that take arbitrary amounts of
3859 time and memory to process. Be wary of accepting regular-expression
3860 search patterns from hostile sources. If you must do so, it is
3861 advisable to impose a statement timeout.
3865 Searches using <function>SIMILAR TO</function> patterns have the same
3866 security hazards, since <function>SIMILAR TO</function> provides many
3867 of the same capabilities as <acronym>POSIX</acronym>-style regular
3872 <function>LIKE</function> searches, being much simpler than the other
3873 two options, are safer to use with possibly-hostile pattern sources.
3877 <sect2 id="functions-like">
3878 <title><function>LIKE</function></title>
3881 <primary>LIKE</primary>
3885 <replaceable>string</replaceable> LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3886 <replaceable>string</replaceable> NOT LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3890 The <function>LIKE</function> expression returns true if the
3891 <replaceable>string</replaceable> matches the supplied
3892 <replaceable>pattern</replaceable>. (As
3893 expected, the <function>NOT LIKE</function> expression returns
3894 false if <function>LIKE</function> returns true, and vice versa.
3895 An equivalent expression is
3896 <literal>NOT (<replaceable>string</replaceable> LIKE
3897 <replaceable>pattern</replaceable>)</literal>.)
3901 If <replaceable>pattern</replaceable> does not contain percent
3902 signs or underscores, then the pattern only represents the string
3903 itself; in that case <function>LIKE</function> acts like the
3904 equals operator. An underscore (<literal>_</literal>) in
3905 <replaceable>pattern</replaceable> stands for (matches) any single
3906 character; a percent sign (<literal>%</literal>) matches any sequence
3907 of zero or more characters.
3913 'abc' LIKE 'abc' <lineannotation>true</lineannotation>
3914 'abc' LIKE 'a%' <lineannotation>true</lineannotation>
3915 'abc' LIKE '_b_' <lineannotation>true</lineannotation>
3916 'abc' LIKE 'c' <lineannotation>false</lineannotation>
3921 <function>LIKE</function> pattern matching always covers the entire
3922 string. Therefore, if it's desired to match a sequence anywhere within
3923 a string, the pattern must start and end with a percent sign.
3927 To match a literal underscore or percent sign without matching
3928 other characters, the respective character in
3929 <replaceable>pattern</replaceable> must be
3930 preceded by the escape character. The default escape
3931 character is the backslash but a different one can be selected by
3932 using the <literal>ESCAPE</literal> clause. To match the escape
3933 character itself, write two escape characters.
3938 If you have <xref linkend="guc-standard-conforming-strings"> turned off,
3939 any backslashes you write in literal string constants will need to be
3940 doubled. See <xref linkend="sql-syntax-strings"> for more information.
3945 It's also possible to select no escape character by writing
3946 <literal>ESCAPE ''</literal>. This effectively disables the
3947 escape mechanism, which makes it impossible to turn off the
3948 special meaning of underscore and percent signs in the pattern.
3952 The key word <token>ILIKE</token> can be used instead of
3953 <token>LIKE</token> to make the match case-insensitive according
3954 to the active locale. This is not in the <acronym>SQL</acronym> standard but is a
3955 <productname>PostgreSQL</productname> extension.
3959 The operator <literal>~~</literal> is equivalent to
3960 <function>LIKE</function>, and <literal>~~*</literal> corresponds to
3961 <function>ILIKE</function>. There are also
3962 <literal>!~~</literal> and <literal>!~~*</literal> operators that
3963 represent <function>NOT LIKE</function> and <function>NOT
3964 ILIKE</function>, respectively. All of these operators are
3965 <productname>PostgreSQL</productname>-specific.
3970 <sect2 id="functions-similarto-regexp">
3971 <title><function>SIMILAR TO</function> Regular Expressions</title>
3974 <primary>regular expression</primary>
3975 <!-- <seealso>pattern matching</seealso> breaks index build -->
3979 <primary>SIMILAR TO</primary>
3982 <primary>substring</primary>
3986 <replaceable>string</replaceable> SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3987 <replaceable>string</replaceable> NOT SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3991 The <function>SIMILAR TO</function> operator returns true or
3992 false depending on whether its pattern matches the given string.
3993 It is similar to <function>LIKE</function>, except that it
3994 interprets the pattern using the SQL standard's definition of a
3995 regular expression. SQL regular expressions are a curious cross
3996 between <function>LIKE</function> notation and common regular
3997 expression notation.
4001 Like <function>LIKE</function>, the <function>SIMILAR TO</function>
4002 operator succeeds only if its pattern matches the entire string;
4003 this is unlike common regular expression behavior where the pattern
4004 can match any part of the string.
4006 <function>LIKE</function>, <function>SIMILAR TO</function> uses
4007 <literal>_</> and <literal>%</> as wildcard characters denoting
4008 any single character and any string, respectively (these are
4009 comparable to <literal>.</> and <literal>.*</> in POSIX regular
4014 In addition to these facilities borrowed from <function>LIKE</function>,
4015 <function>SIMILAR TO</function> supports these pattern-matching
4016 metacharacters borrowed from POSIX regular expressions:
4021 <literal>|</literal> denotes alternation (either of two alternatives).
4026 <literal>*</literal> denotes repetition of the previous item zero
4032 <literal>+</literal> denotes repetition of the previous item one
4038 <literal>?</literal> denotes repetition of the previous item zero
4044 <literal>{</><replaceable>m</><literal>}</literal> denotes repetition
4045 of the previous item exactly <replaceable>m</> times.
4050 <literal>{</><replaceable>m</><literal>,}</literal> denotes repetition
4051 of the previous item <replaceable>m</> or more times.
4056 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</>
4057 denotes repetition of the previous item at least <replaceable>m</> and
4058 not more than <replaceable>n</> times.
4063 Parentheses <literal>()</literal> can be used to group items into
4064 a single logical item.
4069 A bracket expression <literal>[...]</literal> specifies a character
4070 class, just as in POSIX regular expressions.
4075 Notice that the period (<literal>.</>) is not a metacharacter
4076 for <function>SIMILAR TO</>.
4080 As with <function>LIKE</>, a backslash disables the special meaning
4081 of any of these metacharacters; or a different escape character can
4082 be specified with <literal>ESCAPE</>.
4088 'abc' SIMILAR TO 'abc' <lineannotation>true</lineannotation>
4089 'abc' SIMILAR TO 'a' <lineannotation>false</lineannotation>
4090 'abc' SIMILAR TO '%(b|d)%' <lineannotation>true</lineannotation>
4091 'abc' SIMILAR TO '(b|c)%' <lineannotation>false</lineannotation>
4096 The <function>substring</> function with three parameters,
4097 <function>substring(<replaceable>string</replaceable> from
4098 <replaceable>pattern</replaceable> for
4099 <replaceable>escape-character</replaceable>)</function>, provides
4100 extraction of a substring that matches an SQL
4101 regular expression pattern. As with <literal>SIMILAR TO</>, the
4102 specified pattern must match the entire data string, or else the
4103 function fails and returns null. To indicate the part of the
4104 pattern that should be returned on success, the pattern must contain
4105 two occurrences of the escape character followed by a double quote
4106 (<literal>"</>). <!-- " font-lock sanity -->
4107 The text matching the portion of the pattern
4108 between these markers is returned.
4112 Some examples, with <literal>#"</> delimiting the return string:
4114 substring('foobar' from '%#"o_b#"%' for '#') <lineannotation>oob</lineannotation>
4115 substring('foobar' from '#"o_b#"%' for '#') <lineannotation>NULL</lineannotation>
4120 <sect2 id="functions-posix-regexp">
4121 <title><acronym>POSIX</acronym> Regular Expressions</title>
4123 <indexterm zone="functions-posix-regexp">
4124 <primary>regular expression</primary>
4125 <seealso>pattern matching</seealso>
4128 <primary>substring</primary>
4131 <primary>regexp_replace</primary>
4134 <primary>regexp_match</primary>
4137 <primary>regexp_matches</primary>
4140 <primary>regexp_split_to_table</primary>
4143 <primary>regexp_split_to_array</primary>
4147 <xref linkend="functions-posix-table"> lists the available
4148 operators for pattern matching using POSIX regular expressions.
4151 <table id="functions-posix-table">
4152 <title>Regular Expression Match Operators</title>
4157 <entry>Operator</entry>
4158 <entry>Description</entry>
4159 <entry>Example</entry>
4165 <entry> <literal>~</literal> </entry>
4166 <entry>Matches regular expression, case sensitive</entry>
4167 <entry><literal>'thomas' ~ '.*thomas.*'</literal></entry>
4171 <entry> <literal>~*</literal> </entry>
4172 <entry>Matches regular expression, case insensitive</entry>
4173 <entry><literal>'thomas' ~* '.*Thomas.*'</literal></entry>
4177 <entry> <literal>!~</literal> </entry>
4178 <entry>Does not match regular expression, case sensitive</entry>
4179 <entry><literal>'thomas' !~ '.*Thomas.*'</literal></entry>
4183 <entry> <literal>!~*</literal> </entry>
4184 <entry>Does not match regular expression, case insensitive</entry>
4185 <entry><literal>'thomas' !~* '.*vadim.*'</literal></entry>
4192 <acronym>POSIX</acronym> regular expressions provide a more
4193 powerful means for pattern matching than the <function>LIKE</function> and
4194 <function>SIMILAR TO</> operators.
4195 Many Unix tools such as <command>egrep</command>,
4196 <command>sed</command>, or <command>awk</command> use a pattern
4197 matching language that is similar to the one described here.
4201 A regular expression is a character sequence that is an
4202 abbreviated definition of a set of strings (a <firstterm>regular
4203 set</firstterm>). A string is said to match a regular expression
4204 if it is a member of the regular set described by the regular
4205 expression. As with <function>LIKE</function>, pattern characters
4206 match string characters exactly unless they are special characters
4207 in the regular expression language — but regular expressions use
4208 different special characters than <function>LIKE</function> does.
4209 Unlike <function>LIKE</function> patterns, a
4210 regular expression is allowed to match anywhere within a string, unless
4211 the regular expression is explicitly anchored to the beginning or
4218 'abc' ~ 'abc' <lineannotation>true</lineannotation>
4219 'abc' ~ '^a' <lineannotation>true</lineannotation>
4220 'abc' ~ '(b|d)' <lineannotation>true</lineannotation>
4221 'abc' ~ '^(b|c)' <lineannotation>false</lineannotation>
4226 The <acronym>POSIX</acronym> pattern language is described in much
4227 greater detail below.
4231 The <function>substring</> function with two parameters,
4232 <function>substring(<replaceable>string</replaceable> from
4233 <replaceable>pattern</replaceable>)</function>, provides extraction of a
4235 that matches a POSIX regular expression pattern. It returns null if
4236 there is no match, otherwise the portion of the text that matched the
4237 pattern. But if the pattern contains any parentheses, the portion
4238 of the text that matched the first parenthesized subexpression (the
4239 one whose left parenthesis comes first) is
4240 returned. You can put parentheses around the whole expression
4241 if you want to use parentheses within it without triggering this
4242 exception. If you need parentheses in the pattern before the
4243 subexpression you want to extract, see the non-capturing parentheses
4250 substring('foobar' from 'o.b') <lineannotation>oob</lineannotation>
4251 substring('foobar' from 'o(.)b') <lineannotation>o</lineannotation>
4256 The <function>regexp_replace</> function provides substitution of
4257 new text for substrings that match POSIX regular expression patterns.
4259 <function>regexp_replace</function>(<replaceable>source</>,
4260 <replaceable>pattern</>, <replaceable>replacement</>
4261 <optional>, <replaceable>flags</> </optional>).
4262 The <replaceable>source</> string is returned unchanged if
4263 there is no match to the <replaceable>pattern</>. If there is a
4264 match, the <replaceable>source</> string is returned with the
4265 <replaceable>replacement</> string substituted for the matching
4266 substring. The <replaceable>replacement</> string can contain
4267 <literal>\</><replaceable>n</>, where <replaceable>n</> is 1
4268 through 9, to indicate that the source substring matching the
4269 <replaceable>n</>'th parenthesized subexpression of the pattern should be
4270 inserted, and it can contain <literal>\&</> to indicate that the
4271 substring matching the entire pattern should be inserted. Write
4272 <literal>\\</> if you need to put a literal backslash in the replacement
4274 The <replaceable>flags</> parameter is an optional text
4275 string containing zero or more single-letter flags that change the
4276 function's behavior. Flag <literal>i</> specifies case-insensitive
4277 matching, while flag <literal>g</> specifies replacement of each matching
4278 substring rather than only the first one. Supported flags (though
4279 not <literal>g</>) are
4280 described in <xref linkend="posix-embedded-options-table">.
4286 regexp_replace('foobarbaz', 'b..', 'X')
4287 <lineannotation>fooXbaz</lineannotation>
4288 regexp_replace('foobarbaz', 'b..', 'X', 'g')
4289 <lineannotation>fooXX</lineannotation>
4290 regexp_replace('foobarbaz', 'b(..)', E'X\\1Y', 'g')
4291 <lineannotation>fooXarYXazY</lineannotation>
4296 The <function>regexp_match</> function returns a text array of
4297 captured substring(s) resulting from the first match of a POSIX
4298 regular expression pattern to a string. It has the syntax
4299 <function>regexp_match</function>(<replaceable>string</>,
4300 <replaceable>pattern</> <optional>, <replaceable>flags</> </optional>).
4301 If there is no match, the result is <literal>NULL</>.
4302 If a match is found, and the <replaceable>pattern</> contains no
4303 parenthesized subexpressions, then the result is a single-element text
4304 array containing the substring matching the whole pattern.
4305 If a match is found, and the <replaceable>pattern</> contains
4306 parenthesized subexpressions, then the result is a text array
4307 whose <replaceable>n</>'th element is the substring matching
4308 the <replaceable>n</>'th parenthesized subexpression of
4309 the <replaceable>pattern</> (not counting <quote>non-capturing</>
4310 parentheses; see below for details).
4311 The <replaceable>flags</> parameter is an optional text string
4312 containing zero or more single-letter flags that change the function's
4313 behavior. Supported flags are described
4314 in <xref linkend="posix-embedded-options-table">.
4320 SELECT regexp_match('foobarbequebaz', 'bar.*que');
4326 SELECT regexp_match('foobarbequebaz', '(bar)(beque)');
4332 In the common case where you just want the whole matching substring
4333 or <literal>NULL</> for no match, write something like
4335 SELECT (regexp_match('foobarbequebaz', 'bar.*que'))[1];
4344 The <function>regexp_matches</> function returns a set of text arrays
4345 of captured substring(s) resulting from matching a POSIX regular
4346 expression pattern to a string. It has the same syntax as
4347 <function>regexp_match</function>.
4348 This function returns no rows if there is no match, one row if there is
4349 a match and the <literal>g</> flag is not given, or <replaceable>N</>
4350 rows if there are <replaceable>N</> matches and the <literal>g</> flag
4351 is given. Each returned row is a text array containing the whole
4352 matched substring or the substrings matching parenthesized
4353 subexpressions of the <replaceable>pattern</>, just as described above
4354 for <function>regexp_match</function>.
4355 <function>regexp_matches</> accepts all the flags shown
4356 in <xref linkend="posix-embedded-options-table">, plus
4357 the <literal>g</> flag which commands it to return all matches, not
4364 SELECT regexp_matches('foo', 'not there');
4369 SELECT regexp_matches('foobarbequebazilbarfbonk', '(b[^b]+)(b[^b]+)', 'g');
4380 In most cases <function>regexp_matches()</> should be used with
4381 the <literal>g</> flag, since if you only want the first match, it's
4382 easier and more efficient to use <function>regexp_match()</>.
4383 However, <function>regexp_match()</> only exists
4384 in <productname>PostgreSQL</> version 10 and up. When working in older
4385 versions, a common trick is to place a <function>regexp_matches()</>
4386 call in a sub-select, for example:
4388 SELECT col1, (SELECT regexp_matches(col2, '(bar)(beque)')) FROM tab;
4390 This produces a text array if there's a match, or <literal>NULL</> if
4391 not, the same as <function>regexp_match()</> would do. Without the
4392 sub-select, this query would produce no output at all for table rows
4393 without a match, which is typically not the desired behavior.
4398 The <function>regexp_split_to_table</> function splits a string using a POSIX
4399 regular expression pattern as a delimiter. It has the syntax
4400 <function>regexp_split_to_table</function>(<replaceable>string</>, <replaceable>pattern</>
4401 <optional>, <replaceable>flags</> </optional>).
4402 If there is no match to the <replaceable>pattern</>, the function returns the
4403 <replaceable>string</>. If there is at least one match, for each match it returns
4404 the text from the end of the last match (or the beginning of the string)
4405 to the beginning of the match. When there are no more matches, it
4406 returns the text from the end of the last match to the end of the string.
4407 The <replaceable>flags</> parameter is an optional text string containing
4408 zero or more single-letter flags that change the function's behavior.
4409 <function>regexp_split_to_table</function> supports the flags described in
4410 <xref linkend="posix-embedded-options-table">.
4414 The <function>regexp_split_to_array</> function behaves the same as
4415 <function>regexp_split_to_table</>, except that <function>regexp_split_to_array</>
4416 returns its result as an array of <type>text</>. It has the syntax
4417 <function>regexp_split_to_array</function>(<replaceable>string</>, <replaceable>pattern</>
4418 <optional>, <replaceable>flags</> </optional>).
4419 The parameters are the same as for <function>regexp_split_to_table</>.
4426 SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', E'\\s+') AS foo;
4440 SELECT regexp_split_to_array('the quick brown fox jumps over the lazy dog', E'\\s+');
4441 regexp_split_to_array
4442 -----------------------------------------------
4443 {the,quick,brown,fox,jumps,over,the,lazy,dog}
4446 SELECT foo FROM regexp_split_to_table('the quick brown fox', E'\\s*') AS foo;
4470 As the last example demonstrates, the regexp split functions ignore
4471 zero-length matches that occur at the start or end of the string
4472 or immediately after a previous match. This is contrary to the strict
4473 definition of regexp matching that is implemented by
4474 <function>regexp_match</> and
4475 <function>regexp_matches</>, but is usually the most convenient behavior
4476 in practice. Other software systems such as Perl use similar definitions.
4479 <!-- derived from the re_syntax.n man page -->
4481 <sect3 id="posix-syntax-details">
4482 <title>Regular Expression Details</title>
4485 <productname>PostgreSQL</productname>'s regular expressions are implemented
4486 using a software package written by Henry Spencer. Much of
4487 the description of regular expressions below is copied verbatim from his
4492 Regular expressions (<acronym>RE</acronym>s), as defined in
4493 <acronym>POSIX</acronym> 1003.2, come in two forms:
4494 <firstterm>extended</> <acronym>RE</acronym>s or <acronym>ERE</>s
4495 (roughly those of <command>egrep</command>), and
4496 <firstterm>basic</> <acronym>RE</acronym>s or <acronym>BRE</>s
4497 (roughly those of <command>ed</command>).
4498 <productname>PostgreSQL</productname> supports both forms, and
4499 also implements some extensions
4500 that are not in the POSIX standard, but have become widely used
4501 due to their availability in programming languages such as Perl and Tcl.
4502 <acronym>RE</acronym>s using these non-POSIX extensions are called
4503 <firstterm>advanced</> <acronym>RE</acronym>s or <acronym>ARE</>s
4504 in this documentation. AREs are almost an exact superset of EREs,
4505 but BREs have several notational incompatibilities (as well as being
4507 We first describe the ARE and ERE forms, noting features that apply
4508 only to AREs, and then describe how BREs differ.
4513 <productname>PostgreSQL</> always initially presumes that a regular
4514 expression follows the ARE rules. However, the more limited ERE or
4515 BRE rules can be chosen by prepending an <firstterm>embedded option</>
4516 to the RE pattern, as described in <xref linkend="posix-metasyntax">.
4517 This can be useful for compatibility with applications that expect
4518 exactly the <acronym>POSIX</acronym> 1003.2 rules.
4523 A regular expression is defined as one or more
4524 <firstterm>branches</firstterm>, separated by
4525 <literal>|</literal>. It matches anything that matches one of the
4530 A branch is zero or more <firstterm>quantified atoms</> or
4531 <firstterm>constraints</>, concatenated.
4532 It matches a match for the first, followed by a match for the second, etc;
4533 an empty branch matches the empty string.
4537 A quantified atom is an <firstterm>atom</> possibly followed
4538 by a single <firstterm>quantifier</>.
4539 Without a quantifier, it matches a match for the atom.
4540 With a quantifier, it can match some number of matches of the atom.
4541 An <firstterm>atom</firstterm> can be any of the possibilities
4542 shown in <xref linkend="posix-atoms-table">.
4543 The possible quantifiers and their meanings are shown in
4544 <xref linkend="posix-quantifiers-table">.
4548 A <firstterm>constraint</> matches an empty string, but matches only when
4549 specific conditions are met. A constraint can be used where an atom
4550 could be used, except it cannot be followed by a quantifier.
4551 The simple constraints are shown in
4552 <xref linkend="posix-constraints-table">;
4553 some more constraints are described later.
4557 <table id="posix-atoms-table">
4558 <title>Regular Expression Atoms</title>
4564 <entry>Description</entry>
4570 <entry> <literal>(</><replaceable>re</><literal>)</> </entry>
4571 <entry> (where <replaceable>re</> is any regular expression)
4573 <replaceable>re</>, with the match noted for possible reporting </entry>
4577 <entry> <literal>(?:</><replaceable>re</><literal>)</> </entry>
4578 <entry> as above, but the match is not noted for reporting
4579 (a <quote>non-capturing</> set of parentheses)
4580 (AREs only) </entry>
4584 <entry> <literal>.</> </entry>
4585 <entry> matches any single character </entry>
4589 <entry> <literal>[</><replaceable>chars</><literal>]</> </entry>
4590 <entry> a <firstterm>bracket expression</>,
4591 matching any one of the <replaceable>chars</> (see
4592 <xref linkend="posix-bracket-expressions"> for more detail) </entry>
4596 <entry> <literal>\</><replaceable>k</> </entry>
4597 <entry> (where <replaceable>k</> is a non-alphanumeric character)
4598 matches that character taken as an ordinary character,
4599 e.g., <literal>\\</> matches a backslash character </entry>
4603 <entry> <literal>\</><replaceable>c</> </entry>
4604 <entry> where <replaceable>c</> is alphanumeric
4605 (possibly followed by other characters)
4606 is an <firstterm>escape</>, see <xref linkend="posix-escape-sequences">
4607 (AREs only; in EREs and BREs, this matches <replaceable>c</>) </entry>
4611 <entry> <literal>{</> </entry>
4612 <entry> when followed by a character other than a digit,
4613 matches the left-brace character <literal>{</>;
4614 when followed by a digit, it is the beginning of a
4615 <replaceable>bound</> (see below) </entry>
4619 <entry> <replaceable>x</> </entry>
4620 <entry> where <replaceable>x</> is a single character with no other
4621 significance, matches that character </entry>
4628 An RE cannot end with a backslash (<literal>\</>).
4633 If you have <xref linkend="guc-standard-conforming-strings"> turned off,
4634 any backslashes you write in literal string constants will need to be
4635 doubled. See <xref linkend="sql-syntax-strings"> for more information.
4639 <table id="posix-quantifiers-table">
4640 <title>Regular Expression Quantifiers</title>
4645 <entry>Quantifier</entry>
4646 <entry>Matches</entry>
4652 <entry> <literal>*</> </entry>
4653 <entry> a sequence of 0 or more matches of the atom </entry>
4657 <entry> <literal>+</> </entry>
4658 <entry> a sequence of 1 or more matches of the atom </entry>
4662 <entry> <literal>?</> </entry>
4663 <entry> a sequence of 0 or 1 matches of the atom </entry>
4667 <entry> <literal>{</><replaceable>m</><literal>}</> </entry>
4668 <entry> a sequence of exactly <replaceable>m</> matches of the atom </entry>
4672 <entry> <literal>{</><replaceable>m</><literal>,}</> </entry>
4673 <entry> a sequence of <replaceable>m</> or more matches of the atom </entry>
4678 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
4679 <entry> a sequence of <replaceable>m</> through <replaceable>n</>
4680 (inclusive) matches of the atom; <replaceable>m</> cannot exceed
4681 <replaceable>n</> </entry>
4685 <entry> <literal>*?</> </entry>
4686 <entry> non-greedy version of <literal>*</> </entry>
4690 <entry> <literal>+?</> </entry>
4691 <entry> non-greedy version of <literal>+</> </entry>
4695 <entry> <literal>??</> </entry>
4696 <entry> non-greedy version of <literal>?</> </entry>
4700 <entry> <literal>{</><replaceable>m</><literal>}?</> </entry>
4701 <entry> non-greedy version of <literal>{</><replaceable>m</><literal>}</> </entry>
4705 <entry> <literal>{</><replaceable>m</><literal>,}?</> </entry>
4706 <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,}</> </entry>
4711 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</> </entry>
4712 <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
4719 The forms using <literal>{</><replaceable>...</><literal>}</>
4720 are known as <firstterm>bounds</>.
4721 The numbers <replaceable>m</> and <replaceable>n</> within a bound are
4722 unsigned decimal integers with permissible values from 0 to 255 inclusive.
4726 <firstterm>Non-greedy</> quantifiers (available in AREs only) match the
4727 same possibilities as their corresponding normal (<firstterm>greedy</>)
4728 counterparts, but prefer the smallest number rather than the largest
4730 See <xref linkend="posix-matching-rules"> for more detail.
4735 A quantifier cannot immediately follow another quantifier, e.g.,
4736 <literal>**</> is invalid.
4738 begin an expression or subexpression or follow
4739 <literal>^</literal> or <literal>|</literal>.
4743 <table id="posix-constraints-table">
4744 <title>Regular Expression Constraints</title>
4749 <entry>Constraint</entry>
4750 <entry>Description</entry>
4756 <entry> <literal>^</> </entry>
4757 <entry> matches at the beginning of the string </entry>
4761 <entry> <literal>$</> </entry>
4762 <entry> matches at the end of the string </entry>
4766 <entry> <literal>(?=</><replaceable>re</><literal>)</> </entry>
4767 <entry> <firstterm>positive lookahead</> matches at any point
4768 where a substring matching <replaceable>re</> begins
4769 (AREs only) </entry>
4773 <entry> <literal>(?!</><replaceable>re</><literal>)</> </entry>
4774 <entry> <firstterm>negative lookahead</> matches at any point
4775 where no substring matching <replaceable>re</> begins
4776 (AREs only) </entry>
4780 <entry> <literal>(?<=</><replaceable>re</><literal>)</> </entry>
4781 <entry> <firstterm>positive lookbehind</> matches at any point
4782 where a substring matching <replaceable>re</> ends
4783 (AREs only) </entry>
4787 <entry> <literal>(?<!</><replaceable>re</><literal>)</> </entry>
4788 <entry> <firstterm>negative lookbehind</> matches at any point
4789 where no substring matching <replaceable>re</> ends
4790 (AREs only) </entry>
4797 Lookahead and lookbehind constraints cannot contain <firstterm>back
4798 references</> (see <xref linkend="posix-escape-sequences">),
4799 and all parentheses within them are considered non-capturing.
4803 <sect3 id="posix-bracket-expressions">
4804 <title>Bracket Expressions</title>
4807 A <firstterm>bracket expression</firstterm> is a list of
4808 characters enclosed in <literal>[]</literal>. It normally matches
4809 any single character from the list (but see below). If the list
4810 begins with <literal>^</literal>, it matches any single character
4811 <emphasis>not</> from the rest of the list.
4813 in the list are separated by <literal>-</literal>, this is
4814 shorthand for the full range of characters between those two
4815 (inclusive) in the collating sequence,
4816 e.g., <literal>[0-9]</literal> in <acronym>ASCII</acronym> matches
4817 any decimal digit. It is illegal for two ranges to share an
4818 endpoint, e.g., <literal>a-c-e</literal>. Ranges are very
4819 collating-sequence-dependent, so portable programs should avoid
4824 To include a literal <literal>]</literal> in the list, make it the
4825 first character (after <literal>^</literal>, if that is used). To
4826 include a literal <literal>-</literal>, make it the first or last
4827 character, or the second endpoint of a range. To use a literal
4828 <literal>-</literal> as the first endpoint of a range, enclose it
4829 in <literal>[.</literal> and <literal>.]</literal> to make it a
4830 collating element (see below). With the exception of these characters,
4831 some combinations using <literal>[</literal>
4832 (see next paragraphs), and escapes (AREs only), all other special
4833 characters lose their special significance within a bracket expression.
4834 In particular, <literal>\</literal> is not special when following
4835 ERE or BRE rules, though it is special (as introducing an escape)
4840 Within a bracket expression, a collating element (a character, a
4841 multiple-character sequence that collates as if it were a single
4842 character, or a collating-sequence name for either) enclosed in
4843 <literal>[.</literal> and <literal>.]</literal> stands for the
4844 sequence of characters of that collating element. The sequence is
4845 treated as a single element of the bracket expression's list. This
4847 expression containing a multiple-character collating element to
4848 match more than one character, e.g., if the collating sequence
4849 includes a <literal>ch</literal> collating element, then the RE
4850 <literal>[[.ch.]]*c</literal> matches the first five characters of
4851 <literal>chchcc</literal>.
4856 <productname>PostgreSQL</> currently does not support multi-character collating
4857 elements. This information describes possible future behavior.
4862 Within a bracket expression, a collating element enclosed in
4863 <literal>[=</literal> and <literal>=]</literal> is an <firstterm>equivalence
4864 class</>, standing for the sequences of characters of all collating
4865 elements equivalent to that one, including itself. (If there are
4866 no other equivalent collating elements, the treatment is as if the
4867 enclosing delimiters were <literal>[.</literal> and
4868 <literal>.]</literal>.) For example, if <literal>o</literal> and
4869 <literal>^</literal> are the members of an equivalence class, then
4870 <literal>[[=o=]]</literal>, <literal>[[=^=]]</literal>, and
4871 <literal>[o^]</literal> are all synonymous. An equivalence class
4872 cannot be an endpoint of a range.
4876 Within a bracket expression, the name of a character class
4877 enclosed in <literal>[:</literal> and <literal>:]</literal> stands
4878 for the list of all characters belonging to that class. Standard
4879 character class names are: <literal>alnum</literal>,
4880 <literal>alpha</literal>, <literal>blank</literal>,
4881 <literal>cntrl</literal>, <literal>digit</literal>,
4882 <literal>graph</literal>, <literal>lower</literal>,
4883 <literal>print</literal>, <literal>punct</literal>,
4884 <literal>space</literal>, <literal>upper</literal>,
4885 <literal>xdigit</literal>. These stand for the character classes
4887 <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>.
4888 A locale can provide others. A character class cannot be used as
4889 an endpoint of a range.
4893 There are two special cases of bracket expressions: the bracket
4894 expressions <literal>[[:<:]]</literal> and
4895 <literal>[[:>:]]</literal> are constraints,
4896 matching empty strings at the beginning
4897 and end of a word respectively. A word is defined as a sequence
4898 of word characters that is neither preceded nor followed by word
4899 characters. A word character is an <literal>alnum</> character (as
4901 <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>)
4902 or an underscore. This is an extension, compatible with but not
4903 specified by <acronym>POSIX</acronym> 1003.2, and should be used with
4904 caution in software intended to be portable to other systems.
4905 The constraint escapes described below are usually preferable; they
4906 are no more standard, but are easier to type.
4910 <sect3 id="posix-escape-sequences">
4911 <title>Regular Expression Escapes</title>
4914 <firstterm>Escapes</> are special sequences beginning with <literal>\</>
4915 followed by an alphanumeric character. Escapes come in several varieties:
4916 character entry, class shorthands, constraint escapes, and back references.
4917 A <literal>\</> followed by an alphanumeric character but not constituting
4918 a valid escape is illegal in AREs.
4919 In EREs, there are no escapes: outside a bracket expression,
4920 a <literal>\</> followed by an alphanumeric character merely stands for
4921 that character as an ordinary character, and inside a bracket expression,
4922 <literal>\</> is an ordinary character.
4923 (The latter is the one actual incompatibility between EREs and AREs.)
4927 <firstterm>Character-entry escapes</> exist to make it easier to specify
4928 non-printing and other inconvenient characters in REs. They are
4929 shown in <xref linkend="posix-character-entry-escapes-table">.
4933 <firstterm>Class-shorthand escapes</> provide shorthands for certain
4934 commonly-used character classes. They are
4935 shown in <xref linkend="posix-class-shorthand-escapes-table">.
4939 A <firstterm>constraint escape</> is a constraint,
4940 matching the empty string if specific conditions are met,
4941 written as an escape. They are
4942 shown in <xref linkend="posix-constraint-escapes-table">.
4946 A <firstterm>back reference</> (<literal>\</><replaceable>n</>) matches the
4947 same string matched by the previous parenthesized subexpression specified
4948 by the number <replaceable>n</>
4949 (see <xref linkend="posix-constraint-backref-table">). For example,
4950 <literal>([bc])\1</> matches <literal>bb</> or <literal>cc</>
4951 but not <literal>bc</> or <literal>cb</>.
4952 The subexpression must entirely precede the back reference in the RE.
4953 Subexpressions are numbered in the order of their leading parentheses.
4954 Non-capturing parentheses do not define subexpressions.
4957 <table id="posix-character-entry-escapes-table">
4958 <title>Regular Expression Character-entry Escapes</title>
4963 <entry>Escape</entry>
4964 <entry>Description</entry>
4970 <entry> <literal>\a</> </entry>
4971 <entry> alert (bell) character, as in C </entry>
4975 <entry> <literal>\b</> </entry>
4976 <entry> backspace, as in C </entry>
4980 <entry> <literal>\B</> </entry>
4981 <entry> synonym for backslash (<literal>\</>) to help reduce the need for backslash
4986 <entry> <literal>\c</><replaceable>X</> </entry>
4987 <entry> (where <replaceable>X</> is any character) the character whose
4988 low-order 5 bits are the same as those of
4989 <replaceable>X</>, and whose other bits are all zero </entry>
4993 <entry> <literal>\e</> </entry>
4994 <entry> the character whose collating-sequence name
4996 or failing that, the character with octal value <literal>033</> </entry>
5000 <entry> <literal>\f</> </entry>
5001 <entry> form feed, as in C </entry>
5005 <entry> <literal>\n</> </entry>
5006 <entry> newline, as in C </entry>
5010 <entry> <literal>\r</> </entry>
5011 <entry> carriage return, as in C </entry>
5015 <entry> <literal>\t</> </entry>
5016 <entry> horizontal tab, as in C </entry>
5020 <entry> <literal>\u</><replaceable>wxyz</> </entry>
5021 <entry> (where <replaceable>wxyz</> is exactly four hexadecimal digits)
5022 the character whose hexadecimal value is
5023 <literal>0x</><replaceable>wxyz</>
5028 <entry> <literal>\U</><replaceable>stuvwxyz</> </entry>
5029 <entry> (where <replaceable>stuvwxyz</> is exactly eight hexadecimal
5031 the character whose hexadecimal value is
5032 <literal>0x</><replaceable>stuvwxyz</>
5037 <entry> <literal>\v</> </entry>
5038 <entry> vertical tab, as in C </entry>
5042 <entry> <literal>\x</><replaceable>hhh</> </entry>
5043 <entry> (where <replaceable>hhh</> is any sequence of hexadecimal
5045 the character whose hexadecimal value is
5046 <literal>0x</><replaceable>hhh</>
5047 (a single character no matter how many hexadecimal digits are used)
5052 <entry> <literal>\0</> </entry>
5053 <entry> the character whose value is <literal>0</> (the null byte)</entry>
5057 <entry> <literal>\</><replaceable>xy</> </entry>
5058 <entry> (where <replaceable>xy</> is exactly two octal digits,
5059 and is not a <firstterm>back reference</>)
5060 the character whose octal value is
5061 <literal>0</><replaceable>xy</> </entry>
5065 <entry> <literal>\</><replaceable>xyz</> </entry>
5066 <entry> (where <replaceable>xyz</> is exactly three octal digits,
5067 and is not a <firstterm>back reference</>)
5068 the character whose octal value is
5069 <literal>0</><replaceable>xyz</> </entry>
5076 Hexadecimal digits are <literal>0</>-<literal>9</>,
5077 <literal>a</>-<literal>f</>, and <literal>A</>-<literal>F</>.
5078 Octal digits are <literal>0</>-<literal>7</>.
5082 Numeric character-entry escapes specifying values outside the ASCII range
5083 (0-127) have meanings dependent on the database encoding. When the
5084 encoding is UTF-8, escape values are equivalent to Unicode code points,
5085 for example <literal>\u1234</> means the character <literal>U+1234</>.
5086 For other multibyte encodings, character-entry escapes usually just
5087 specify the concatenation of the byte values for the character. If the
5088 escape value does not correspond to any legal character in the database
5089 encoding, no error will be raised, but it will never match any data.
5093 The character-entry escapes are always taken as ordinary characters.
5094 For example, <literal>\135</> is <literal>]</> in ASCII, but
5095 <literal>\135</> does not terminate a bracket expression.
5098 <table id="posix-class-shorthand-escapes-table">
5099 <title>Regular Expression Class-shorthand Escapes</title>
5104 <entry>Escape</entry>
5105 <entry>Description</entry>
5111 <entry> <literal>\d</> </entry>
5112 <entry> <literal>[[:digit:]]</> </entry>
5116 <entry> <literal>\s</> </entry>
5117 <entry> <literal>[[:space:]]</> </entry>
5121 <entry> <literal>\w</> </entry>
5122 <entry> <literal>[[:alnum:]_]</>
5123 (note underscore is included) </entry>
5127 <entry> <literal>\D</> </entry>
5128 <entry> <literal>[^[:digit:]]</> </entry>
5132 <entry> <literal>\S</> </entry>
5133 <entry> <literal>[^[:space:]]</> </entry>
5137 <entry> <literal>\W</> </entry>
5138 <entry> <literal>[^[:alnum:]_]</>
5139 (note underscore is included) </entry>
5146 Within bracket expressions, <literal>\d</>, <literal>\s</>,
5147 and <literal>\w</> lose their outer brackets,
5148 and <literal>\D</>, <literal>\S</>, and <literal>\W</> are illegal.
5149 (So, for example, <literal>[a-c\d]</> is equivalent to
5150 <literal>[a-c[:digit:]]</>.
5151 Also, <literal>[a-c\D]</>, which is equivalent to
5152 <literal>[a-c^[:digit:]]</>, is illegal.)
5155 <table id="posix-constraint-escapes-table">
5156 <title>Regular Expression Constraint Escapes</title>
5161 <entry>Escape</entry>
5162 <entry>Description</entry>
5168 <entry> <literal>\A</> </entry>
5169 <entry> matches only at the beginning of the string
5170 (see <xref linkend="posix-matching-rules"> for how this differs from
5171 <literal>^</>) </entry>
5175 <entry> <literal>\m</> </entry>
5176 <entry> matches only at the beginning of a word </entry>
5180 <entry> <literal>\M</> </entry>
5181 <entry> matches only at the end of a word </entry>
5185 <entry> <literal>\y</> </entry>
5186 <entry> matches only at the beginning or end of a word </entry>
5190 <entry> <literal>\Y</> </entry>
5191 <entry> matches only at a point that is not the beginning or end of a
5196 <entry> <literal>\Z</> </entry>
5197 <entry> matches only at the end of the string
5198 (see <xref linkend="posix-matching-rules"> for how this differs from
5199 <literal>$</>) </entry>
5206 A word is defined as in the specification of
5207 <literal>[[:<:]]</> and <literal>[[:>:]]</> above.
5208 Constraint escapes are illegal within bracket expressions.
5211 <table id="posix-constraint-backref-table">
5212 <title>Regular Expression Back References</title>
5217 <entry>Escape</entry>
5218 <entry>Description</entry>
5224 <entry> <literal>\</><replaceable>m</> </entry>
5225 <entry> (where <replaceable>m</> is a nonzero digit)
5226 a back reference to the <replaceable>m</>'th subexpression </entry>
5230 <entry> <literal>\</><replaceable>mnn</> </entry>
5231 <entry> (where <replaceable>m</> is a nonzero digit, and
5232 <replaceable>nn</> is some more digits, and the decimal value
5233 <replaceable>mnn</> is not greater than the number of closing capturing
5234 parentheses seen so far)
5235 a back reference to the <replaceable>mnn</>'th subexpression </entry>
5243 There is an inherent ambiguity between octal character-entry
5244 escapes and back references, which is resolved by the following heuristics,
5246 A leading zero always indicates an octal escape.
5247 A single non-zero digit, not followed by another digit,
5248 is always taken as a back reference.
5249 A multi-digit sequence not starting with a zero is taken as a back
5250 reference if it comes after a suitable subexpression
5251 (i.e., the number is in the legal range for a back reference),
5252 and otherwise is taken as octal.
5257 <sect3 id="posix-metasyntax">
5258 <title>Regular Expression Metasyntax</title>
5261 In addition to the main syntax described above, there are some special
5262 forms and miscellaneous syntactic facilities available.
5266 An RE can begin with one of two special <firstterm>director</> prefixes.
5267 If an RE begins with <literal>***:</>,
5268 the rest of the RE is taken as an ARE. (This normally has no effect in
5269 <productname>PostgreSQL</>, since REs are assumed to be AREs;
5270 but it does have an effect if ERE or BRE mode had been specified by
5271 the <replaceable>flags</> parameter to a regex function.)
5272 If an RE begins with <literal>***=</>,
5273 the rest of the RE is taken to be a literal string,
5274 with all characters considered ordinary characters.
5278 An ARE can begin with <firstterm>embedded options</>:
5279 a sequence <literal>(?</><replaceable>xyz</><literal>)</>
5280 (where <replaceable>xyz</> is one or more alphabetic characters)
5281 specifies options affecting the rest of the RE.
5282 These options override any previously determined options —
5283 in particular, they can override the case-sensitivity behavior implied by
5284 a regex operator, or the <replaceable>flags</> parameter to a regex
5286 The available option letters are
5287 shown in <xref linkend="posix-embedded-options-table">.
5288 Note that these same option letters are used in the <replaceable>flags</>
5289 parameters of regex functions.
5292 <table id="posix-embedded-options-table">
5293 <title>ARE Embedded-option Letters</title>
5298 <entry>Option</entry>
5299 <entry>Description</entry>
5305 <entry> <literal>b</> </entry>
5306 <entry> rest of RE is a BRE </entry>
5310 <entry> <literal>c</> </entry>
5311 <entry> case-sensitive matching (overrides operator type) </entry>
5315 <entry> <literal>e</> </entry>
5316 <entry> rest of RE is an ERE </entry>
5320 <entry> <literal>i</> </entry>
5321 <entry> case-insensitive matching (see
5322 <xref linkend="posix-matching-rules">) (overrides operator type) </entry>
5326 <entry> <literal>m</> </entry>
5327 <entry> historical synonym for <literal>n</> </entry>
5331 <entry> <literal>n</> </entry>
5332 <entry> newline-sensitive matching (see
5333 <xref linkend="posix-matching-rules">) </entry>
5337 <entry> <literal>p</> </entry>
5338 <entry> partial newline-sensitive matching (see
5339 <xref linkend="posix-matching-rules">) </entry>
5343 <entry> <literal>q</> </entry>
5344 <entry> rest of RE is a literal (<quote>quoted</>) string, all ordinary
5349 <entry> <literal>s</> </entry>
5350 <entry> non-newline-sensitive matching (default) </entry>
5354 <entry> <literal>t</> </entry>
5355 <entry> tight syntax (default; see below) </entry>
5359 <entry> <literal>w</> </entry>
5360 <entry> inverse partial newline-sensitive (<quote>weird</>) matching
5361 (see <xref linkend="posix-matching-rules">) </entry>
5365 <entry> <literal>x</> </entry>
5366 <entry> expanded syntax (see below) </entry>
5373 Embedded options take effect at the <literal>)</> terminating the sequence.
5374 They can appear only at the start of an ARE (after the
5375 <literal>***:</> director if any).
5379 In addition to the usual (<firstterm>tight</>) RE syntax, in which all
5380 characters are significant, there is an <firstterm>expanded</> syntax,
5381 available by specifying the embedded <literal>x</> option.
5382 In the expanded syntax,
5383 white-space characters in the RE are ignored, as are
5384 all characters between a <literal>#</>
5385 and the following newline (or the end of the RE). This
5386 permits paragraphing and commenting a complex RE.
5387 There are three exceptions to that basic rule:
5392 a white-space character or <literal>#</> preceded by <literal>\</> is
5398 white space or <literal>#</> within a bracket expression is retained
5403 white space and comments cannot appear within multi-character symbols,
5404 such as <literal>(?:</>
5409 For this purpose, white-space characters are blank, tab, newline, and
5410 any character that belongs to the <replaceable>space</> character class.
5414 Finally, in an ARE, outside bracket expressions, the sequence
5415 <literal>(?#</><replaceable>ttt</><literal>)</>
5416 (where <replaceable>ttt</> is any text not containing a <literal>)</>)
5417 is a comment, completely ignored.
5418 Again, this is not allowed between the characters of
5419 multi-character symbols, like <literal>(?:</>.
5420 Such comments are more a historical artifact than a useful facility,
5421 and their use is deprecated; use the expanded syntax instead.
5425 <emphasis>None</> of these metasyntax extensions is available if
5426 an initial <literal>***=</> director
5427 has specified that the user's input be treated as a literal string
5428 rather than as an RE.
5432 <sect3 id="posix-matching-rules">
5433 <title>Regular Expression Matching Rules</title>
5436 In the event that an RE could match more than one substring of a given
5437 string, the RE matches the one starting earliest in the string.
5438 If the RE could match more than one substring starting at that point,
5439 either the longest possible match or the shortest possible match will
5440 be taken, depending on whether the RE is <firstterm>greedy</> or
5441 <firstterm>non-greedy</>.
5445 Whether an RE is greedy or not is determined by the following rules:
5449 Most atoms, and all constraints, have no greediness attribute (because
5450 they cannot match variable amounts of text anyway).
5455 Adding parentheses around an RE does not change its greediness.
5460 A quantified atom with a fixed-repetition quantifier
5461 (<literal>{</><replaceable>m</><literal>}</>
5463 <literal>{</><replaceable>m</><literal>}?</>)
5464 has the same greediness (possibly none) as the atom itself.
5469 A quantified atom with other normal quantifiers (including
5470 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</>
5471 with <replaceable>m</> equal to <replaceable>n</>)
5472 is greedy (prefers longest match).
5477 A quantified atom with a non-greedy quantifier (including
5478 <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</>
5479 with <replaceable>m</> equal to <replaceable>n</>)
5480 is non-greedy (prefers shortest match).
5485 A branch — that is, an RE that has no top-level
5486 <literal>|</> operator — has the same greediness as the first
5487 quantified atom in it that has a greediness attribute.
5492 An RE consisting of two or more branches connected by the
5493 <literal>|</> operator is always greedy.
5500 The above rules associate greediness attributes not only with individual
5501 quantified atoms, but with branches and entire REs that contain quantified
5502 atoms. What that means is that the matching is done in such a way that
5503 the branch, or whole RE, matches the longest or shortest possible
5504 substring <emphasis>as a whole</>. Once the length of the entire match
5505 is determined, the part of it that matches any particular subexpression
5506 is determined on the basis of the greediness attribute of that
5507 subexpression, with subexpressions starting earlier in the RE taking
5508 priority over ones starting later.
5512 An example of what this means:
5514 SELECT SUBSTRING('XY1234Z', 'Y*([0-9]{1,3})');
5515 <lineannotation>Result: </lineannotation><computeroutput>123</computeroutput>
5516 SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{1,3})');
5517 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
5519 In the first case, the RE as a whole is greedy because <literal>Y*</>
5520 is greedy. It can match beginning at the <literal>Y</>, and it matches
5521 the longest possible string starting there, i.e., <literal>Y123</>.
5522 The output is the parenthesized part of that, or <literal>123</>.
5523 In the second case, the RE as a whole is non-greedy because <literal>Y*?</>
5524 is non-greedy. It can match beginning at the <literal>Y</>, and it matches
5525 the shortest possible string starting there, i.e., <literal>Y1</>.
5526 The subexpression <literal>[0-9]{1,3}</> is greedy but it cannot change
5527 the decision as to the overall match length; so it is forced to match
5532 In short, when an RE contains both greedy and non-greedy subexpressions,
5533 the total match length is either as long as possible or as short as
5534 possible, according to the attribute assigned to the whole RE. The
5535 attributes assigned to the subexpressions only affect how much of that
5536 match they are allowed to <quote>eat</> relative to each other.
5540 The quantifiers <literal>{1,1}</> and <literal>{1,1}?</>
5541 can be used to force greediness or non-greediness, respectively,
5542 on a subexpression or a whole RE.
5543 This is useful when you need the whole RE to have a greediness attribute
5544 different from what's deduced from its elements. As an example,
5545 suppose that we are trying to separate a string containing some digits
5546 into the digits and the parts before and after them. We might try to
5549 SELECT regexp_match('abc01234xyz', '(.*)(\d+)(.*)');
5550 <lineannotation>Result: </lineannotation><computeroutput>{abc0123,4,xyz}</computeroutput>
5552 That didn't work: the first <literal>.*</> is greedy so
5553 it <quote>eats</> as much as it can, leaving the <literal>\d+</> to
5554 match at the last possible place, the last digit. We might try to fix
5555 that by making it non-greedy:
5557 SELECT regexp_match('abc01234xyz', '(.*?)(\d+)(.*)');
5558 <lineannotation>Result: </lineannotation><computeroutput>{abc,0,""}</computeroutput>
5560 That didn't work either, because now the RE as a whole is non-greedy
5561 and so it ends the overall match as soon as possible. We can get what
5562 we want by forcing the RE as a whole to be greedy:
5564 SELECT regexp_match('abc01234xyz', '(?:(.*?)(\d+)(.*)){1,1}');
5565 <lineannotation>Result: </lineannotation><computeroutput>{abc,01234,xyz}</computeroutput>
5567 Controlling the RE's overall greediness separately from its components'
5568 greediness allows great flexibility in handling variable-length patterns.
5572 When deciding what is a longer or shorter match,
5573 match lengths are measured in characters, not collating elements.
5574 An empty string is considered longer than no match at all.
5577 matches the three middle characters of <literal>abbbc</>;
5578 <literal>(week|wee)(night|knights)</>
5579 matches all ten characters of <literal>weeknights</>;
5580 when <literal>(.*).*</>
5581 is matched against <literal>abc</> the parenthesized subexpression
5582 matches all three characters; and when
5583 <literal>(a*)*</> is matched against <literal>bc</>
5584 both the whole RE and the parenthesized
5585 subexpression match an empty string.
5589 If case-independent matching is specified,
5590 the effect is much as if all case distinctions had vanished from the
5592 When an alphabetic that exists in multiple cases appears as an
5593 ordinary character outside a bracket expression, it is effectively
5594 transformed into a bracket expression containing both cases,
5595 e.g., <literal>x</> becomes <literal>[xX]</>.
5596 When it appears inside a bracket expression, all case counterparts
5597 of it are added to the bracket expression, e.g.,
5598 <literal>[x]</> becomes <literal>[xX]</>
5599 and <literal>[^x]</> becomes <literal>[^xX]</>.
5603 If newline-sensitive matching is specified, <literal>.</>
5604 and bracket expressions using <literal>^</>
5605 will never match the newline character
5606 (so that matches will never cross newlines unless the RE
5607 explicitly arranges it)
5608 and <literal>^</> and <literal>$</>
5609 will match the empty string after and before a newline
5610 respectively, in addition to matching at beginning and end of string
5612 But the ARE escapes <literal>\A</> and <literal>\Z</>
5613 continue to match beginning or end of string <emphasis>only</>.
5617 If partial newline-sensitive matching is specified,
5618 this affects <literal>.</> and bracket expressions
5619 as with newline-sensitive matching, but not <literal>^</>
5624 If inverse partial newline-sensitive matching is specified,
5625 this affects <literal>^</> and <literal>$</>
5626 as with newline-sensitive matching, but not <literal>.</>
5627 and bracket expressions.
5628 This isn't very useful but is provided for symmetry.
5632 <sect3 id="posix-limits-compatibility">
5633 <title>Limits and Compatibility</title>
5636 No particular limit is imposed on the length of REs in this
5637 implementation. However,
5638 programs intended to be highly portable should not employ REs longer
5640 as a POSIX-compliant implementation can refuse to accept such REs.
5644 The only feature of AREs that is actually incompatible with
5645 POSIX EREs is that <literal>\</> does not lose its special
5646 significance inside bracket expressions.
5647 All other ARE features use syntax which is illegal or has
5648 undefined or unspecified effects in POSIX EREs;
5649 the <literal>***</> syntax of directors likewise is outside the POSIX
5650 syntax for both BREs and EREs.
5654 Many of the ARE extensions are borrowed from Perl, but some have
5655 been changed to clean them up, and a few Perl extensions are not present.
5656 Incompatibilities of note include <literal>\b</>, <literal>\B</>,
5657 the lack of special treatment for a trailing newline,
5658 the addition of complemented bracket expressions to the things
5659 affected by newline-sensitive matching,
5660 the restrictions on parentheses and back references in lookahead/lookbehind
5661 constraints, and the longest/shortest-match (rather than first-match)
5666 Two significant incompatibilities exist between AREs and the ERE syntax
5667 recognized by pre-7.4 releases of <productname>PostgreSQL</>:
5672 In AREs, <literal>\</> followed by an alphanumeric character is either
5673 an escape or an error, while in previous releases, it was just another
5674 way of writing the alphanumeric.
5675 This should not be much of a problem because there was no reason to
5676 write such a sequence in earlier releases.
5681 In AREs, <literal>\</> remains a special character within
5682 <literal>[]</>, so a literal <literal>\</> within a bracket
5683 expression must be written <literal>\\</>.
5690 <sect3 id="posix-basic-regexes">
5691 <title>Basic Regular Expressions</title>
5694 BREs differ from EREs in several respects.
5695 In BREs, <literal>|</>, <literal>+</>, and <literal>?</>
5696 are ordinary characters and there is no equivalent
5697 for their functionality.
5698 The delimiters for bounds are
5699 <literal>\{</> and <literal>\}</>,
5700 with <literal>{</> and <literal>}</>
5701 by themselves ordinary characters.
5702 The parentheses for nested subexpressions are
5703 <literal>\(</> and <literal>\)</>,
5704 with <literal>(</> and <literal>)</> by themselves ordinary characters.
5705 <literal>^</> is an ordinary character except at the beginning of the
5706 RE or the beginning of a parenthesized subexpression,
5707 <literal>$</> is an ordinary character except at the end of the
5708 RE or the end of a parenthesized subexpression,
5709 and <literal>*</> is an ordinary character if it appears at the beginning
5710 of the RE or the beginning of a parenthesized subexpression
5711 (after a possible leading <literal>^</>).
5712 Finally, single-digit back references are available, and
5713 <literal>\<</> and <literal>\></>
5715 <literal>[[:<:]]</> and <literal>[[:>:]]</>
5716 respectively; no other escapes are available in BREs.
5720 <!-- end re_syntax.n man page -->
5726 <sect1 id="functions-formatting">
5727 <title>Data Type Formatting Functions</title>
5730 <primary>formatting</primary>
5734 The <productname>PostgreSQL</productname> formatting functions
5735 provide a powerful set of tools for converting various data types
5736 (date/time, integer, floating point, numeric) to formatted strings
5737 and for converting from formatted strings to specific data types.
5738 <xref linkend="functions-formatting-table"> lists them.
5739 These functions all follow a common calling convention: the first
5740 argument is the value to be formatted and the second argument is a
5741 template that defines the output or input format.
5744 <table id="functions-formatting-table">
5745 <title>Formatting Functions</title>
5749 <entry>Function</entry>
5750 <entry>Return Type</entry>
5751 <entry>Description</entry>
5752 <entry>Example</entry>
5759 <primary>to_char</primary>
5761 <literal><function>to_char(<type>timestamp</type>, <type>text</type>)</function></literal>
5763 <entry><type>text</type></entry>
5764 <entry>convert time stamp to string</entry>
5765 <entry><literal>to_char(current_timestamp, 'HH12:MI:SS')</literal></entry>
5768 <entry><literal><function>to_char(<type>interval</type>, <type>text</type>)</function></literal></entry>
5769 <entry><type>text</type></entry>
5770 <entry>convert interval to string</entry>
5771 <entry><literal>to_char(interval '15h 2m 12s', 'HH24:MI:SS')</literal></entry>
5774 <entry><literal><function>to_char(<type>int</type>, <type>text</type>)</function></literal></entry>
5775 <entry><type>text</type></entry>
5776 <entry>convert integer to string</entry>
5777 <entry><literal>to_char(125, '999')</literal></entry>
5780 <entry><literal><function>to_char</function>(<type>double precision</type>,
5781 <type>text</type>)</literal></entry>
5782 <entry><type>text</type></entry>
5783 <entry>convert real/double precision to string</entry>
5784 <entry><literal>to_char(125.8::real, '999D9')</literal></entry>
5787 <entry><literal><function>to_char(<type>numeric</type>, <type>text</type>)</function></literal></entry>
5788 <entry><type>text</type></entry>
5789 <entry>convert numeric to string</entry>
5790 <entry><literal>to_char(-125.8, '999D99S')</literal></entry>
5795 <primary>to_date</primary>
5797 <literal><function>to_date(<type>text</type>, <type>text</type>)</function></literal>
5799 <entry><type>date</type></entry>
5800 <entry>convert string to date</entry>
5801 <entry><literal>to_date('05 Dec 2000', 'DD Mon YYYY')</literal></entry>
5806 <primary>to_number</primary>
5808 <literal><function>to_number(<type>text</type>, <type>text</type>)</function></literal>
5810 <entry><type>numeric</type></entry>
5811 <entry>convert string to numeric</entry>
5812 <entry><literal>to_number('12,454.8-', '99G999D9S')</literal></entry>
5817 <primary>to_timestamp</primary>
5819 <literal><function>to_timestamp(<type>text</type>, <type>text</type>)</function></literal>
5821 <entry><type>timestamp with time zone</type></entry>
5822 <entry>convert string to time stamp</entry>
5823 <entry><literal>to_timestamp('05 Dec 2000', 'DD Mon YYYY')</literal></entry>
5831 There is also a single-argument <function>to_timestamp</function>
5832 function; see <xref linkend="functions-datetime-table">.
5838 <function>to_timestamp</function> and <function>to_date</function>
5839 exist to handle input formats that cannot be converted by
5840 simple casting. For most standard date/time formats, simply casting the
5841 source string to the required data type works, and is much easier.
5842 Similarly, <function>to_number</> is unnecessary for standard numeric
5848 In a <function>to_char</> output template string, there are certain
5849 patterns that are recognized and replaced with appropriately-formatted
5850 data based on the given value. Any text that is not a template pattern is
5851 simply copied verbatim. Similarly, in an input template string (for the
5852 other functions), template patterns identify the values to be supplied by
5853 the input data string.
5857 <xref linkend="functions-formatting-datetime-table"> shows the
5858 template patterns available for formatting date and time values.
5861 <table id="functions-formatting-datetime-table">
5862 <title>Template Patterns for Date/Time Formatting</title>
5866 <entry>Pattern</entry>
5867 <entry>Description</entry>
5872 <entry><literal>HH</literal></entry>
5873 <entry>hour of day (01-12)</entry>
5876 <entry><literal>HH12</literal></entry>
5877 <entry>hour of day (01-12)</entry>
5880 <entry><literal>HH24</literal></entry>
5881 <entry>hour of day (00-23)</entry>
5884 <entry><literal>MI</literal></entry>
5885 <entry>minute (00-59)</entry>
5888 <entry><literal>SS</literal></entry>
5889 <entry>second (00-59)</entry>
5892 <entry><literal>MS</literal></entry>
5893 <entry>millisecond (000-999)</entry>
5896 <entry><literal>US</literal></entry>
5897 <entry>microsecond (000000-999999)</entry>
5900 <entry><literal>SSSS</literal></entry>
5901 <entry>seconds past midnight (0-86399)</entry>
5904 <entry><literal>AM</literal>, <literal>am</literal>,
5905 <literal>PM</literal> or <literal>pm</literal></entry>
5906 <entry>meridiem indicator (without periods)</entry>
5909 <entry><literal>A.M.</literal>, <literal>a.m.</literal>,
5910 <literal>P.M.</literal> or <literal>p.m.</literal></entry>
5911 <entry>meridiem indicator (with periods)</entry>
5914 <entry><literal>Y,YYY</literal></entry>
5915 <entry>year (4 or more digits) with comma</entry>
5918 <entry><literal>YYYY</literal></entry>
5919 <entry>year (4 or more digits)</entry>
5922 <entry><literal>YYY</literal></entry>
5923 <entry>last 3 digits of year</entry>
5926 <entry><literal>YY</literal></entry>
5927 <entry>last 2 digits of year</entry>
5930 <entry><literal>Y</literal></entry>
5931 <entry>last digit of year</entry>
5934 <entry><literal>IYYY</literal></entry>
5935 <entry>ISO 8601 week-numbering year (4 or more digits)</entry>
5938 <entry><literal>IYY</literal></entry>
5939 <entry>last 3 digits of ISO 8601 week-numbering year</entry>
5942 <entry><literal>IY</literal></entry>
5943 <entry>last 2 digits of ISO 8601 week-numbering year</entry>
5946 <entry><literal>I</literal></entry>
5947 <entry>last digit of ISO 8601 week-numbering year</entry>
5950 <entry><literal>BC</literal>, <literal>bc</literal>,
5951 <literal>AD</literal> or <literal>ad</literal></entry>
5952 <entry>era indicator (without periods)</entry>
5955 <entry><literal>B.C.</literal>, <literal>b.c.</literal>,
5956 <literal>A.D.</literal> or <literal>a.d.</literal></entry>
5957 <entry>era indicator (with periods)</entry>
5960 <entry><literal>MONTH</literal></entry>
5961 <entry>full upper case month name (blank-padded to 9 chars)</entry>
5964 <entry><literal>Month</literal></entry>
5965 <entry>full capitalized month name (blank-padded to 9 chars)</entry>
5968 <entry><literal>month</literal></entry>
5969 <entry>full lower case month name (blank-padded to 9 chars)</entry>
5972 <entry><literal>MON</literal></entry>
5973 <entry>abbreviated upper case month name (3 chars in English, localized lengths vary)</entry>
5976 <entry><literal>Mon</literal></entry>
5977 <entry>abbreviated capitalized month name (3 chars in English, localized lengths vary)</entry>
5980 <entry><literal>mon</literal></entry>
5981 <entry>abbreviated lower case month name (3 chars in English, localized lengths vary)</entry>
5984 <entry><literal>MM</literal></entry>
5985 <entry>month number (01-12)</entry>
5988 <entry><literal>DAY</literal></entry>
5989 <entry>full upper case day name (blank-padded to 9 chars)</entry>
5992 <entry><literal>Day</literal></entry>
5993 <entry>full capitalized day name (blank-padded to 9 chars)</entry>
5996 <entry><literal>day</literal></entry>
5997 <entry>full lower case day name (blank-padded to 9 chars)</entry>
6000 <entry><literal>DY</literal></entry>
6001 <entry>abbreviated upper case day name (3 chars in English, localized lengths vary)</entry>
6004 <entry><literal>Dy</literal></entry>
6005 <entry>abbreviated capitalized day name (3 chars in English, localized lengths vary)</entry>
6008 <entry><literal>dy</literal></entry>
6009 <entry>abbreviated lower case day name (3 chars in English, localized lengths vary)</entry>
6012 <entry><literal>DDD</literal></entry>
6013 <entry>day of year (001-366)</entry>
6016 <entry><literal>IDDD</literal></entry>
6017 <entry>day of ISO 8601 week-numbering year (001-371; day 1 of the year is Monday of the first ISO week)</entry>
6020 <entry><literal>DD</literal></entry>
6021 <entry>day of month (01-31)</entry>
6024 <entry><literal>D</literal></entry>
6025 <entry>day of the week, Sunday (<literal>1</>) to Saturday (<literal>7</>)</entry>
6028 <entry><literal>ID</literal></entry>
6029 <entry>ISO 8601 day of the week, Monday (<literal>1</>) to Sunday (<literal>7</>)</entry>
6032 <entry><literal>W</literal></entry>
6033 <entry>week of month (1-5) (the first week starts on the first day of the month)</entry>
6036 <entry><literal>WW</literal></entry>
6037 <entry>week number of year (1-53) (the first week starts on the first day of the year)</entry>
6040 <entry><literal>IW</literal></entry>
6041 <entry>week number of ISO 8601 week-numbering year (01-53; the first Thursday of the year is in week 1)</entry>
6044 <entry><literal>CC</literal></entry>
6045 <entry>century (2 digits) (the twenty-first century starts on 2001-01-01)</entry>
6048 <entry><literal>J</literal></entry>
6049 <entry>Julian Day (integer days since November 24, 4714 BC at midnight UTC)</entry>
6052 <entry><literal>Q</literal></entry>
6053 <entry>quarter</entry>
6056 <entry><literal>RM</literal></entry>
6057 <entry>month in upper case Roman numerals (I-XII; I=January)</entry>
6060 <entry><literal>rm</literal></entry>
6061 <entry>month in lower case Roman numerals (i-xii; i=January)</entry>
6064 <entry><literal>TZ</literal></entry>
6065 <entry>upper case time-zone abbreviation
6066 (only supported in <function>to_char</>)</entry>
6069 <entry><literal>tz</literal></entry>
6070 <entry>lower case time-zone abbreviation
6071 (only supported in <function>to_char</>)</entry>
6074 <entry><literal>OF</literal></entry>
6075 <entry>time-zone offset from UTC
6076 (only supported in <function>to_char</>)</entry>
6083 Modifiers can be applied to any template pattern to alter its
6084 behavior. For example, <literal>FMMonth</literal>
6085 is the <literal>Month</literal> pattern with the
6086 <literal>FM</literal> modifier.
6087 <xref linkend="functions-formatting-datetimemod-table"> shows the
6088 modifier patterns for date/time formatting.
6091 <table id="functions-formatting-datetimemod-table">
6092 <title>Template Pattern Modifiers for Date/Time Formatting</title>
6096 <entry>Modifier</entry>
6097 <entry>Description</entry>
6098 <entry>Example</entry>
6103 <entry><literal>FM</literal> prefix</entry>
6104 <entry>fill mode (suppress leading zeroes and padding blanks)</entry>
6105 <entry><literal>FMMonth</literal></entry>
6108 <entry><literal>TH</literal> suffix</entry>
6109 <entry>upper case ordinal number suffix</entry>
6110 <entry><literal>DDTH</literal>, e.g., <literal>12TH</></entry>
6113 <entry><literal>th</literal> suffix</entry>
6114 <entry>lower case ordinal number suffix</entry>
6115 <entry><literal>DDth</literal>, e.g., <literal>12th</></entry>
6118 <entry><literal>FX</literal> prefix</entry>
6119 <entry>fixed format global option (see usage notes)</entry>
6120 <entry><literal>FX Month DD Day</literal></entry>
6123 <entry><literal>TM</literal> prefix</entry>
6124 <entry>translation mode (print localized day and month names based on
6125 <xref linkend="guc-lc-time">)</entry>
6126 <entry><literal>TMMonth</literal></entry>
6129 <entry><literal>SP</literal> suffix</entry>
6130 <entry>spell mode (not implemented)</entry>
6131 <entry><literal>DDSP</literal></entry>
6138 Usage notes for date/time formatting:
6143 <literal>FM</literal> suppresses leading zeroes and trailing blanks
6144 that would otherwise be added to make the output of a pattern be
6145 fixed-width. In <productname>PostgreSQL</productname>,
6146 <literal>FM</literal> modifies only the next specification, while in
6147 Oracle <literal>FM</literal> affects all subsequent
6148 specifications, and repeated <literal>FM</literal> modifiers
6149 toggle fill mode on and off.
6155 <literal>TM</literal> does not include trailing blanks.
6156 <function>to_timestamp</> and <function>to_date</> ignore
6157 the <literal>TM</literal> modifier.
6163 <function>to_timestamp</function> and <function>to_date</function>
6164 skip multiple blank spaces in the input string unless the
6165 <literal>FX</literal> option is used. For example,
6166 <literal>to_timestamp('2000 JUN', 'YYYY MON')</literal> works, but
6167 <literal>to_timestamp('2000 JUN', 'FXYYYY MON')</literal> returns an error
6168 because <function>to_timestamp</function> expects one space only.
6169 <literal>FX</literal> must be specified as the first item in
6176 Ordinary text is allowed in <function>to_char</function>
6177 templates and will be output literally. You can put a substring
6178 in double quotes to force it to be interpreted as literal text
6179 even if it contains pattern key words. For example, in
6180 <literal>'"Hello Year "YYYY'</literal>, the <literal>YYYY</literal>
6181 will be replaced by the year data, but the single <literal>Y</literal> in <literal>Year</literal>
6182 will not be. In <function>to_date</>, <function>to_number</>,
6183 and <function>to_timestamp</>, double-quoted strings skip the number of
6184 input characters contained in the string, e.g. <literal>"XX"</>
6185 skips two input characters.
6191 If you want to have a double quote in the output you must
6192 precede it with a backslash, for example <literal>'\"YYYY
6193 Month\"'</literal>. <!-- "" font-lock sanity :-) -->
6199 In <function>to_timestamp</function> and <function>to_date</function>,
6200 if the year format specification is less than four digits, e.g.
6201 <literal>YYY</>, and the supplied year is less than four digits,
6202 the year will be adjusted to be nearest to the year 2020, e.g.
6203 <literal>95</> becomes 1995.
6209 In <function>to_timestamp</function> and <function>to_date</function>,
6210 the <literal>YYYY</literal> conversion has a restriction when
6211 processing years with more than 4 digits. You must
6212 use some non-digit character or template after <literal>YYYY</literal>,
6213 otherwise the year is always interpreted as 4 digits. For example
6214 (with the year 20000):
6215 <literal>to_date('200001131', 'YYYYMMDD')</literal> will be
6216 interpreted as a 4-digit year; instead use a non-digit
6217 separator after the year, like
6218 <literal>to_date('20000-1131', 'YYYY-MMDD')</literal> or
6219 <literal>to_date('20000Nov31', 'YYYYMonDD')</literal>.
6225 In <function>to_timestamp</function> and <function>to_date</function>,
6226 the <literal>CC</literal> (century) field is accepted but ignored
6227 if there is a <literal>YYY</literal>, <literal>YYYY</literal> or
6228 <literal>Y,YYY</literal> field. If <literal>CC</literal> is used with
6229 <literal>YY</literal> or <literal>Y</literal> then the result is
6230 computed as that year in the specified century. If the century is
6231 specified but the year is not, the first year of the century
6238 In <function>to_timestamp</function> and <function>to_date</function>,
6239 weekday names or numbers (<literal>DAY</literal>, <literal>D</literal>,
6240 and related field types) are accepted but are ignored for purposes of
6241 computing the result. The same is true for quarter
6242 (<literal>Q</literal>) fields.
6248 In <function>to_timestamp</function> and <function>to_date</function>,
6249 an ISO 8601 week-numbering date (as distinct from a Gregorian date)
6250 can be specified in one of two ways:
6254 Year, week number, and weekday: for
6255 example <literal>to_date('2006-42-4', 'IYYY-IW-ID')</literal>
6256 returns the date <literal>2006-10-19</literal>.
6257 If you omit the weekday it is assumed to be 1 (Monday).
6262 Year and day of year: for example <literal>to_date('2006-291',
6263 'IYYY-IDDD')</literal> also returns <literal>2006-10-19</literal>.
6269 Attempting to enter a date using a mixture of ISO 8601 week-numbering
6270 fields and Gregorian date fields is nonsensical, and will cause an
6271 error. In the context of an ISO 8601 week-numbering year, the
6272 concept of a <quote>month</> or <quote>day of month</> has no
6273 meaning. In the context of a Gregorian year, the ISO week has no
6278 While <function>to_date</function> will reject a mixture of
6279 Gregorian and ISO week-numbering date
6280 fields, <function>to_char</function> will not, since output format
6281 specifications like <literal>YYYY-MM-DD (IYYY-IDDD)</> can be
6282 useful. But avoid writing something like <literal>IYYY-MM-DD</>;
6283 that would yield surprising results near the start of the year.
6284 (See <xref linkend="functions-datetime-extract"> for more
6292 In <function>to_timestamp</function>, millisecond
6293 (<literal>MS</literal>) or microsecond (<literal>US</literal>)
6294 fields are used as the
6295 seconds digits after the decimal point. For example
6296 <literal>to_timestamp('12.3', 'SS.MS')</literal> is not 3 milliseconds,
6297 but 300, because the conversion treats it as 12 + 0.3 seconds.
6298 So, for the format <literal>SS.MS</literal>, the input values
6299 <literal>12.3</literal>, <literal>12.30</literal>,
6300 and <literal>12.300</literal> specify the
6301 same number of milliseconds. To get three milliseconds, one must write
6302 <literal>12.003</literal>, which the conversion treats as
6303 12 + 0.003 = 12.003 seconds.
6309 <literal>to_timestamp('15:12:02.020.001230', 'HH24:MI:SS.MS.US')</literal>
6310 is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds +
6311 1230 microseconds = 2.021230 seconds.
6317 <function>to_char(..., 'ID')</function>'s day of the week numbering
6318 matches the <function>extract(isodow from ...)</function> function, but
6319 <function>to_char(..., 'D')</function>'s does not match
6320 <function>extract(dow from ...)</function>'s day numbering.
6326 <function>to_char(interval)</function> formats <literal>HH</> and
6327 <literal>HH12</> as shown on a 12-hour clock, for example zero hours
6328 and 36 hours both output as <literal>12</>, while <literal>HH24</>
6329 outputs the full hour value, which can exceed 23 in
6330 an <type>interval</> value.
6338 <xref linkend="functions-formatting-numeric-table"> shows the
6339 template patterns available for formatting numeric values.
6342 <table id="functions-formatting-numeric-table">
6343 <title>Template Patterns for Numeric Formatting</title>
6347 <entry>Pattern</entry>
6348 <entry>Description</entry>
6353 <entry><literal>9</literal></entry>
6354 <entry>value with the specified number of digits</entry>
6357 <entry><literal>0</literal></entry>
6358 <entry>value with leading zeros</entry>
6361 <entry><literal>.</literal> (period)</entry>
6362 <entry>decimal point</entry>
6365 <entry><literal>,</literal> (comma)</entry>
6366 <entry>group (thousand) separator</entry>
6369 <entry><literal>PR</literal></entry>
6370 <entry>negative value in angle brackets</entry>
6373 <entry><literal>S</literal></entry>
6374 <entry>sign anchored to number (uses locale)</entry>
6377 <entry><literal>L</literal></entry>
6378 <entry>currency symbol (uses locale)</entry>
6381 <entry><literal>D</literal></entry>
6382 <entry>decimal point (uses locale)</entry>
6385 <entry><literal>G</literal></entry>
6386 <entry>group separator (uses locale)</entry>
6389 <entry><literal>MI</literal></entry>
6390 <entry>minus sign in specified position (if number < 0)</entry>
6393 <entry><literal>PL</literal></entry>
6394 <entry>plus sign in specified position (if number > 0)</entry>
6397 <entry><literal>SG</literal></entry>
6398 <entry>plus/minus sign in specified position</entry>
6401 <entry><literal>RN</literal></entry>
6402 <entry>Roman numeral (input between 1 and 3999)</entry>
6405 <entry><literal>TH</literal> or <literal>th</literal></entry>
6406 <entry>ordinal number suffix</entry>
6409 <entry><literal>V</literal></entry>
6410 <entry>shift specified number of digits (see notes)</entry>
6413 <entry><literal>EEEE</literal></entry>
6414 <entry>exponent for scientific notation</entry>
6421 Usage notes for numeric formatting:
6426 A sign formatted using <literal>SG</literal>, <literal>PL</literal>, or
6427 <literal>MI</literal> is not anchored to
6428 the number; for example,
6429 <literal>to_char(-12, 'MI9999')</literal> produces <literal>'- 12'</literal>
6430 but <literal>to_char(-12, 'S9999')</literal> produces <literal>' -12'</literal>.
6431 The Oracle implementation does not allow the use of
6432 <literal>MI</literal> before <literal>9</literal>, but rather
6433 requires that <literal>9</literal> precede
6434 <literal>MI</literal>.
6440 <literal>9</literal> results in a value with the same number of
6441 digits as there are <literal>9</literal>s. If a digit is
6442 not available it outputs a space.
6448 <literal>TH</literal> does not convert values less than zero
6449 and does not convert fractional numbers.
6455 <literal>PL</literal>, <literal>SG</literal>, and
6456 <literal>TH</literal> are <productname>PostgreSQL</productname>
6463 <literal>V</literal> with <function>to_char</function>
6464 multiplies the input values by
6465 <literal>10^<replaceable>n</replaceable></literal>, where
6466 <replaceable>n</replaceable> is the number of digits following
6467 <literal>V</literal>. <literal>V</literal> with
6468 <function>to_number</function> divides in a similar manner.
6469 <function>to_char</function> and <function>to_number</function>
6470 do not support the use of
6471 <literal>V</literal> combined with a decimal point
6472 (e.g., <literal>99.9V99</literal> is not allowed).
6478 <literal>EEEE</literal> (scientific notation) cannot be used in
6479 combination with any of the other formatting patterns or
6480 modifiers other than digit and decimal point patterns, and must be at the end of the format string
6481 (e.g., <literal>9.99EEEE</literal> is a valid pattern).
6488 Certain modifiers can be applied to any template pattern to alter its
6489 behavior. For example, <literal>FM9999</literal>
6490 is the <literal>9999</literal> pattern with the
6491 <literal>FM</literal> modifier.
6492 <xref linkend="functions-formatting-numericmod-table"> shows the
6493 modifier patterns for numeric formatting.
6496 <table id="functions-formatting-numericmod-table">
6497 <title>Template Pattern Modifiers for Numeric Formatting</title>
6501 <entry>Modifier</entry>
6502 <entry>Description</entry>
6503 <entry>Example</entry>
6508 <entry><literal>FM</literal> prefix</entry>
6509 <entry>fill mode (suppress leading zeroes and padding blanks)</entry>
6510 <entry><literal>FM9999</literal></entry>
6513 <entry><literal>TH</literal> suffix</entry>
6514 <entry>upper case ordinal number suffix</entry>
6515 <entry><literal>999TH</literal></entry>
6518 <entry><literal>th</literal> suffix</entry>
6519 <entry>lower case ordinal number suffix</entry>
6520 <entry><literal>999th</literal></entry>
6527 <xref linkend="functions-formatting-examples-table"> shows some
6528 examples of the use of the <function>to_char</function> function.
6531 <table id="functions-formatting-examples-table">
6532 <title><function>to_char</function> Examples</title>
6536 <entry>Expression</entry>
6537 <entry>Result</entry>
6542 <entry><literal>to_char(current_timestamp, 'Day, DD HH12:MI:SS')</literal></entry>
6543 <entry><literal>'Tuesday , 06 05:39:18'</literal></entry>
6546 <entry><literal>to_char(current_timestamp, 'FMDay, FMDD HH12:MI:SS')</literal></entry>
6547 <entry><literal>'Tuesday, 6 05:39:18'</literal></entry>
6550 <entry><literal>to_char(-0.1, '99.99')</literal></entry>
6551 <entry><literal>' -.10'</literal></entry>
6554 <entry><literal>to_char(-0.1, 'FM9.99')</literal></entry>
6555 <entry><literal>'-.1'</literal></entry>
6558 <entry><literal>to_char(0.1, '0.9')</literal></entry>
6559 <entry><literal>' 0.1'</literal></entry>
6562 <entry><literal>to_char(12, '9990999.9')</literal></entry>
6563 <entry><literal>' 0012.0'</literal></entry>
6566 <entry><literal>to_char(12, 'FM9990999.9')</literal></entry>
6567 <entry><literal>'0012.'</literal></entry>
6570 <entry><literal>to_char(485, '999')</literal></entry>
6571 <entry><literal>' 485'</literal></entry>
6574 <entry><literal>to_char(-485, '999')</literal></entry>
6575 <entry><literal>'-485'</literal></entry>
6578 <entry><literal>to_char(485, '9 9 9')</literal></entry>
6579 <entry><literal>' 4 8 5'</literal></entry>
6582 <entry><literal>to_char(1485, '9,999')</literal></entry>
6583 <entry><literal>' 1,485'</literal></entry>
6586 <entry><literal>to_char(1485, '9G999')</literal></entry>
6587 <entry><literal>' 1 485'</literal></entry>
6590 <entry><literal>to_char(148.5, '999.999')</literal></entry>
6591 <entry><literal>' 148.500'</literal></entry>
6594 <entry><literal>to_char(148.5, 'FM999.999')</literal></entry>
6595 <entry><literal>'148.5'</literal></entry>
6598 <entry><literal>to_char(148.5, 'FM999.990')</literal></entry>
6599 <entry><literal>'148.500'</literal></entry>
6602 <entry><literal>to_char(148.5, '999D999')</literal></entry>
6603 <entry><literal>' 148,500'</literal></entry>
6606 <entry><literal>to_char(3148.5, '9G999D999')</literal></entry>
6607 <entry><literal>' 3 148,500'</literal></entry>
6610 <entry><literal>to_char(-485, '999S')</literal></entry>
6611 <entry><literal>'485-'</literal></entry>
6614 <entry><literal>to_char(-485, '999MI')</literal></entry>
6615 <entry><literal>'485-'</literal></entry>
6618 <entry><literal>to_char(485, '999MI')</literal></entry>
6619 <entry><literal>'485 '</literal></entry>
6622 <entry><literal>to_char(485, 'FM999MI')</literal></entry>
6623 <entry><literal>'485'</literal></entry>
6626 <entry><literal>to_char(485, 'PL999')</literal></entry>
6627 <entry><literal>'+485'</literal></entry>
6630 <entry><literal>to_char(485, 'SG999')</literal></entry>
6631 <entry><literal>'+485'</literal></entry>
6634 <entry><literal>to_char(-485, 'SG999')</literal></entry>
6635 <entry><literal>'-485'</literal></entry>
6638 <entry><literal>to_char(-485, '9SG99')</literal></entry>
6639 <entry><literal>'4-85'</literal></entry>
6642 <entry><literal>to_char(-485, '999PR')</literal></entry>
6643 <entry><literal>'<485>'</literal></entry>
6646 <entry><literal>to_char(485, 'L999')</literal></entry>
6647 <entry><literal>'DM 485'</literal></entry>
6650 <entry><literal>to_char(485, 'RN')</literal></entry>
6651 <entry><literal>' CDLXXXV'</literal></entry>
6654 <entry><literal>to_char(485, 'FMRN')</literal></entry>
6655 <entry><literal>'CDLXXXV'</literal></entry>
6658 <entry><literal>to_char(5.2, 'FMRN')</literal></entry>
6659 <entry><literal>'V'</literal></entry>
6662 <entry><literal>to_char(482, '999th')</literal></entry>
6663 <entry><literal>' 482nd'</literal></entry>
6666 <entry><literal>to_char(485, '"Good number:"999')</literal></entry>
6667 <entry><literal>'Good number: 485'</literal></entry>
6670 <entry><literal>to_char(485.8, '"Pre:"999" Post:" .999')</literal></entry>
6671 <entry><literal>'Pre: 485 Post: .800'</literal></entry>
6674 <entry><literal>to_char(12, '99V999')</literal></entry>
6675 <entry><literal>' 12000'</literal></entry>
6678 <entry><literal>to_char(12.4, '99V999')</literal></entry>
6679 <entry><literal>' 12400'</literal></entry>
6682 <entry><literal>to_char(12.45, '99V9')</literal></entry>
6683 <entry><literal>' 125'</literal></entry>
6686 <entry><literal>to_char(0.0004859, '9.99EEEE')</literal></entry>
6687 <entry><literal>' 4.86e-04'</literal></entry>
6696 <sect1 id="functions-datetime">
6697 <title>Date/Time Functions and Operators</title>
6700 <xref linkend="functions-datetime-table"> shows the available
6701 functions for date/time value processing, with details appearing in
6702 the following subsections. <xref
6703 linkend="operators-datetime-table"> illustrates the behaviors of
6704 the basic arithmetic operators (<literal>+</literal>,
6705 <literal>*</literal>, etc.). For formatting functions, refer to
6706 <xref linkend="functions-formatting">. You should be familiar with
6707 the background information on date/time data types from <xref
6708 linkend="datatype-datetime">.
6712 All the functions and operators described below that take <type>time</type> or <type>timestamp</type>
6713 inputs actually come in two variants: one that takes <type>time with time zone</type> or <type>timestamp
6714 with time zone</type>, and one that takes <type>time without time zone</type> or <type>timestamp without time zone</type>.
6715 For brevity, these variants are not shown separately. Also, the
6716 <literal>+</> and <literal>*</> operators come in commutative pairs (for
6717 example both date + integer and integer + date); we show only one of each
6721 <table id="operators-datetime-table">
6722 <title>Date/Time Operators</title>
6727 <entry>Operator</entry>
6728 <entry>Example</entry>
6729 <entry>Result</entry>
6735 <entry> <literal>+</literal> </entry>
6736 <entry><literal>date '2001-09-28' + integer '7'</literal></entry>
6737 <entry><literal>date '2001-10-05'</literal></entry>
6741 <entry> <literal>+</literal> </entry>
6742 <entry><literal>date '2001-09-28' + interval '1 hour'</literal></entry>
6743 <entry><literal>timestamp '2001-09-28 01:00:00'</literal></entry>
6747 <entry> <literal>+</literal> </entry>
6748 <entry><literal>date '2001-09-28' + time '03:00'</literal></entry>
6749 <entry><literal>timestamp '2001-09-28 03:00:00'</literal></entry>
6753 <entry> <literal>+</literal> </entry>
6754 <entry><literal>interval '1 day' + interval '1 hour'</literal></entry>
6755 <entry><literal>interval '1 day 01:00:00'</literal></entry>
6759 <entry> <literal>+</literal> </entry>
6760 <entry><literal>timestamp '2001-09-28 01:00' + interval '23 hours'</literal></entry>
6761 <entry><literal>timestamp '2001-09-29 00:00:00'</literal></entry>
6765 <entry> <literal>+</literal> </entry>
6766 <entry><literal>time '01:00' + interval '3 hours'</literal></entry>
6767 <entry><literal>time '04:00:00'</literal></entry>
6771 <entry> <literal>-</literal> </entry>
6772 <entry><literal>- interval '23 hours'</literal></entry>
6773 <entry><literal>interval '-23:00:00'</literal></entry>
6777 <entry> <literal>-</literal> </entry>
6778 <entry><literal>date '2001-10-01' - date '2001-09-28'</literal></entry>
6779 <entry><literal>integer '3'</literal> (days)</entry>
6783 <entry> <literal>-</literal> </entry>
6784 <entry><literal>date '2001-10-01' - integer '7'</literal></entry>
6785 <entry><literal>date '2001-09-24'</literal></entry>
6789 <entry> <literal>-</literal> </entry>
6790 <entry><literal>date '2001-09-28' - interval '1 hour'</literal></entry>
6791 <entry><literal>timestamp '2001-09-27 23:00:00'</literal></entry>
6795 <entry> <literal>-</literal> </entry>
6796 <entry><literal>time '05:00' - time '03:00'</literal></entry>
6797 <entry><literal>interval '02:00:00'</literal></entry>
6801 <entry> <literal>-</literal> </entry>
6802 <entry><literal>time '05:00' - interval '2 hours'</literal></entry>
6803 <entry><literal>time '03:00:00'</literal></entry>
6807 <entry> <literal>-</literal> </entry>
6808 <entry><literal>timestamp '2001-09-28 23:00' - interval '23 hours'</literal></entry>
6809 <entry><literal>timestamp '2001-09-28 00:00:00'</literal></entry>
6813 <entry> <literal>-</literal> </entry>
6814 <entry><literal>interval '1 day' - interval '1 hour'</literal></entry>
6815 <entry><literal>interval '1 day -01:00:00'</literal></entry>
6819 <entry> <literal>-</literal> </entry>
6820 <entry><literal>timestamp '2001-09-29 03:00' - timestamp '2001-09-27 12:00'</literal></entry>
6821 <entry><literal>interval '1 day 15:00:00'</literal></entry>
6825 <entry> <literal>*</literal> </entry>
6826 <entry><literal>900 * interval '1 second'</literal></entry>
6827 <entry><literal>interval '00:15:00'</literal></entry>
6831 <entry> <literal>*</literal> </entry>
6832 <entry><literal>21 * interval '1 day'</literal></entry>
6833 <entry><literal>interval '21 days'</literal></entry>
6837 <entry> <literal>*</literal> </entry>
6838 <entry><literal>double precision '3.5' * interval '1 hour'</literal></entry>
6839 <entry><literal>interval '03:30:00'</literal></entry>
6843 <entry> <literal>/</literal> </entry>
6844 <entry><literal>interval '1 hour' / double precision '1.5'</literal></entry>
6845 <entry><literal>interval '00:40:00'</literal></entry>
6851 <table id="functions-datetime-table">
6852 <title>Date/Time Functions</title>
6856 <entry>Function</entry>
6857 <entry>Return Type</entry>
6858 <entry>Description</entry>
6859 <entry>Example</entry>
6860 <entry>Result</entry>
6868 <primary>age</primary>
6870 <literal><function>age(<type>timestamp</type>, <type>timestamp</type>)</function></literal>
6872 <entry><type>interval</type></entry>
6873 <entry>Subtract arguments, producing a <quote>symbolic</> result that
6874 uses years and months, rather than just days</entry>
6875 <entry><literal>age(timestamp '2001-04-10', timestamp '1957-06-13')</literal></entry>
6876 <entry><literal>43 years 9 mons 27 days</literal></entry>
6880 <entry><literal><function>age(<type>timestamp</type>)</function></literal></entry>
6881 <entry><type>interval</type></entry>
6882 <entry>Subtract from <function>current_date</function> (at midnight)</entry>
6883 <entry><literal>age(timestamp '1957-06-13')</literal></entry>
6884 <entry><literal>43 years 8 mons 3 days</literal></entry>
6890 <primary>clock_timestamp</primary>
6892 <literal><function>clock_timestamp()</function></literal>
6894 <entry><type>timestamp with time zone</type></entry>
6895 <entry>Current date and time (changes during statement execution);
6896 see <xref linkend="functions-datetime-current">
6905 <primary>current_date</primary>
6907 <literal><function>current_date</function></literal>
6909 <entry><type>date</type></entry>
6910 <entry>Current date;
6911 see <xref linkend="functions-datetime-current">
6920 <primary>current_time</primary>
6922 <literal><function>current_time</function></literal>
6924 <entry><type>time with time zone</type></entry>
6925 <entry>Current time of day;
6926 see <xref linkend="functions-datetime-current">
6935 <primary>current_timestamp</primary>
6937 <literal><function>current_timestamp</function></literal>
6939 <entry><type>timestamp with time zone</type></entry>
6940 <entry>Current date and time (start of current transaction);
6941 see <xref linkend="functions-datetime-current">
6950 <primary>date_part</primary>
6952 <literal><function>date_part(<type>text</type>, <type>timestamp</type>)</function></literal>
6954 <entry><type>double precision</type></entry>
6955 <entry>Get subfield (equivalent to <function>extract</function>);
6956 see <xref linkend="functions-datetime-extract">
6958 <entry><literal>date_part('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
6959 <entry><literal>20</literal></entry>
6963 <entry><literal><function>date_part(<type>text</type>, <type>interval</type>)</function></literal></entry>
6964 <entry><type>double precision</type></entry>
6965 <entry>Get subfield (equivalent to
6966 <function>extract</function>); see <xref linkend="functions-datetime-extract">
6968 <entry><literal>date_part('month', interval '2 years 3 months')</literal></entry>
6969 <entry><literal>3</literal></entry>
6975 <primary>date_trunc</primary>
6977 <literal><function>date_trunc(<type>text</type>, <type>timestamp</type>)</function></literal>
6979 <entry><type>timestamp</type></entry>
6980 <entry>Truncate to specified precision; see also <xref linkend="functions-datetime-trunc">
6982 <entry><literal>date_trunc('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
6983 <entry><literal>2001-02-16 20:00:00</literal></entry>
6987 <entry><literal><function>date_trunc(<type>text</type>, <type>interval</type>)</function></literal></entry>
6988 <entry><type>interval</type></entry>
6989 <entry>Truncate to specified precision; see also <xref linkend="functions-datetime-trunc">
6991 <entry><literal>date_trunc('hour', interval '2 days 3 hours 40 minutes')</literal></entry>
6992 <entry><literal>2 days 03:00:00</literal></entry>
6998 <primary>extract</primary>
7000 <literal><function>extract</function>(<parameter>field</parameter> from
7001 <type>timestamp</type>)</literal>
7003 <entry><type>double precision</type></entry>
7004 <entry>Get subfield; see <xref linkend="functions-datetime-extract">
7006 <entry><literal>extract(hour from timestamp '2001-02-16 20:38:40')</literal></entry>
7007 <entry><literal>20</literal></entry>
7011 <entry><literal><function>extract</function>(<parameter>field</parameter> from
7012 <type>interval</type>)</literal></entry>
7013 <entry><type>double precision</type></entry>
7014 <entry>Get subfield; see <xref linkend="functions-datetime-extract">
7016 <entry><literal>extract(month from interval '2 years 3 months')</literal></entry>
7017 <entry><literal>3</literal></entry>
7023 <primary>isfinite</primary>
7025 <literal><function>isfinite(<type>date</type>)</function></literal>
7027 <entry><type>boolean</type></entry>
7028 <entry>Test for finite date (not +/-infinity)</entry>
7029 <entry><literal>isfinite(date '2001-02-16')</literal></entry>
7030 <entry><literal>true</literal></entry>
7034 <entry><literal><function>isfinite(<type>timestamp</type>)</function></literal></entry>
7035 <entry><type>boolean</type></entry>
7036 <entry>Test for finite time stamp (not +/-infinity)</entry>
7037 <entry><literal>isfinite(timestamp '2001-02-16 21:28:30')</literal></entry>
7038 <entry><literal>true</literal></entry>
7042 <entry><literal><function>isfinite(<type>interval</type>)</function></literal></entry>
7043 <entry><type>boolean</type></entry>
7044 <entry>Test for finite interval</entry>
7045 <entry><literal>isfinite(interval '4 hours')</literal></entry>
7046 <entry><literal>true</literal></entry>
7052 <primary>justify_days</primary>
7054 <literal><function>justify_days(<type>interval</type>)</function></literal>
7056 <entry><type>interval</type></entry>
7057 <entry>Adjust interval so 30-day time periods are represented as months</entry>
7058 <entry><literal>justify_days(interval '35 days')</literal></entry>
7059 <entry><literal>1 mon 5 days</literal></entry>
7065 <primary>justify_hours</primary>
7067 <literal><function>justify_hours(<type>interval</type>)</function></literal>
7069 <entry><type>interval</type></entry>
7070 <entry>Adjust interval so 24-hour time periods are represented as days</entry>
7071 <entry><literal>justify_hours(interval '27 hours')</literal></entry>
7072 <entry><literal>1 day 03:00:00</literal></entry>
7078 <primary>justify_interval</primary>
7080 <literal><function>justify_interval(<type>interval</type>)</function></literal>
7082 <entry><type>interval</type></entry>
7083 <entry>Adjust interval using <function>justify_days</> and <function>justify_hours</>, with additional sign adjustments</entry>
7084 <entry><literal>justify_interval(interval '1 mon -1 hour')</literal></entry>
7085 <entry><literal>29 days 23:00:00</literal></entry>
7091 <primary>localtime</primary>
7093 <literal><function>localtime</function></literal>
7095 <entry><type>time</type></entry>
7096 <entry>Current time of day;
7097 see <xref linkend="functions-datetime-current">
7106 <primary>localtimestamp</primary>
7108 <literal><function>localtimestamp</function></literal>
7110 <entry><type>timestamp</type></entry>
7111 <entry>Current date and time (start of current transaction);
7112 see <xref linkend="functions-datetime-current">
7121 <primary>make_date</primary>
7125 make_date(<parameter>year</parameter> <type>int</type>,
7126 <parameter>month</parameter> <type>int</type>,
7127 <parameter>day</parameter> <type>int</type>)
7131 <entry><type>date</type></entry>
7133 Create date from year, month and day fields
7135 <entry><literal>make_date(2013, 7, 15)</literal></entry>
7136 <entry><literal>2013-07-15</literal></entry>
7142 <primary>make_interval</primary>
7146 make_interval(<parameter>years</parameter> <type>int</type> DEFAULT 0,
7147 <parameter>months</parameter> <type>int</type> DEFAULT 0,
7148 <parameter>weeks</parameter> <type>int</type> DEFAULT 0,
7149 <parameter>days</parameter> <type>int</type> DEFAULT 0,
7150 <parameter>hours</parameter> <type>int</type> DEFAULT 0,
7151 <parameter>mins</parameter> <type>int</type> DEFAULT 0,
7152 <parameter>secs</parameter> <type>double precision</type> DEFAULT 0.0)
7156 <entry><type>interval</type></entry>
7158 Create interval from years, months, weeks, days, hours, minutes and
7161 <entry><literal>make_interval(days => 10)</literal></entry>
7162 <entry><literal>10 days</literal></entry>
7168 <primary>make_time</primary>
7172 make_time(<parameter>hour</parameter> <type>int</type>,
7173 <parameter>min</parameter> <type>int</type>,
7174 <parameter>sec</parameter> <type>double precision</type>)
7178 <entry><type>time</type></entry>
7180 Create time from hour, minute and seconds fields
7182 <entry><literal>make_time(8, 15, 23.5)</literal></entry>
7183 <entry><literal>08:15:23.5</literal></entry>
7189 <primary>make_timestamp</primary>
7193 make_timestamp(<parameter>year</parameter> <type>int</type>,
7194 <parameter>month</parameter> <type>int</type>,
7195 <parameter>day</parameter> <type>int</type>,
7196 <parameter>hour</parameter> <type>int</type>,
7197 <parameter>min</parameter> <type>int</type>,
7198 <parameter>sec</parameter> <type>double precision</type>)
7202 <entry><type>timestamp</type></entry>
7204 Create timestamp from year, month, day, hour, minute and seconds fields
7206 <entry><literal>make_timestamp(2013, 7, 15, 8, 15, 23.5)</literal></entry>
7207 <entry><literal>2013-07-15 08:15:23.5</literal></entry>
7213 <primary>make_timestamptz</primary>
7217 make_timestamptz(<parameter>year</parameter> <type>int</type>,
7218 <parameter>month</parameter> <type>int</type>,
7219 <parameter>day</parameter> <type>int</type>,
7220 <parameter>hour</parameter> <type>int</type>,
7221 <parameter>min</parameter> <type>int</type>,
7222 <parameter>sec</parameter> <type>double precision</type>,
7223 <optional> <parameter>timezone</parameter> <type>text</type> </optional>)
7227 <entry><type>timestamp with time zone</type></entry>
7229 Create timestamp with time zone from year, month, day, hour, minute
7230 and seconds fields; if <parameter>timezone</parameter> is not
7231 specified, the current time zone is used
7233 <entry><literal>make_timestamptz(2013, 7, 15, 8, 15, 23.5)</literal></entry>
7234 <entry><literal>2013-07-15 08:15:23.5+01</literal></entry>
7240 <primary>now</primary>
7242 <literal><function>now()</function></literal>
7244 <entry><type>timestamp with time zone</type></entry>
7245 <entry>Current date and time (start of current transaction);
7246 see <xref linkend="functions-datetime-current">
7255 <primary>statement_timestamp</primary>
7257 <literal><function>statement_timestamp()</function></literal>
7259 <entry><type>timestamp with time zone</type></entry>
7260 <entry>Current date and time (start of current statement);
7261 see <xref linkend="functions-datetime-current">
7270 <primary>timeofday</primary>
7272 <literal><function>timeofday()</function></literal>
7274 <entry><type>text</type></entry>
7275 <entry>Current date and time
7276 (like <function>clock_timestamp</>, but as a <type>text</> string);
7277 see <xref linkend="functions-datetime-current">
7286 <primary>transaction_timestamp</primary>
7288 <literal><function>transaction_timestamp()</function></literal>
7290 <entry><type>timestamp with time zone</type></entry>
7291 <entry>Current date and time (start of current transaction);
7292 see <xref linkend="functions-datetime-current">
7300 <primary>to_timestamp</primary>
7302 <literal><function>to_timestamp(<type>double precision</type>)</function></literal>
7304 <entry><type>timestamp with time zone</type></entry>
7305 <entry>Convert Unix epoch (seconds since 1970-01-01 00:00:00+00) to
7307 <entry><literal>to_timestamp(1284352323)</literal></entry>
7308 <entry><literal>2010-09-13 04:32:03+00</literal></entry>
7316 <primary>OVERLAPS</primary>
7318 In addition to these functions, the SQL <literal>OVERLAPS</> operator is
7321 (<replaceable>start1</replaceable>, <replaceable>end1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>end2</replaceable>)
7322 (<replaceable>start1</replaceable>, <replaceable>length1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>length2</replaceable>)
7324 This expression yields true when two time periods (defined by their
7325 endpoints) overlap, false when they do not overlap. The endpoints
7326 can be specified as pairs of dates, times, or time stamps; or as
7327 a date, time, or time stamp followed by an interval. When a pair
7328 of values is provided, either the start or the end can be written
7329 first; <literal>OVERLAPS</> automatically takes the earlier value
7330 of the pair as the start. Each time period is considered to
7331 represent the half-open interval <replaceable>start</> <literal><=</>
7332 <replaceable>time</> <literal><</> <replaceable>end</>, unless
7333 <replaceable>start</> and <replaceable>end</> are equal in which case it
7334 represents that single time instant. This means for instance that two
7335 time periods with only an endpoint in common do not overlap.
7339 SELECT (DATE '2001-02-16', DATE '2001-12-21') OVERLAPS
7340 (DATE '2001-10-30', DATE '2002-10-30');
7341 <lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
7342 SELECT (DATE '2001-02-16', INTERVAL '100 days') OVERLAPS
7343 (DATE '2001-10-30', DATE '2002-10-30');
7344 <lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
7345 SELECT (DATE '2001-10-29', DATE '2001-10-30') OVERLAPS
7346 (DATE '2001-10-30', DATE '2001-10-31');
7347 <lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
7348 SELECT (DATE '2001-10-30', DATE '2001-10-30') OVERLAPS
7349 (DATE '2001-10-30', DATE '2001-10-31');
7350 <lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
7354 When adding an <type>interval</type> value to (or subtracting an
7355 <type>interval</type> value from) a <type>timestamp with time zone</type>
7356 value, the days component advances or decrements the date of the
7357 <type>timestamp with time zone</type> by the indicated number of days.
7358 Across daylight saving time changes (when the session time zone is set to a
7359 time zone that recognizes DST), this means <literal>interval '1 day'</literal>
7360 does not necessarily equal <literal>interval '24 hours'</literal>.
7361 For example, with the session time zone set to <literal>CST7CDT</literal>,
7362 <literal>timestamp with time zone '2005-04-02 12:00-07' + interval '1 day'</literal>
7363 will produce <literal>timestamp with time zone '2005-04-03 12:00-06'</literal>,
7364 while adding <literal>interval '24 hours'</literal> to the same initial
7365 <type>timestamp with time zone</type> produces
7366 <literal>timestamp with time zone '2005-04-03 13:00-06'</literal>, as there is
7367 a change in daylight saving time at <literal>2005-04-03 02:00</literal> in time zone
7368 <literal>CST7CDT</literal>.
7372 Note there can be ambiguity in the <literal>months</> field returned by
7373 <function>age</> because different months have different numbers of
7374 days. <productname>PostgreSQL</>'s approach uses the month from the
7375 earlier of the two dates when calculating partial months. For example,
7376 <literal>age('2004-06-01', '2004-04-30')</> uses April to yield
7377 <literal>1 mon 1 day</>, while using May would yield <literal>1 mon 2
7378 days</> because May has 31 days, while April has only 30.
7382 Subtraction of dates and timestamps can also be complex. One conceptually
7383 simple way to perform subtraction is to convert each value to a number
7384 of seconds using <literal>EXTRACT(EPOCH FROM ...)</>, then subtract the
7385 results; this produces the
7386 number of <emphasis>seconds</> between the two values. This will adjust
7387 for the number of days in each month, timezone changes, and daylight
7388 saving time adjustments. Subtraction of date or timestamp
7389 values with the <quote><literal>-</></quote> operator
7390 returns the number of days (24-hours) and hours/minutes/seconds
7391 between the values, making the same adjustments. The <function>age</>
7392 function returns years, months, days, and hours/minutes/seconds,
7393 performing field-by-field subtraction and then adjusting for negative
7394 field values. The following queries illustrate the differences in these
7395 approaches. The sample results were produced with <literal>timezone
7396 = 'US/Eastern'</>; there is a daylight saving time change between the
7401 SELECT EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
7402 EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00');
7403 <lineannotation>Result: </lineannotation><computeroutput>10537200</computeroutput>
7404 SELECT (EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
7405 EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00'))
7407 <lineannotation>Result: </lineannotation><computeroutput>121.958333333333</computeroutput>
7408 SELECT timestamptz '2013-07-01 12:00:00' - timestamptz '2013-03-01 12:00:00';
7409 <lineannotation>Result: </lineannotation><computeroutput>121 days 23:00:00</computeroutput>
7410 SELECT age(timestamptz '2013-07-01 12:00:00', timestamptz '2013-03-01 12:00:00');
7411 <lineannotation>Result: </lineannotation><computeroutput>4 mons</computeroutput>
7414 <sect2 id="functions-datetime-extract">
7415 <title><function>EXTRACT</function>, <function>date_part</function></title>
7418 <primary>date_part</primary>
7421 <primary>extract</primary>
7425 EXTRACT(<replaceable>field</replaceable> FROM <replaceable>source</replaceable>)
7429 The <function>extract</function> function retrieves subfields
7430 such as year or hour from date/time values.
7431 <replaceable>source</replaceable> must be a value expression of
7432 type <type>timestamp</type>, <type>time</type>, or <type>interval</type>.
7433 (Expressions of type <type>date</type> are
7434 cast to <type>timestamp</type> and can therefore be used as
7435 well.) <replaceable>field</replaceable> is an identifier or
7436 string that selects what field to extract from the source value.
7437 The <function>extract</function> function returns values of type
7438 <type>double precision</type>.
7439 The following are valid field names:
7441 <!-- alphabetical -->
7444 <term><literal>century</literal></term>
7451 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');
7452 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
7453 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
7454 <lineannotation>Result: </lineannotation><computeroutput>21</computeroutput>
7458 The first century starts at 0001-01-01 00:00:00 AD, although
7459 they did not know it at the time. This definition applies to all
7460 Gregorian calendar countries. There is no century number 0,
7461 you go from -1 century to 1 century.
7463 If you disagree with this, please write your complaint to:
7464 Pope, Cathedral Saint-Peter of Roma, Vatican.
7470 <term><literal>day</literal></term>
7473 For <type>timestamp</type> values, the day (of the month) field
7474 (1 - 31) ; for <type>interval</type> values, the number of days
7478 SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
7479 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
7481 SELECT EXTRACT(DAY FROM INTERVAL '40 days 1 minute');
7482 <lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
7491 <term><literal>decade</literal></term>
7494 The year field divided by 10
7498 SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
7499 <lineannotation>Result: </lineannotation><computeroutput>200</computeroutput>
7505 <term><literal>dow</literal></term>
7508 The day of the week as Sunday (<literal>0</>) to
7509 Saturday (<literal>6</>)
7513 SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
7514 <lineannotation>Result: </lineannotation><computeroutput>5</computeroutput>
7517 Note that <function>extract</function>'s day of the week numbering
7518 differs from that of the <function>to_char(...,
7519 'D')</function> function.
7526 <term><literal>doy</literal></term>
7529 The day of the year (1 - 365/366)
7533 SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
7534 <lineannotation>Result: </lineannotation><computeroutput>47</computeroutput>
7540 <term><literal>epoch</literal></term>
7543 For <type>timestamp with time zone</type> values, the
7544 number of seconds since 1970-01-01 00:00:00 UTC (can be negative);
7545 for <type>date</type> and <type>timestamp</type> values, the
7546 number of seconds since 1970-01-01 00:00:00 local time;
7547 for <type>interval</type> values, the total number
7548 of seconds in the interval
7552 SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');
7553 <lineannotation>Result: </lineannotation><computeroutput>982384720.12</computeroutput>
7555 SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
7556 <lineannotation>Result: </lineannotation><computeroutput>442800</computeroutput>
7560 You can convert an epoch value back to a time stamp
7561 with <function>to_timestamp</>:
7564 SELECT to_timestamp(982384720.12);
7565 <lineannotation>Result: </lineannotation><computeroutput>2001-02-17 04:38:40.12+00</computeroutput>
7571 <term><literal>hour</literal></term>
7574 The hour field (0 - 23)
7578 SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
7579 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
7585 <term><literal>isodow</literal></term>
7588 The day of the week as Monday (<literal>1</>) to
7589 Sunday (<literal>7</>)
7593 SELECT EXTRACT(ISODOW FROM TIMESTAMP '2001-02-18 20:38:40');
7594 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
7597 This is identical to <literal>dow</> except for Sunday. This
7598 matches the <acronym>ISO</> 8601 day of the week numbering.
7605 <term><literal>isoyear</literal></term>
7608 The <acronym>ISO</acronym> 8601 week-numbering year that the date
7609 falls in (not applicable to intervals)
7613 SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-01');
7614 <lineannotation>Result: </lineannotation><computeroutput>2005</computeroutput>
7615 SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-02');
7616 <lineannotation>Result: </lineannotation><computeroutput>2006</computeroutput>
7620 Each <acronym>ISO</acronym> 8601 week-numbering year begins with the
7621 Monday of the week containing the 4th of January, so in early
7622 January or late December the <acronym>ISO</acronym> year may be
7623 different from the Gregorian year. See the <literal>week</literal>
7624 field for more information.
7627 This field is not available in PostgreSQL releases prior to 8.3.
7633 <term><literal>microseconds</literal></term>
7636 The seconds field, including fractional parts, multiplied by 1
7637 000 000; note that this includes full seconds
7641 SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
7642 <lineannotation>Result: </lineannotation><computeroutput>28500000</computeroutput>
7648 <term><literal>millennium</literal></term>
7655 SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
7656 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
7660 Years in the 1900s are in the second millennium.
7661 The third millennium started January 1, 2001.
7667 <term><literal>milliseconds</literal></term>
7670 The seconds field, including fractional parts, multiplied by
7671 1000. Note that this includes full seconds.
7675 SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
7676 <lineannotation>Result: </lineannotation><computeroutput>28500</computeroutput>
7682 <term><literal>minute</literal></term>
7685 The minutes field (0 - 59)
7689 SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
7690 <lineannotation>Result: </lineannotation><computeroutput>38</computeroutput>
7696 <term><literal>month</literal></term>
7699 For <type>timestamp</type> values, the number of the month
7700 within the year (1 - 12) ; for <type>interval</type> values,
7701 the number of months, modulo 12 (0 - 11)
7705 SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
7706 <lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
7708 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
7709 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
7711 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
7712 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
7718 <term><literal>quarter</literal></term>
7721 The quarter of the year (1 - 4) that the date is in
7725 SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
7726 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
7732 <term><literal>second</literal></term>
7735 The seconds field, including fractional parts (0 -
7736 59<footnote><simpara>60 if leap seconds are
7737 implemented by the operating system</simpara></footnote>)
7741 SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
7742 <lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
7744 SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
7745 <lineannotation>Result: </lineannotation><computeroutput>28.5</computeroutput>
7750 <term><literal>timezone</literal></term>
7753 The time zone offset from UTC, measured in seconds. Positive values
7754 correspond to time zones east of UTC, negative values to
7755 zones west of UTC. (Technically,
7756 <productname>PostgreSQL</productname> does not use UTC because
7757 leap seconds are not handled.)
7763 <term><literal>timezone_hour</literal></term>
7766 The hour component of the time zone offset
7772 <term><literal>timezone_minute</literal></term>
7775 The minute component of the time zone offset
7781 <term><literal>week</literal></term>
7784 The number of the <acronym>ISO</acronym> 8601 week-numbering week of
7785 the year. By definition, ISO weeks start on Mondays and the first
7786 week of a year contains January 4 of that year. In other words, the
7787 first Thursday of a year is in week 1 of that year.
7790 In the ISO week-numbering system, it is possible for early-January
7791 dates to be part of the 52nd or 53rd week of the previous year, and for
7792 late-December dates to be part of the first week of the next year.
7793 For example, <literal>2005-01-01</> is part of the 53rd week of year
7794 2004, and <literal>2006-01-01</> is part of the 52nd week of year
7795 2005, while <literal>2012-12-31</> is part of the first week of 2013.
7796 It's recommended to use the <literal>isoyear</> field together with
7797 <literal>week</> to get consistent results.
7801 SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
7802 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
7808 <term><literal>year</literal></term>
7811 The year field. Keep in mind there is no <literal>0 AD</>, so subtracting
7812 <literal>BC</> years from <literal>AD</> years should be done with care.
7816 SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
7817 <lineannotation>Result: </lineannotation><computeroutput>2001</computeroutput>
7827 When the input value is +/-Infinity, <function>extract</> returns
7828 +/-Infinity for monotonically-increasing fields (<literal>epoch</>,
7829 <literal>julian</>, <literal>year</>, <literal>isoyear</>,
7830 <literal>decade</>, <literal>century</>, and <literal>millennium</>).
7831 For other fields, NULL is returned. <productname>PostgreSQL</>
7832 versions before 9.6 returned zero for all cases of infinite input.
7837 The <function>extract</function> function is primarily intended
7838 for computational processing. For formatting date/time values for
7839 display, see <xref linkend="functions-formatting">.
7843 The <function>date_part</function> function is modeled on the traditional
7844 <productname>Ingres</productname> equivalent to the
7845 <acronym>SQL</acronym>-standard function <function>extract</function>:
7847 date_part('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
7849 Note that here the <replaceable>field</replaceable> parameter needs to
7850 be a string value, not a name. The valid field names for
7851 <function>date_part</function> are the same as for
7852 <function>extract</function>.
7856 SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
7857 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
7859 SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
7860 <lineannotation>Result: </lineannotation><computeroutput>4</computeroutput>
7865 <sect2 id="functions-datetime-trunc">
7866 <title><function>date_trunc</function></title>
7869 <primary>date_trunc</primary>
7873 The function <function>date_trunc</function> is conceptually
7874 similar to the <function>trunc</function> function for numbers.
7879 date_trunc('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
7881 <replaceable>source</replaceable> is a value expression of type
7882 <type>timestamp</type> or <type>interval</>.
7883 (Values of type <type>date</type> and
7884 <type>time</type> are cast automatically to <type>timestamp</type> or
7885 <type>interval</>, respectively.)
7886 <replaceable>field</replaceable> selects to which precision to
7887 truncate the input value. The return value is of type
7888 <type>timestamp</type> or <type>interval</>
7889 with all fields that are less significant than the
7890 selected one set to zero (or one, for day and month).
7894 Valid values for <replaceable>field</replaceable> are:
7896 <member><literal>microseconds</literal></member>
7897 <member><literal>milliseconds</literal></member>
7898 <member><literal>second</literal></member>
7899 <member><literal>minute</literal></member>
7900 <member><literal>hour</literal></member>
7901 <member><literal>day</literal></member>
7902 <member><literal>week</literal></member>
7903 <member><literal>month</literal></member>
7904 <member><literal>quarter</literal></member>
7905 <member><literal>year</literal></member>
7906 <member><literal>decade</literal></member>
7907 <member><literal>century</literal></member>
7908 <member><literal>millennium</literal></member>
7915 SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
7916 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 20:00:00</computeroutput>
7918 SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
7919 <lineannotation>Result: </lineannotation><computeroutput>2001-01-01 00:00:00</computeroutput>
7924 <sect2 id="functions-datetime-zoneconvert">
7925 <title><literal>AT TIME ZONE</literal></title>
7928 <primary>time zone</primary>
7929 <secondary>conversion</secondary>
7933 <primary>AT TIME ZONE</primary>
7937 The <literal>AT TIME ZONE</literal> construct allows conversions
7938 of time stamps to different time zones. <xref
7939 linkend="functions-datetime-zoneconvert-table"> shows its
7943 <table id="functions-datetime-zoneconvert-table">
7944 <title><literal>AT TIME ZONE</literal> Variants</title>
7948 <entry>Expression</entry>
7949 <entry>Return Type</entry>
7950 <entry>Description</entry>
7957 <literal><type>timestamp without time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7959 <entry><type>timestamp with time zone</type></entry>
7960 <entry>Treat given time stamp <emphasis>without time zone</> as located in the specified time zone</entry>
7965 <literal><type>timestamp with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7967 <entry><type>timestamp without time zone</type></entry>
7968 <entry>Convert given time stamp <emphasis>with time zone</> to the new time
7969 zone, with no time zone designation</entry>
7974 <literal><type>time with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7976 <entry><type>time with time zone</type></entry>
7977 <entry>Convert given time <emphasis>with time zone</> to the new time zone</entry>
7984 In these expressions, the desired time zone <replaceable>zone</> can be
7985 specified either as a text string (e.g., <literal>'PST'</literal>)
7986 or as an interval (e.g., <literal>INTERVAL '-08:00'</literal>).
7987 In the text case, a time zone name can be specified in any of the ways
7988 described in <xref linkend="datatype-timezones">.
7992 Examples (assuming the local time zone is <literal>PST8PDT</>):
7994 SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'MST';
7995 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 19:38:40-08</computeroutput>
7997 SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'MST';
7998 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 18:38:40</computeroutput>
8000 The first example takes a time stamp without time zone and interprets it as MST time
8001 (UTC-7), which is then converted to PST (UTC-8) for display. The second example takes
8002 a time stamp specified in EST (UTC-5) and converts it to local time in MST (UTC-7).
8006 The function <literal><function>timezone</function>(<replaceable>zone</>,
8007 <replaceable>timestamp</>)</literal> is equivalent to the SQL-conforming construct
8008 <literal><replaceable>timestamp</> AT TIME ZONE
8009 <replaceable>zone</></literal>.
8013 <sect2 id="functions-datetime-current">
8014 <title>Current Date/Time</title>
8017 <primary>date</primary>
8018 <secondary>current</secondary>
8022 <primary>time</primary>
8023 <secondary>current</secondary>
8027 <productname>PostgreSQL</productname> provides a number of functions
8028 that return values related to the current date and time. These
8029 SQL-standard functions all return values based on the start time of
8030 the current transaction:
8035 CURRENT_TIME(<replaceable>precision</replaceable>)
8036 CURRENT_TIMESTAMP(<replaceable>precision</replaceable>)
8039 LOCALTIME(<replaceable>precision</replaceable>)
8040 LOCALTIMESTAMP(<replaceable>precision</replaceable>)
8045 <function>CURRENT_TIME</function> and
8046 <function>CURRENT_TIMESTAMP</function> deliver values with time zone;
8047 <function>LOCALTIME</function> and
8048 <function>LOCALTIMESTAMP</function> deliver values without time zone.
8052 <function>CURRENT_TIME</function>,
8053 <function>CURRENT_TIMESTAMP</function>,
8054 <function>LOCALTIME</function>, and
8055 <function>LOCALTIMESTAMP</function>
8057 a precision parameter, which causes the result to be rounded
8058 to that many fractional digits in the seconds field. Without a precision parameter,
8059 the result is given to the full available precision.
8065 SELECT CURRENT_TIME;
8066 <lineannotation>Result: </lineannotation><computeroutput>14:39:53.662522-05</computeroutput>
8068 SELECT CURRENT_DATE;
8069 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23</computeroutput>
8071 SELECT CURRENT_TIMESTAMP;
8072 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522-05</computeroutput>
8074 SELECT CURRENT_TIMESTAMP(2);
8075 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.66-05</computeroutput>
8077 SELECT LOCALTIMESTAMP;
8078 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522</computeroutput>
8083 Since these functions return
8084 the start time of the current transaction, their values do not
8085 change during the transaction. This is considered a feature:
8086 the intent is to allow a single transaction to have a consistent
8087 notion of the <quote>current</quote> time, so that multiple
8088 modifications within the same transaction bear the same
8094 Other database systems might advance these values more
8100 <productname>PostgreSQL</productname> also provides functions that
8101 return the start time of the current statement, as well as the actual
8102 current time at the instant the function is called. The complete list
8103 of non-SQL-standard time functions is:
8105 transaction_timestamp()
8106 statement_timestamp()
8114 <function>transaction_timestamp()</> is equivalent to
8115 <function>CURRENT_TIMESTAMP</function>, but is named to clearly reflect
8117 <function>statement_timestamp()</> returns the start time of the current
8118 statement (more specifically, the time of receipt of the latest command
8119 message from the client).
8120 <function>statement_timestamp()</> and <function>transaction_timestamp()</>
8121 return the same value during the first command of a transaction, but might
8122 differ during subsequent commands.
8123 <function>clock_timestamp()</> returns the actual current time, and
8124 therefore its value changes even within a single SQL command.
8125 <function>timeofday()</> is a historical
8126 <productname>PostgreSQL</productname> function. Like
8127 <function>clock_timestamp()</>, it returns the actual current time,
8128 but as a formatted <type>text</> string rather than a <type>timestamp
8129 with time zone</> value.
8130 <function>now()</> is a traditional <productname>PostgreSQL</productname>
8131 equivalent to <function>transaction_timestamp()</function>.
8135 All the date/time data types also accept the special literal value
8136 <literal>now</literal> to specify the current date and time (again,
8137 interpreted as the transaction start time). Thus,
8138 the following three all return the same result:
8140 SELECT CURRENT_TIMESTAMP;
8142 SELECT TIMESTAMP 'now'; -- incorrect for use with DEFAULT
8148 You do not want to use the third form when specifying a <literal>DEFAULT</>
8149 clause while creating a table. The system will convert <literal>now</literal>
8150 to a <type>timestamp</type> as soon as the constant is parsed, so that when
8151 the default value is needed,
8152 the time of the table creation would be used! The first two
8153 forms will not be evaluated until the default value is used,
8154 because they are function calls. Thus they will give the desired
8155 behavior of defaulting to the time of row insertion.
8160 <sect2 id="functions-datetime-delay">
8161 <title>Delaying Execution</title>
8164 <primary>pg_sleep</primary>
8167 <primary>pg_sleep_for</primary>
8170 <primary>pg_sleep_until</primary>
8173 <primary>sleep</primary>
8176 <primary>delay</primary>
8180 The following functions are available to delay execution of the server
8183 pg_sleep(<replaceable>seconds</replaceable>)
8184 pg_sleep_for(<type>interval</>)
8185 pg_sleep_until(<type>timestamp with time zone</>)
8188 <function>pg_sleep</function> makes the current session's process
8189 sleep until <replaceable>seconds</replaceable> seconds have
8190 elapsed. <replaceable>seconds</replaceable> is a value of type
8191 <type>double precision</>, so fractional-second delays can be specified.
8192 <function>pg_sleep_for</function> is a convenience function for larger
8193 sleep times specified as an <type>interval</>.
8194 <function>pg_sleep_until</function> is a convenience function for when
8195 a specific wake-up time is desired.
8199 SELECT pg_sleep(1.5);
8200 SELECT pg_sleep_for('5 minutes');
8201 SELECT pg_sleep_until('tomorrow 03:00');
8207 The effective resolution of the sleep interval is platform-specific;
8208 0.01 seconds is a common value. The sleep delay will be at least as long
8209 as specified. It might be longer depending on factors such as server load.
8210 In particular, <function>pg_sleep_until</function> is not guaranteed to
8211 wake up exactly at the specified time, but it will not wake up any earlier.
8217 Make sure that your session does not hold more locks than necessary
8218 when calling <function>pg_sleep</function> or its variants. Otherwise
8219 other sessions might have to wait for your sleeping process, slowing down
8228 <sect1 id="functions-enum">
8229 <title>Enum Support Functions</title>
8232 For enum types (described in <xref linkend="datatype-enum">),
8233 there are several functions that allow cleaner programming without
8234 hard-coding particular values of an enum type.
8235 These are listed in <xref linkend="functions-enum-table">. The examples
8236 assume an enum type created as:
8239 CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'purple');
8244 <table id="functions-enum-table">
8245 <title>Enum Support Functions</title>
8249 <entry>Function</entry>
8250 <entry>Description</entry>
8251 <entry>Example</entry>
8252 <entry>Example Result</entry>
8259 <primary>enum_first</primary>
8261 <literal>enum_first(anyenum)</literal>
8263 <entry>Returns the first value of the input enum type</entry>
8264 <entry><literal>enum_first(null::rainbow)</literal></entry>
8265 <entry><literal>red</literal></entry>
8270 <primary>enum_last</primary>
8272 <literal>enum_last(anyenum)</literal>
8274 <entry>Returns the last value of the input enum type</entry>
8275 <entry><literal>enum_last(null::rainbow)</literal></entry>
8276 <entry><literal>purple</literal></entry>
8281 <primary>enum_range</primary>
8283 <literal>enum_range(anyenum)</literal>
8285 <entry>Returns all values of the input enum type in an ordered array</entry>
8286 <entry><literal>enum_range(null::rainbow)</literal></entry>
8287 <entry><literal>{red,orange,yellow,green,blue,purple}</literal></entry>
8290 <entry morerows="2"><literal>enum_range(anyenum, anyenum)</literal></entry>
8291 <entry morerows="2">
8292 Returns the range between the two given enum values, as an ordered
8293 array. The values must be from the same enum type. If the first
8294 parameter is null, the result will start with the first value of
8296 If the second parameter is null, the result will end with the last
8297 value of the enum type.
8299 <entry><literal>enum_range('orange'::rainbow, 'green'::rainbow)</literal></entry>
8300 <entry><literal>{orange,yellow,green}</literal></entry>
8303 <entry><literal>enum_range(NULL, 'green'::rainbow)</literal></entry>
8304 <entry><literal>{red,orange,yellow,green}</literal></entry>
8307 <entry><literal>enum_range('orange'::rainbow, NULL)</literal></entry>
8308 <entry><literal>{orange,yellow,green,blue,purple}</literal></entry>
8315 Notice that except for the two-argument form of <function>enum_range</>,
8316 these functions disregard the specific value passed to them; they care
8317 only about its declared data type. Either null or a specific value of
8318 the type can be passed, with the same result. It is more common to
8319 apply these functions to a table column or function argument than to
8320 a hardwired type name as suggested by the examples.
8324 <sect1 id="functions-geometry">
8325 <title>Geometric Functions and Operators</title>
8328 The geometric types <type>point</type>, <type>box</type>,
8329 <type>lseg</type>, <type>line</type>, <type>path</type>,
8330 <type>polygon</type>, and <type>circle</type> have a large set of
8331 native support functions and operators, shown in <xref
8332 linkend="functions-geometry-op-table">, <xref
8333 linkend="functions-geometry-func-table">, and <xref
8334 linkend="functions-geometry-conv-table">.
8339 Note that the <quote>same as</> operator, <literal>~=</>, represents
8340 the usual notion of equality for the <type>point</type>,
8341 <type>box</type>, <type>polygon</type>, and <type>circle</type> types.
8342 Some of these types also have an <literal>=</> operator, but
8343 <literal>=</> compares
8344 for equal <emphasis>areas</> only. The other scalar comparison operators
8345 (<literal><=</> and so on) likewise compare areas for these types.
8349 <table id="functions-geometry-op-table">
8350 <title>Geometric Operators</title>
8354 <entry>Operator</entry>
8355 <entry>Description</entry>
8356 <entry>Example</entry>
8361 <entry> <literal>+</literal> </entry>
8362 <entry>Translation</entry>
8363 <entry><literal>box '((0,0),(1,1))' + point '(2.0,0)'</literal></entry>
8366 <entry> <literal>-</literal> </entry>
8367 <entry>Translation</entry>
8368 <entry><literal>box '((0,0),(1,1))' - point '(2.0,0)'</literal></entry>
8371 <entry> <literal>*</literal> </entry>
8372 <entry>Scaling/rotation</entry>
8373 <entry><literal>box '((0,0),(1,1))' * point '(2.0,0)'</literal></entry>
8376 <entry> <literal>/</literal> </entry>
8377 <entry>Scaling/rotation</entry>
8378 <entry><literal>box '((0,0),(2,2))' / point '(2.0,0)'</literal></entry>
8381 <entry> <literal>#</literal> </entry>
8382 <entry>Point or box of intersection</entry>
8383 <entry><literal>box '((1,-1),(-1,1))' # box '((1,1),(-2,-2))'</literal></entry>
8386 <entry> <literal>#</literal> </entry>
8387 <entry>Number of points in path or polygon</entry>
8388 <entry><literal># path '((1,0),(0,1),(-1,0))'</literal></entry>
8391 <entry> <literal>@-@</literal> </entry>
8392 <entry>Length or circumference</entry>
8393 <entry><literal>@-@ path '((0,0),(1,0))'</literal></entry>
8396 <entry> <literal>@@</literal> </entry>
8397 <entry>Center</entry>
8398 <entry><literal>@@ circle '((0,0),10)'</literal></entry>
8401 <entry> <literal>##</literal> </entry>
8402 <entry>Closest point to first operand on second operand</entry>
8403 <entry><literal>point '(0,0)' ## lseg '((2,0),(0,2))'</literal></entry>
8406 <entry> <literal><-></literal> </entry>
8407 <entry>Distance between</entry>
8408 <entry><literal>circle '((0,0),1)' <-> circle '((5,0),1)'</literal></entry>
8411 <entry> <literal>&&</literal> </entry>
8412 <entry>Overlaps? (One point in common makes this true.)</entry>
8413 <entry><literal>box '((0,0),(1,1))' && box '((0,0),(2,2))'</literal></entry>
8416 <entry> <literal><<</literal> </entry>
8417 <entry>Is strictly left of?</entry>
8418 <entry><literal>circle '((0,0),1)' << circle '((5,0),1)'</literal></entry>
8421 <entry> <literal>>></literal> </entry>
8422 <entry>Is strictly right of?</entry>
8423 <entry><literal>circle '((5,0),1)' >> circle '((0,0),1)'</literal></entry>
8426 <entry> <literal>&<</literal> </entry>
8427 <entry>Does not extend to the right of?</entry>
8428 <entry><literal>box '((0,0),(1,1))' &< box '((0,0),(2,2))'</literal></entry>
8431 <entry> <literal>&></literal> </entry>
8432 <entry>Does not extend to the left of?</entry>
8433 <entry><literal>box '((0,0),(3,3))' &> box '((0,0),(2,2))'</literal></entry>
8436 <entry> <literal><<|</literal> </entry>
8437 <entry>Is strictly below?</entry>
8438 <entry><literal>box '((0,0),(3,3))' <<| box '((3,4),(5,5))'</literal></entry>
8441 <entry> <literal>|>></literal> </entry>
8442 <entry>Is strictly above?</entry>
8443 <entry><literal>box '((3,4),(5,5))' |>> box '((0,0),(3,3))'</literal></entry>
8446 <entry> <literal>&<|</literal> </entry>
8447 <entry>Does not extend above?</entry>
8448 <entry><literal>box '((0,0),(1,1))' &<| box '((0,0),(2,2))'</literal></entry>
8451 <entry> <literal>|&></literal> </entry>
8452 <entry>Does not extend below?</entry>
8453 <entry><literal>box '((0,0),(3,3))' |&> box '((0,0),(2,2))'</literal></entry>
8456 <entry> <literal><^</literal> </entry>
8457 <entry>Is below (allows touching)?</entry>
8458 <entry><literal>circle '((0,0),1)' <^ circle '((0,5),1)'</literal></entry>
8461 <entry> <literal>>^</literal> </entry>
8462 <entry>Is above (allows touching)?</entry>
8463 <entry><literal>circle '((0,5),1)' >^ circle '((0,0),1)'</literal></entry>
8466 <entry> <literal>?#</literal> </entry>
8467 <entry>Intersects?</entry>
8468 <entry><literal>lseg '((-1,0),(1,0))' ?# box '((-2,-2),(2,2))'</literal></entry>
8471 <entry> <literal>?-</literal> </entry>
8472 <entry>Is horizontal?</entry>
8473 <entry><literal>?- lseg '((-1,0),(1,0))'</literal></entry>
8476 <entry> <literal>?-</literal> </entry>
8477 <entry>Are horizontally aligned?</entry>
8478 <entry><literal>point '(1,0)' ?- point '(0,0)'</literal></entry>
8481 <entry> <literal>?|</literal> </entry>
8482 <entry>Is vertical?</entry>
8483 <entry><literal>?| lseg '((-1,0),(1,0))'</literal></entry>
8486 <entry> <literal>?|</literal> </entry>
8487 <entry>Are vertically aligned?</entry>
8488 <entry><literal>point '(0,1)' ?| point '(0,0)'</literal></entry>
8491 <entry> <literal>?-|</literal> </entry>
8492 <entry>Is perpendicular?</entry>
8493 <entry><literal>lseg '((0,0),(0,1))' ?-| lseg '((0,0),(1,0))'</literal></entry>
8496 <entry> <literal>?||</literal> </entry>
8497 <entry>Are parallel?</entry>
8498 <entry><literal>lseg '((-1,0),(1,0))' ?|| lseg '((-1,2),(1,2))'</literal></entry>
8501 <entry> <literal>@></literal> </entry>
8502 <entry>Contains?</entry>
8503 <entry><literal>circle '((0,0),2)' @> point '(1,1)'</literal></entry>
8506 <entry> <literal><@</literal> </entry>
8507 <entry>Contained in or on?</entry>
8508 <entry><literal>point '(1,1)' <@ circle '((0,0),2)'</literal></entry>
8511 <entry> <literal>~=</literal> </entry>
8512 <entry>Same as?</entry>
8513 <entry><literal>polygon '((0,0),(1,1))' ~= polygon '((1,1),(0,0))'</literal></entry>
8521 Before <productname>PostgreSQL</productname> 8.2, the containment
8522 operators <literal>@></> and <literal><@</> were respectively
8523 called <literal>~</> and <literal>@</>. These names are still
8524 available, but are deprecated and will eventually be removed.
8529 <primary>area</primary>
8532 <primary>center</primary>
8535 <primary>diameter</primary>
8538 <primary>height</primary>
8541 <primary>isclosed</primary>
8544 <primary>isopen</primary>
8547 <primary>length</primary>
8550 <primary>npoints</primary>
8553 <primary>pclose</primary>
8556 <primary>popen</primary>
8559 <primary>radius</primary>
8562 <primary>width</primary>
8565 <table id="functions-geometry-func-table">
8566 <title>Geometric Functions</title>
8570 <entry>Function</entry>
8571 <entry>Return Type</entry>
8572 <entry>Description</entry>
8573 <entry>Example</entry>
8578 <entry><literal><function>area(<replaceable>object</>)</function></literal></entry>
8579 <entry><type>double precision</type></entry>
8581 <entry><literal>area(box '((0,0),(1,1))')</literal></entry>
8584 <entry><literal><function>center(<replaceable>object</>)</function></literal></entry>
8585 <entry><type>point</type></entry>
8586 <entry>center</entry>
8587 <entry><literal>center(box '((0,0),(1,2))')</literal></entry>
8590 <entry><literal><function>diameter(<type>circle</>)</function></literal></entry>
8591 <entry><type>double precision</type></entry>
8592 <entry>diameter of circle</entry>
8593 <entry><literal>diameter(circle '((0,0),2.0)')</literal></entry>
8596 <entry><literal><function>height(<type>box</>)</function></literal></entry>
8597 <entry><type>double precision</type></entry>
8598 <entry>vertical size of box</entry>
8599 <entry><literal>height(box '((0,0),(1,1))')</literal></entry>
8602 <entry><literal><function>isclosed(<type>path</>)</function></literal></entry>
8603 <entry><type>boolean</type></entry>
8604 <entry>a closed path?</entry>
8605 <entry><literal>isclosed(path '((0,0),(1,1),(2,0))')</literal></entry>
8608 <entry><literal><function>isopen(<type>path</>)</function></literal></entry>
8609 <entry><type>boolean</type></entry>
8610 <entry>an open path?</entry>
8611 <entry><literal>isopen(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8614 <entry><literal><function>length(<replaceable>object</>)</function></literal></entry>
8615 <entry><type>double precision</type></entry>
8616 <entry>length</entry>
8617 <entry><literal>length(path '((-1,0),(1,0))')</literal></entry>
8620 <entry><literal><function>npoints(<type>path</>)</function></literal></entry>
8621 <entry><type>int</type></entry>
8622 <entry>number of points</entry>
8623 <entry><literal>npoints(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8626 <entry><literal><function>npoints(<type>polygon</>)</function></literal></entry>
8627 <entry><type>int</type></entry>
8628 <entry>number of points</entry>
8629 <entry><literal>npoints(polygon '((1,1),(0,0))')</literal></entry>
8632 <entry><literal><function>pclose(<type>path</>)</function></literal></entry>
8633 <entry><type>path</type></entry>
8634 <entry>convert path to closed</entry>
8635 <entry><literal>pclose(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8638 <!-- Not defined by this name. Implements the intersection operator '#' -->
8640 <entry><literal><function>point(<type>lseg</>, <type>lseg</>)</function></literal></entry>
8641 <entry><type>point</type></entry>
8642 <entry>intersection</entry>
8643 <entry><literal>point(lseg '((-1,0),(1,0))',lseg '((-2,-2),(2,2))')</literal></entry>
8647 <entry><literal><function>popen(<type>path</>)</function></literal></entry>
8648 <entry><type>path</type></entry>
8649 <entry>convert path to open</entry>
8650 <entry><literal>popen(path '((0,0),(1,1),(2,0))')</literal></entry>
8653 <entry><literal><function>radius(<type>circle</type>)</function></literal></entry>
8654 <entry><type>double precision</type></entry>
8655 <entry>radius of circle</entry>
8656 <entry><literal>radius(circle '((0,0),2.0)')</literal></entry>
8659 <entry><literal><function>width(<type>box</>)</function></literal></entry>
8660 <entry><type>double precision</type></entry>
8661 <entry>horizontal size of box</entry>
8662 <entry><literal>width(box '((0,0),(1,1))')</literal></entry>
8668 <table id="functions-geometry-conv-table">
8669 <title>Geometric Type Conversion Functions</title>
8673 <entry>Function</entry>
8674 <entry>Return Type</entry>
8675 <entry>Description</entry>
8676 <entry>Example</entry>
8683 <primary>box</primary>
8685 <literal><function>box(<type>circle</type>)</function></literal>
8687 <entry><type>box</type></entry>
8688 <entry>circle to box</entry>
8689 <entry><literal>box(circle '((0,0),2.0)')</literal></entry>
8692 <entry><literal><function>box(<type>point</type>)</function></literal></entry>
8693 <entry><type>box</type></entry>
8694 <entry>point to empty box</entry>
8695 <entry><literal>box(point '(0,0)')</literal></entry>
8698 <entry><literal><function>box(<type>point</type>, <type>point</type>)</function></literal></entry>
8699 <entry><type>box</type></entry>
8700 <entry>points to box</entry>
8701 <entry><literal>box(point '(0,0)', point '(1,1)')</literal></entry>
8704 <entry><literal><function>box(<type>polygon</type>)</function></literal></entry>
8705 <entry><type>box</type></entry>
8706 <entry>polygon to box</entry>
8707 <entry><literal>box(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8710 <entry><literal><function>bound_box(<type>box</type>, <type>box</type>)</function></literal></entry>
8711 <entry><type>box</type></entry>
8712 <entry>boxes to bounding box</entry>
8713 <entry><literal>bound_box(box '((0,0),(1,1))', box '((3,3),(4,4))')</literal></entry>
8718 <primary>circle</primary>
8720 <literal><function>circle(<type>box</type>)</function></literal>
8722 <entry><type>circle</type></entry>
8723 <entry>box to circle</entry>
8724 <entry><literal>circle(box '((0,0),(1,1))')</literal></entry>
8727 <entry><literal><function>circle(<type>point</type>, <type>double precision</type>)</function></literal></entry>
8728 <entry><type>circle</type></entry>
8729 <entry>center and radius to circle</entry>
8730 <entry><literal>circle(point '(0,0)', 2.0)</literal></entry>
8733 <entry><literal><function>circle(<type>polygon</type>)</function></literal></entry>
8734 <entry><type>circle</type></entry>
8735 <entry>polygon to circle</entry>
8736 <entry><literal>circle(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8739 <entry><literal><function>line(<type>point</type>, <type>point</type>)</function></literal></entry>
8740 <entry><type>line</type></entry>
8741 <entry>points to line</entry>
8742 <entry><literal>line(point '(-1,0)', point '(1,0)')</literal></entry>
8747 <primary>lseg</primary>
8749 <literal><function>lseg(<type>box</type>)</function></literal>
8751 <entry><type>lseg</type></entry>
8752 <entry>box diagonal to line segment</entry>
8753 <entry><literal>lseg(box '((-1,0),(1,0))')</literal></entry>
8756 <entry><literal><function>lseg(<type>point</type>, <type>point</type>)</function></literal></entry>
8757 <entry><type>lseg</type></entry>
8758 <entry>points to line segment</entry>
8759 <entry><literal>lseg(point '(-1,0)', point '(1,0)')</literal></entry>
8764 <primary>path</primary>
8766 <literal><function>path(<type>polygon</type>)</function></literal>
8768 <entry><type>path</type></entry>
8769 <entry>polygon to path</entry>
8770 <entry><literal>path(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8775 <primary>point</primary>
8777 <literal><function>point</function>(<type>double
8778 precision</type>, <type>double precision</type>)</literal>
8780 <entry><type>point</type></entry>
8781 <entry>construct point</entry>
8782 <entry><literal>point(23.4, -44.5)</literal></entry>
8785 <entry><literal><function>point(<type>box</type>)</function></literal></entry>
8786 <entry><type>point</type></entry>
8787 <entry>center of box</entry>
8788 <entry><literal>point(box '((-1,0),(1,0))')</literal></entry>
8791 <entry><literal><function>point(<type>circle</type>)</function></literal></entry>
8792 <entry><type>point</type></entry>
8793 <entry>center of circle</entry>
8794 <entry><literal>point(circle '((0,0),2.0)')</literal></entry>
8797 <entry><literal><function>point(<type>lseg</type>)</function></literal></entry>
8798 <entry><type>point</type></entry>
8799 <entry>center of line segment</entry>
8800 <entry><literal>point(lseg '((-1,0),(1,0))')</literal></entry>
8803 <entry><literal><function>point(<type>polygon</type>)</function></literal></entry>
8804 <entry><type>point</type></entry>
8805 <entry>center of polygon</entry>
8806 <entry><literal>point(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8811 <primary>polygon</primary>
8813 <literal><function>polygon(<type>box</type>)</function></literal>
8815 <entry><type>polygon</type></entry>
8816 <entry>box to 4-point polygon</entry>
8817 <entry><literal>polygon(box '((0,0),(1,1))')</literal></entry>
8820 <entry><literal><function>polygon(<type>circle</type>)</function></literal></entry>
8821 <entry><type>polygon</type></entry>
8822 <entry>circle to 12-point polygon</entry>
8823 <entry><literal>polygon(circle '((0,0),2.0)')</literal></entry>
8826 <entry><literal><function>polygon(<replaceable class="parameter">npts</replaceable>, <type>circle</type>)</function></literal></entry>
8827 <entry><type>polygon</type></entry>
8828 <entry>circle to <replaceable class="parameter">npts</replaceable>-point polygon</entry>
8829 <entry><literal>polygon(12, circle '((0,0),2.0)')</literal></entry>
8832 <entry><literal><function>polygon(<type>path</type>)</function></literal></entry>
8833 <entry><type>polygon</type></entry>
8834 <entry>path to polygon</entry>
8835 <entry><literal>polygon(path '((0,0),(1,1),(2,0))')</literal></entry>
8842 It is possible to access the two component numbers of a <type>point</>
8843 as though the point were an array with indexes 0 and 1. For example, if
8844 <literal>t.p</> is a <type>point</> column then
8845 <literal>SELECT p[0] FROM t</> retrieves the X coordinate and
8846 <literal>UPDATE t SET p[1] = ...</> changes the Y coordinate.
8847 In the same way, a value of type <type>box</> or <type>lseg</> can be treated
8848 as an array of two <type>point</> values.
8852 The <function>area</function> function works for the types
8853 <type>box</type>, <type>circle</type>, and <type>path</type>.
8854 The <function>area</function> function only works on the
8855 <type>path</type> data type if the points in the
8856 <type>path</type> are non-intersecting. For example, the
8858 <literal>'((0,0),(0,1),(2,1),(2,2),(1,2),(1,0),(0,0))'::PATH</literal>
8859 will not work; however, the following visually identical
8861 <literal>'((0,0),(0,1),(1,1),(1,2),(2,2),(2,1),(1,1),(1,0),(0,0))'::PATH</literal>
8862 will work. If the concept of an intersecting versus
8863 non-intersecting <type>path</type> is confusing, draw both of the
8864 above <type>path</type>s side by side on a piece of graph paper.
8870 <sect1 id="functions-net">
8871 <title>Network Address Functions and Operators</title>
8874 <xref linkend="cidr-inet-operators-table"> shows the operators
8875 available for the <type>cidr</type> and <type>inet</type> types.
8876 The operators <literal><<</literal>,
8877 <literal><<=</literal>, <literal>>></literal>,
8878 <literal>>>=</literal>, and <literal>&&</literal>
8879 test for subnet inclusion. They
8880 consider only the network parts of the two addresses (ignoring any
8881 host part) and determine whether one network is identical to
8882 or a subnet of the other.
8885 <table id="cidr-inet-operators-table">
8886 <title><type>cidr</type> and <type>inet</type> Operators</title>
8890 <entry>Operator</entry>
8891 <entry>Description</entry>
8892 <entry>Example</entry>
8897 <entry> <literal><</literal> </entry>
8898 <entry>is less than</entry>
8899 <entry><literal>inet '192.168.1.5' < inet '192.168.1.6'</literal></entry>
8902 <entry> <literal><=</literal> </entry>
8903 <entry>is less than or equal</entry>
8904 <entry><literal>inet '192.168.1.5' <= inet '192.168.1.5'</literal></entry>
8907 <entry> <literal>=</literal> </entry>
8908 <entry>equals</entry>
8909 <entry><literal>inet '192.168.1.5' = inet '192.168.1.5'</literal></entry>
8912 <entry> <literal>>=</literal> </entry>
8913 <entry>is greater or equal</entry>
8914 <entry><literal>inet '192.168.1.5' >= inet '192.168.1.5'</literal></entry>
8917 <entry> <literal>></literal> </entry>
8918 <entry>is greater than</entry>
8919 <entry><literal>inet '192.168.1.5' > inet '192.168.1.4'</literal></entry>
8922 <entry> <literal><></literal> </entry>
8923 <entry>is not equal</entry>
8924 <entry><literal>inet '192.168.1.5' <> inet '192.168.1.4'</literal></entry>
8927 <entry> <literal><<</literal> </entry>
8928 <entry>is contained by</entry>
8929 <entry><literal>inet '192.168.1.5' << inet '192.168.1/24'</literal></entry>
8932 <entry> <literal><<=</literal> </entry>
8933 <entry>is contained by or equals</entry>
8934 <entry><literal>inet '192.168.1/24' <<= inet '192.168.1/24'</literal></entry>
8937 <entry> <literal>>></literal> </entry>
8938 <entry>contains</entry>
8939 <entry><literal>inet '192.168.1/24' >> inet '192.168.1.5'</literal></entry>
8942 <entry> <literal>>>=</literal> </entry>
8943 <entry>contains or equals</entry>
8944 <entry><literal>inet '192.168.1/24' >>= inet '192.168.1/24'</literal></entry>
8947 <entry> <literal>&&</literal> </entry>
8948 <entry>contains or is contained by</entry>
8949 <entry><literal>inet '192.168.1/24' && inet '192.168.1.80/28'</literal></entry>
8952 <entry> <literal>~</literal> </entry>
8953 <entry>bitwise NOT</entry>
8954 <entry><literal>~ inet '192.168.1.6'</literal></entry>
8957 <entry> <literal>&</literal> </entry>
8958 <entry>bitwise AND</entry>
8959 <entry><literal>inet '192.168.1.6' & inet '0.0.0.255'</literal></entry>
8962 <entry> <literal>|</literal> </entry>
8963 <entry>bitwise OR</entry>
8964 <entry><literal>inet '192.168.1.6' | inet '0.0.0.255'</literal></entry>
8967 <entry> <literal>+</literal> </entry>
8968 <entry>addition</entry>
8969 <entry><literal>inet '192.168.1.6' + 25</literal></entry>
8972 <entry> <literal>-</literal> </entry>
8973 <entry>subtraction</entry>
8974 <entry><literal>inet '192.168.1.43' - 36</literal></entry>
8977 <entry> <literal>-</literal> </entry>
8978 <entry>subtraction</entry>
8979 <entry><literal>inet '192.168.1.43' - inet '192.168.1.19'</literal></entry>
8986 <xref linkend="cidr-inet-functions-table"> shows the functions
8987 available for use with the <type>cidr</type> and <type>inet</type>
8988 types. The <function>abbrev</function>, <function>host</function>,
8989 and <function>text</function>
8990 functions are primarily intended to offer alternative display
8994 <table id="cidr-inet-functions-table">
8995 <title><type>cidr</type> and <type>inet</type> Functions</title>
8999 <entry>Function</entry>
9000 <entry>Return Type</entry>
9001 <entry>Description</entry>
9002 <entry>Example</entry>
9003 <entry>Result</entry>
9010 <primary>abbrev</primary>
9012 <literal><function>abbrev(<type>inet</type>)</function></literal>
9014 <entry><type>text</type></entry>
9015 <entry>abbreviated display format as text</entry>
9016 <entry><literal>abbrev(inet '10.1.0.0/16')</literal></entry>
9017 <entry><literal>10.1.0.0/16</literal></entry>
9020 <entry><literal><function>abbrev(<type>cidr</type>)</function></literal></entry>
9021 <entry><type>text</type></entry>
9022 <entry>abbreviated display format as text</entry>
9023 <entry><literal>abbrev(cidr '10.1.0.0/16')</literal></entry>
9024 <entry><literal>10.1/16</literal></entry>
9029 <primary>broadcast</primary>
9031 <literal><function>broadcast(<type>inet</type>)</function></literal>
9033 <entry><type>inet</type></entry>
9034 <entry>broadcast address for network</entry>
9035 <entry><literal>broadcast('192.168.1.5/24')</literal></entry>
9036 <entry><literal>192.168.1.255/24</literal></entry>
9041 <primary>family</primary>
9043 <literal><function>family(<type>inet</type>)</function></literal>
9045 <entry><type>int</type></entry>
9046 <entry>extract family of address; <literal>4</literal> for IPv4,
9047 <literal>6</literal> for IPv6</entry>
9048 <entry><literal>family('::1')</literal></entry>
9049 <entry><literal>6</literal></entry>
9054 <primary>host</primary>
9056 <literal><function>host(<type>inet</type>)</function></literal>
9058 <entry><type>text</type></entry>
9059 <entry>extract IP address as text</entry>
9060 <entry><literal>host('192.168.1.5/24')</literal></entry>
9061 <entry><literal>192.168.1.5</literal></entry>
9066 <primary>hostmask</primary>
9068 <literal><function>hostmask(<type>inet</type>)</function></literal>
9070 <entry><type>inet</type></entry>
9071 <entry>construct host mask for network</entry>
9072 <entry><literal>hostmask('192.168.23.20/30')</literal></entry>
9073 <entry><literal>0.0.0.3</literal></entry>
9078 <primary>masklen</primary>
9080 <literal><function>masklen(<type>inet</type>)</function></literal>
9082 <entry><type>int</type></entry>
9083 <entry>extract netmask length</entry>
9084 <entry><literal>masklen('192.168.1.5/24')</literal></entry>
9085 <entry><literal>24</literal></entry>
9090 <primary>netmask</primary>
9092 <literal><function>netmask(<type>inet</type>)</function></literal>
9094 <entry><type>inet</type></entry>
9095 <entry>construct netmask for network</entry>
9096 <entry><literal>netmask('192.168.1.5/24')</literal></entry>
9097 <entry><literal>255.255.255.0</literal></entry>
9102 <primary>network</primary>
9104 <literal><function>network(<type>inet</type>)</function></literal>
9106 <entry><type>cidr</type></entry>
9107 <entry>extract network part of address</entry>
9108 <entry><literal>network('192.168.1.5/24')</literal></entry>
9109 <entry><literal>192.168.1.0/24</literal></entry>
9114 <primary>set_masklen</primary>
9116 <literal><function>set_masklen(<type>inet</type>, <type>int</type>)</function></literal>
9118 <entry><type>inet</type></entry>
9119 <entry>set netmask length for <type>inet</type> value</entry>
9120 <entry><literal>set_masklen('192.168.1.5/24', 16)</literal></entry>
9121 <entry><literal>192.168.1.5/16</literal></entry>
9124 <entry><literal><function>set_masklen(<type>cidr</type>, <type>int</type>)</function></literal></entry>
9125 <entry><type>cidr</type></entry>
9126 <entry>set netmask length for <type>cidr</type> value</entry>
9127 <entry><literal>set_masklen('192.168.1.0/24'::cidr, 16)</literal></entry>
9128 <entry><literal>192.168.0.0/16</literal></entry>
9133 <primary>text</primary>
9135 <literal><function>text(<type>inet</type>)</function></literal>
9137 <entry><type>text</type></entry>
9138 <entry>extract IP address and netmask length as text</entry>
9139 <entry><literal>text(inet '192.168.1.5')</literal></entry>
9140 <entry><literal>192.168.1.5/32</literal></entry>
9145 <primary>inet_same_family</primary>
9147 <literal><function>inet_same_family(<type>inet</type>, <type>inet</type>)</function></literal>
9149 <entry><type>boolean</type></entry>
9150 <entry>are the addresses from the same family?</entry>
9151 <entry><literal>inet_same_family('192.168.1.5/24', '::1')</literal></entry>
9152 <entry><literal>false</literal></entry>
9157 <primary>inet_merge</primary>
9159 <literal><function>inet_merge(<type>inet</type>, <type>inet</type>)</function></literal>
9161 <entry><type>cidr</type></entry>
9162 <entry>the smallest network which includes both of the given networks</entry>
9163 <entry><literal>inet_merge('192.168.1.5/24', '192.168.2.5/24')</literal></entry>
9164 <entry><literal>192.168.0.0/22</literal></entry>
9171 Any <type>cidr</> value can be cast to <type>inet</> implicitly
9172 or explicitly; therefore, the functions shown above as operating on
9173 <type>inet</> also work on <type>cidr</> values. (Where there are
9174 separate functions for <type>inet</> and <type>cidr</>, it is because
9175 the behavior should be different for the two cases.)
9176 Also, it is permitted to cast an <type>inet</> value to <type>cidr</>.
9177 When this is done, any bits to the right of the netmask are silently zeroed
9178 to create a valid <type>cidr</> value.
9180 you can cast a text value to <type>inet</> or <type>cidr</>
9181 using normal casting syntax: for example,
9182 <literal>inet(<replaceable>expression</>)</literal> or
9183 <literal><replaceable>colname</>::cidr</literal>.
9187 <xref linkend="macaddr-functions-table"> shows the functions
9188 available for use with the <type>macaddr</type> type. The function
9189 <literal><function>trunc(<type>macaddr</type>)</function></literal> returns a MAC
9190 address with the last 3 bytes set to zero. This can be used to
9191 associate the remaining prefix with a manufacturer.
9194 <table id="macaddr-functions-table">
9195 <title><type>macaddr</type> Functions</title>
9199 <entry>Function</entry>
9200 <entry>Return Type</entry>
9201 <entry>Description</entry>
9202 <entry>Example</entry>
9203 <entry>Result</entry>
9210 <primary>trunc</primary>
9212 <literal><function>trunc(<type>macaddr</type>)</function></literal>
9214 <entry><type>macaddr</type></entry>
9215 <entry>set last 3 bytes to zero</entry>
9216 <entry><literal>trunc(macaddr '12:34:56:78:90:ab')</literal></entry>
9217 <entry><literal>12:34:56:00:00:00</literal></entry>
9224 The <type>macaddr</type> type also supports the standard relational
9225 operators (<literal>></literal>, <literal><=</literal>, etc.) for
9226 lexicographical ordering, and the bitwise arithmetic operators
9227 (<literal>~</literal>, <literal>&</literal> and <literal>|</literal>)
9228 for NOT, AND and OR.
9232 <xref linkend="macaddr8-functions-table"> shows the functions
9233 available for use with the <type>macaddr8</type> type. The function
9234 <literal><function>trunc(<type>macaddr8</type>)</function></literal> returns a MAC
9235 address with the last 5 bytes set to zero. This can be used to
9236 associate the remaining prefix with a manufacturer.
9239 <table id="macaddr8-functions-table">
9240 <title><type>macaddr8</type> Functions</title>
9244 <entry>Function</entry>
9245 <entry>Return Type</entry>
9246 <entry>Description</entry>
9247 <entry>Example</entry>
9248 <entry>Result</entry>
9255 <primary>trunc</primary>
9257 <literal><function>trunc(<type>macaddr8</type>)</function></literal>
9259 <entry><type>macaddr8</type></entry>
9260 <entry>set last 5 bytes to zero</entry>
9261 <entry><literal>trunc(macaddr8 '12:34:56:78:90:ab:cd:ef')</literal></entry>
9262 <entry><literal>12:34:56:00:00:00:00:00</literal></entry>
9267 <primary>macaddr8_set7bit</primary>
9269 <literal><function>macaddr8_set7bit(<type>macaddr8</type>)</function></literal>
9271 <entry><type>macaddr8</type></entry>
9272 <entry>set 7th bit to one, also known as modified EUI-64, for inclusion in an IPv6 address</entry>
9273 <entry><literal>macaddr8_set7bit(macaddr8 '00:34:56:ab:cd:ef')</literal></entry>
9274 <entry><literal>02:34:56:ff:fe:ab:cd:ef</literal></entry>
9281 The <type>macaddr8</type> type also supports the standard relational
9282 operators (<literal>></literal>, <literal><=</literal>, etc.) for
9283 ordering, and the bitwise arithmetic operators (<literal>~</literal>,
9284 <literal>&</literal> and <literal>|</literal>) for NOT, AND and OR.
9290 <sect1 id="functions-textsearch">
9291 <title>Text Search Functions and Operators</title>
9293 <indexterm zone="datatype-textsearch">
9294 <primary>full text search</primary>
9295 <secondary>functions and operators</secondary>
9298 <indexterm zone="datatype-textsearch">
9299 <primary>text search</primary>
9300 <secondary>functions and operators</secondary>
9304 <xref linkend="textsearch-operators-table">,
9305 <xref linkend="textsearch-functions-table"> and
9306 <xref linkend="textsearch-functions-debug-table">
9307 summarize the functions and operators that are provided
9308 for full text searching. See <xref linkend="textsearch"> for a detailed
9309 explanation of <productname>PostgreSQL</productname>'s text search
9313 <table id="textsearch-operators-table">
9314 <title>Text Search Operators</title>
9318 <entry>Operator</entry>
9319 <entry>Return Type</entry>
9320 <entry>Description</entry>
9321 <entry>Example</entry>
9322 <entry>Result</entry>
9327 <entry> <literal>@@</literal> </entry>
9328 <entry><type>boolean</></entry>
9329 <entry><type>tsvector</> matches <type>tsquery</> ?</entry>
9330 <entry><literal>to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat')</literal></entry>
9331 <entry><literal>t</literal></entry>
9334 <entry> <literal>@@@</literal> </entry>
9335 <entry><type>boolean</></entry>
9336 <entry>deprecated synonym for <literal>@@</></entry>
9337 <entry><literal>to_tsvector('fat cats ate rats') @@@ to_tsquery('cat & rat')</literal></entry>
9338 <entry><literal>t</literal></entry>
9341 <entry> <literal>||</literal> </entry>
9342 <entry><type>tsvector</></entry>
9343 <entry>concatenate <type>tsvector</>s</entry>
9344 <entry><literal>'a:1 b:2'::tsvector || 'c:1 d:2 b:3'::tsvector</literal></entry>
9345 <entry><literal>'a':1 'b':2,5 'c':3 'd':4</literal></entry>
9348 <entry> <literal>&&</literal> </entry>
9349 <entry><type>tsquery</></entry>
9350 <entry>AND <type>tsquery</>s together</entry>
9351 <entry><literal>'fat | rat'::tsquery && 'cat'::tsquery</literal></entry>
9352 <entry><literal>( 'fat' | 'rat' ) & 'cat'</literal></entry>
9355 <entry> <literal>||</literal> </entry>
9356 <entry><type>tsquery</></entry>
9357 <entry>OR <type>tsquery</>s together</entry>
9358 <entry><literal>'fat | rat'::tsquery || 'cat'::tsquery</literal></entry>
9359 <entry><literal>( 'fat' | 'rat' ) | 'cat'</literal></entry>
9362 <entry> <literal>!!</literal> </entry>
9363 <entry><type>tsquery</></entry>
9364 <entry>negate a <type>tsquery</></entry>
9365 <entry><literal>!! 'cat'::tsquery</literal></entry>
9366 <entry><literal>!'cat'</literal></entry>
9369 <entry> <literal><-></literal> </entry>
9370 <entry><type>tsquery</></entry>
9371 <entry><type>tsquery</> followed by <type>tsquery</></entry>
9372 <entry><literal>to_tsquery('fat') <-> to_tsquery('rat')</literal></entry>
9373 <entry><literal>'fat' <-> 'rat'</literal></entry>
9376 <entry> <literal>@></literal> </entry>
9377 <entry><type>boolean</></entry>
9378 <entry><type>tsquery</> contains another ?</entry>
9379 <entry><literal>'cat'::tsquery @> 'cat & rat'::tsquery</literal></entry>
9380 <entry><literal>f</literal></entry>
9383 <entry> <literal><@</literal> </entry>
9384 <entry><type>boolean</></entry>
9385 <entry><type>tsquery</> is contained in ?</entry>
9386 <entry><literal>'cat'::tsquery <@ 'cat & rat'::tsquery</literal></entry>
9387 <entry><literal>t</literal></entry>
9395 The <type>tsquery</> containment operators consider only the lexemes
9396 listed in the two queries, ignoring the combining operators.
9401 In addition to the operators shown in the table, the ordinary B-tree
9402 comparison operators (<literal>=</>, <literal><</>, etc) are defined
9403 for types <type>tsvector</> and <type>tsquery</>. These are not very
9404 useful for text searching but allow, for example, unique indexes to be
9405 built on columns of these types.
9408 <table id="textsearch-functions-table">
9409 <title>Text Search Functions</title>
9413 <entry>Function</entry>
9414 <entry>Return Type</entry>
9415 <entry>Description</entry>
9416 <entry>Example</entry>
9417 <entry>Result</entry>
9424 <primary>array_to_tsvector</primary>
9426 <literal><function>array_to_tsvector(<type>text[]</>)</function></literal>
9428 <entry><type>tsvector</type></entry>
9429 <entry>convert array of lexemes to <type>tsvector</type></entry>
9430 <entry><literal>array_to_tsvector('{fat,cat,rat}'::text[])</literal></entry>
9431 <entry><literal>'cat' 'fat' 'rat'</literal></entry>
9436 <primary>get_current_ts_config</primary>
9438 <literal><function>get_current_ts_config()</function></literal>
9440 <entry><type>regconfig</type></entry>
9441 <entry>get default text search configuration</entry>
9442 <entry><literal>get_current_ts_config()</literal></entry>
9443 <entry><literal>english</literal></entry>
9448 <primary>length</primary>
9450 <literal><function>length(<type>tsvector</>)</function></literal>
9452 <entry><type>integer</type></entry>
9453 <entry>number of lexemes in <type>tsvector</></entry>
9454 <entry><literal>length('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9455 <entry><literal>3</literal></entry>
9460 <primary>numnode</primary>
9462 <literal><function>numnode(<type>tsquery</>)</function></literal>
9464 <entry><type>integer</type></entry>
9465 <entry>number of lexemes plus operators in <type>tsquery</></entry>
9466 <entry><literal> numnode('(fat & rat) | cat'::tsquery)</literal></entry>
9467 <entry><literal>5</literal></entry>
9472 <primary>plainto_tsquery</primary>
9474 <literal><function>plainto_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
9476 <entry><type>tsquery</type></entry>
9477 <entry>produce <type>tsquery</> ignoring punctuation</entry>
9478 <entry><literal>plainto_tsquery('english', 'The Fat Rats')</literal></entry>
9479 <entry><literal>'fat' & 'rat'</literal></entry>
9484 <primary>phraseto_tsquery</primary>
9486 <literal><function>phraseto_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
9488 <entry><type>tsquery</type></entry>
9489 <entry>produce <type>tsquery</> that searches for a phrase,
9490 ignoring punctuation</entry>
9491 <entry><literal>phraseto_tsquery('english', 'The Fat Rats')</literal></entry>
9492 <entry><literal>'fat' <-> 'rat'</literal></entry>
9497 <primary>querytree</primary>
9499 <literal><function>querytree(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>)</function></literal>
9501 <entry><type>text</type></entry>
9502 <entry>get indexable part of a <type>tsquery</></entry>
9503 <entry><literal>querytree('foo & ! bar'::tsquery)</literal></entry>
9504 <entry><literal>'foo'</literal></entry>
9509 <primary>setweight</primary>
9511 <literal><function>setweight(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">weight</replaceable> <type>"char"</>)</function></literal>
9513 <entry><type>tsvector</type></entry>
9514 <entry>assign <replaceable class="PARAMETER">weight</replaceable> to each element of <replaceable class="PARAMETER">vector</replaceable></entry>
9515 <entry><literal>setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A')</literal></entry>
9516 <entry><literal>'cat':3A 'fat':2A,4A 'rat':5A</literal></entry>
9521 <primary>setweight</primary>
9522 <secondary>setweight for specific lexeme(s)</secondary>
9524 <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>
9526 <entry><type>tsvector</type></entry>
9527 <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>
9528 <entry><literal>setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A', '{cat,rat}')</literal></entry>
9529 <entry><literal>'cat':3A 'fat':2,4 'rat':5A</literal></entry>
9534 <primary>strip</primary>
9536 <literal><function>strip(<type>tsvector</>)</function></literal>
9538 <entry><type>tsvector</type></entry>
9539 <entry>remove positions and weights from <type>tsvector</></entry>
9540 <entry><literal>strip('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9541 <entry><literal>'cat' 'fat' 'rat'</literal></entry>
9546 <primary>to_tsquery</primary>
9548 <literal><function>to_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
9550 <entry><type>tsquery</type></entry>
9551 <entry>normalize words and convert to <type>tsquery</></entry>
9552 <entry><literal>to_tsquery('english', 'The & Fat & Rats')</literal></entry>
9553 <entry><literal>'fat' & 'rat'</literal></entry>
9558 <primary>to_tsvector</primary>
9560 <literal><function>to_tsvector(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">document</> <type>text</type>)</function></literal>
9562 <entry><type>tsvector</type></entry>
9563 <entry>reduce document text to <type>tsvector</></entry>
9564 <entry><literal>to_tsvector('english', 'The Fat Rats')</literal></entry>
9565 <entry><literal>'fat':2 'rat':3</literal></entry>
9570 <primary>ts_delete</primary>
9572 <literal><function>ts_delete(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">lexeme</replaceable> <type>text</>)</function></literal>
9574 <entry><type>tsvector</type></entry>
9575 <entry>remove given <replaceable class="PARAMETER">lexeme</replaceable> from <replaceable class="PARAMETER">vector</replaceable></entry>
9576 <entry><literal>ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, 'fat')</literal></entry>
9577 <entry><literal>'cat':3 'rat':5A</literal></entry>
9581 <!-- previous indexterm entry covers this too -->
9582 <literal><function>ts_delete(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">lexemes</replaceable> <type>text[]</>)</function></literal>
9584 <entry><type>tsvector</type></entry>
9585 <entry>remove any occurrence of lexemes in <replaceable class="PARAMETER">lexemes</replaceable> from <replaceable class="PARAMETER">vector</replaceable></entry>
9586 <entry><literal>ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, ARRAY['fat','rat'])</literal></entry>
9587 <entry><literal>'cat':3</literal></entry>
9592 <primary>ts_filter</primary>
9594 <literal><function>ts_filter(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">weights</replaceable> <type>"char"[]</>)</function></literal>
9596 <entry><type>tsvector</type></entry>
9597 <entry>select only elements with given <replaceable class="PARAMETER">weights</replaceable> from <replaceable class="PARAMETER">vector</replaceable></entry>
9598 <entry><literal>ts_filter('fat:2,4 cat:3b rat:5A'::tsvector, '{a,b}')</literal></entry>
9599 <entry><literal>'cat':3B 'rat':5A</literal></entry>
9604 <primary>ts_headline</primary>
9606 <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>
9608 <entry><type>text</type></entry>
9609 <entry>display a query match</entry>
9610 <entry><literal>ts_headline('x y z', 'z'::tsquery)</literal></entry>
9611 <entry><literal>x y <b>z</b></literal></entry>
9616 <primary>ts_rank</primary>
9618 <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>
9620 <entry><type>float4</type></entry>
9621 <entry>rank document for query</entry>
9622 <entry><literal>ts_rank(textsearch, query)</literal></entry>
9623 <entry><literal>0.818</literal></entry>
9628 <primary>ts_rank_cd</primary>
9630 <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>
9632 <entry><type>float4</type></entry>
9633 <entry>rank document for query using cover density</entry>
9634 <entry><literal>ts_rank_cd('{0.1, 0.2, 0.4, 1.0}', textsearch, query)</literal></entry>
9635 <entry><literal>2.01317</literal></entry>
9640 <primary>ts_rewrite</primary>
9642 <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>
9644 <entry><type>tsquery</type></entry>
9645 <entry>replace <replaceable>target</> with <replaceable>substitute</>
9646 within query</entry>
9647 <entry><literal>ts_rewrite('a & b'::tsquery, 'a'::tsquery, 'foo|bar'::tsquery)</literal></entry>
9648 <entry><literal>'b' & ( 'foo' | 'bar' )</literal></entry>
9651 <entry><literal><function>ts_rewrite(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">select</replaceable> <type>text</>)</function></literal></entry>
9652 <entry><type>tsquery</type></entry>
9653 <entry>replace using targets and substitutes from a <command>SELECT</> command</entry>
9654 <entry><literal>SELECT ts_rewrite('a & b'::tsquery, 'SELECT t,s FROM aliases')</literal></entry>
9655 <entry><literal>'b' & ( 'foo' | 'bar' )</literal></entry>
9660 <primary>tsquery_phrase</primary>
9662 <literal><function>tsquery_phrase(<replaceable class="PARAMETER">query1</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">query2</replaceable> <type>tsquery</>)</function></literal>
9664 <entry><type>tsquery</type></entry>
9665 <entry>make query that searches for <replaceable>query1</> followed
9666 by <replaceable>query2</> (same as <literal><-></>
9668 <entry><literal>tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'))</literal></entry>
9669 <entry><literal>'fat' <-> 'cat'</literal></entry>
9673 <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>
9675 <entry><type>tsquery</type></entry>
9676 <entry>make query that searches for <replaceable>query1</> followed by
9677 <replaceable>query2</> at distance <replaceable>distance</></entry>
9678 <entry><literal>tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'), 10)</literal></entry>
9679 <entry><literal>'fat' <10> 'cat'</literal></entry>
9684 <primary>tsvector_to_array</primary>
9686 <literal><function>tsvector_to_array(<type>tsvector</>)</function></literal>
9688 <entry><type>text[]</type></entry>
9689 <entry>convert <type>tsvector</> to array of lexemes</entry>
9690 <entry><literal>tsvector_to_array('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9691 <entry><literal>{cat,fat,rat}</literal></entry>
9696 <primary>tsvector_update_trigger</primary>
9698 <literal><function>tsvector_update_trigger()</function></literal>
9700 <entry><type>trigger</type></entry>
9701 <entry>trigger function for automatic <type>tsvector</> column update</entry>
9702 <entry><literal>CREATE TRIGGER ... tsvector_update_trigger(tsvcol, 'pg_catalog.swedish', title, body)</literal></entry>
9703 <entry><literal></literal></entry>
9708 <primary>tsvector_update_trigger_column</primary>
9710 <literal><function>tsvector_update_trigger_column()</function></literal>
9712 <entry><type>trigger</type></entry>
9713 <entry>trigger function for automatic <type>tsvector</> column update</entry>
9714 <entry><literal>CREATE TRIGGER ... tsvector_update_trigger_column(tsvcol, configcol, title, body)</literal></entry>
9715 <entry><literal></literal></entry>
9720 <primary>unnest</primary>
9721 <secondary>for tsvector</secondary>
9723 <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>
9725 <entry><type>setof record</type></entry>
9726 <entry>expand a tsvector to a set of rows</entry>
9727 <entry><literal>unnest('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9728 <entry><literal>(cat,{3},{D}) ...</literal></entry>
9736 All the text search functions that accept an optional <type>regconfig</>
9737 argument will use the configuration specified by
9738 <xref linkend="guc-default-text-search-config">
9739 when that argument is omitted.
9745 <xref linkend="textsearch-functions-debug-table">
9746 are listed separately because they are not usually used in everyday text
9747 searching operations. They are helpful for development and debugging
9748 of new text search configurations.
9751 <table id="textsearch-functions-debug-table">
9752 <title>Text Search Debugging Functions</title>
9756 <entry>Function</entry>
9757 <entry>Return Type</entry>
9758 <entry>Description</entry>
9759 <entry>Example</entry>
9760 <entry>Result</entry>
9767 <primary>ts_debug</primary>
9769 <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>
9771 <entry><type>setof record</type></entry>
9772 <entry>test a configuration</entry>
9773 <entry><literal>ts_debug('english', 'The Brightest supernovaes')</literal></entry>
9774 <entry><literal>(asciiword,"Word, all ASCII",The,{english_stem},english_stem,{}) ...</literal></entry>
9779 <primary>ts_lexize</primary>
9781 <literal><function>ts_lexize(<replaceable class="PARAMETER">dict</replaceable> <type>regdictionary</>, <replaceable class="PARAMETER">token</replaceable> <type>text</>)</function></literal>
9783 <entry><type>text[]</type></entry>
9784 <entry>test a dictionary</entry>
9785 <entry><literal>ts_lexize('english_stem', 'stars')</literal></entry>
9786 <entry><literal>{star}</literal></entry>
9791 <primary>ts_parse</primary>
9793 <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>
9795 <entry><type>setof record</type></entry>
9796 <entry>test a parser</entry>
9797 <entry><literal>ts_parse('default', 'foo - bar')</literal></entry>
9798 <entry><literal>(1,foo) ...</literal></entry>
9801 <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>
9802 <entry><type>setof record</type></entry>
9803 <entry>test a parser</entry>
9804 <entry><literal>ts_parse(3722, 'foo - bar')</literal></entry>
9805 <entry><literal>(1,foo) ...</literal></entry>
9810 <primary>ts_token_type</primary>
9812 <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>
9814 <entry><type>setof record</type></entry>
9815 <entry>get token types defined by parser</entry>
9816 <entry><literal>ts_token_type('default')</literal></entry>
9817 <entry><literal>(1,asciiword,"Word, all ASCII") ...</literal></entry>
9820 <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>
9821 <entry><type>setof record</type></entry>
9822 <entry>get token types defined by parser</entry>
9823 <entry><literal>ts_token_type(3722)</literal></entry>
9824 <entry><literal>(1,asciiword,"Word, all ASCII") ...</literal></entry>
9829 <primary>ts_stat</primary>
9831 <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>
9833 <entry><type>setof record</type></entry>
9834 <entry>get statistics of a <type>tsvector</> column</entry>
9835 <entry><literal>ts_stat('SELECT vector from apod')</literal></entry>
9836 <entry><literal>(foo,10,15) ...</literal></entry>
9845 <sect1 id="functions-xml">
9846 <title>XML Functions</title>
9849 The functions and function-like expressions described in this
9850 section operate on values of type <type>xml</type>. Check <xref
9851 linkend="datatype-xml"> for information about the <type>xml</type>
9852 type. The function-like expressions <function>xmlparse</function>
9853 and <function>xmlserialize</function> for converting to and from
9854 type <type>xml</type> are not repeated here. Use of most of these
9855 functions requires the installation to have been built
9856 with <command>configure --with-libxml</>.
9859 <sect2 id="functions-producing-xml">
9860 <title>Producing XML Content</title>
9863 A set of functions and function-like expressions are available for
9864 producing XML content from SQL data. As such, they are
9865 particularly suitable for formatting query results into XML
9866 documents for processing in client applications.
9870 <title><literal>xmlcomment</literal></title>
9873 <primary>xmlcomment</primary>
9877 <function>xmlcomment</function>(<replaceable>text</replaceable>)
9881 The function <function>xmlcomment</function> creates an XML value
9882 containing an XML comment with the specified text as content.
9883 The text cannot contain <quote><literal>--</literal></quote> or end with a
9884 <quote><literal>-</literal></quote> so that the resulting construct is a valid
9885 XML comment. If the argument is null, the result is null.
9891 SELECT xmlcomment('hello');
9901 <title><literal>xmlconcat</literal></title>
9904 <primary>xmlconcat</primary>
9908 <function>xmlconcat</function>(<replaceable>xml</replaceable><optional>, ...</optional>)
9912 The function <function>xmlconcat</function> concatenates a list
9913 of individual XML values to create a single value containing an
9914 XML content fragment. Null values are omitted; the result is
9915 only null if there are no nonnull arguments.
9921 SELECT xmlconcat('<abc/>', '<bar>foo</bar>');
9924 ----------------------
9925 <abc/><bar>foo</bar>
9930 XML declarations, if present, are combined as follows. If all
9931 argument values have the same XML version declaration, that
9932 version is used in the result, else no version is used. If all
9933 argument values have the standalone declaration value
9934 <quote>yes</quote>, then that value is used in the result. If
9935 all argument values have a standalone declaration value and at
9936 least one is <quote>no</quote>, then that is used in the result.
9937 Else the result will have no standalone declaration. If the
9938 result is determined to require a standalone declaration but no
9939 version declaration, a version declaration with version 1.0 will
9940 be used because XML requires an XML declaration to contain a
9941 version declaration. Encoding declarations are ignored and
9942 removed in all cases.
9948 SELECT xmlconcat('<?xml version="1.1"?><foo/>', '<?xml version="1.1" standalone="no"?><bar/>');
9951 -----------------------------------
9952 <?xml version="1.1"?><foo/><bar/>
9958 <title><literal>xmlelement</literal></title>
9961 <primary>xmlelement</primary>
9965 <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>)
9969 The <function>xmlelement</function> expression produces an XML
9970 element with the given name, attributes, and content.
9976 SELECT xmlelement(name foo);
9982 SELECT xmlelement(name foo, xmlattributes('xyz' as bar));
9988 SELECT xmlelement(name foo, xmlattributes(current_date as bar), 'cont', 'ent');
9991 -------------------------------------
9992 <foo bar="2007-01-26">content</foo>
9997 Element and attribute names that are not valid XML names are
9998 escaped by replacing the offending characters by the sequence
9999 <literal>_x<replaceable>HHHH</replaceable>_</literal>, where
10000 <replaceable>HHHH</replaceable> is the character's Unicode
10001 codepoint in hexadecimal notation. For example:
10003 SELECT xmlelement(name "foo$bar", xmlattributes('xyz' as "a&b"));
10006 ----------------------------------
10007 <foo_x0024_bar a_x0026_b="xyz"/>
10012 An explicit attribute name need not be specified if the attribute
10013 value is a column reference, in which case the column's name will
10014 be used as the attribute name by default. In other cases, the
10015 attribute must be given an explicit name. So this example is
10018 CREATE TABLE test (a xml, b xml);
10019 SELECT xmlelement(name test, xmlattributes(a, b)) FROM test;
10023 SELECT xmlelement(name test, xmlattributes('constant'), a, b) FROM test;
10024 SELECT xmlelement(name test, xmlattributes(func(a, b))) FROM test;
10029 Element content, if specified, will be formatted according to
10030 its data type. If the content is itself of type <type>xml</type>,
10031 complex XML documents can be constructed. For example:
10033 SELECT xmlelement(name foo, xmlattributes('xyz' as bar),
10034 xmlelement(name abc),
10035 xmlcomment('test'),
10036 xmlelement(name xyz));
10039 ----------------------------------------------
10040 <foo bar="xyz"><abc/><!--test--><xyz/></foo>
10043 Content of other types will be formatted into valid XML character
10044 data. This means in particular that the characters <, >,
10045 and & will be converted to entities. Binary data (data type
10046 <type>bytea</type>) will be represented in base64 or hex
10047 encoding, depending on the setting of the configuration parameter
10048 <xref linkend="guc-xmlbinary">. The particular behavior for
10049 individual data types is expected to evolve in order to align the
10050 SQL and PostgreSQL data types with the XML Schema specification,
10051 at which point a more precise description will appear.
10056 <title><literal>xmlforest</literal></title>
10059 <primary>xmlforest</primary>
10063 <function>xmlforest</function>(<replaceable>content</replaceable> <optional>AS <replaceable>name</replaceable></optional> <optional>, ...</optional>)
10067 The <function>xmlforest</function> expression produces an XML
10068 forest (sequence) of elements using the given names and content.
10074 SELECT xmlforest('abc' AS foo, 123 AS bar);
10077 ------------------------------
10078 <foo>abc</foo><bar>123</bar>
10081 SELECT xmlforest(table_name, column_name)
10082 FROM information_schema.columns
10083 WHERE table_schema = 'pg_catalog';
10086 -------------------------------------------------------------------------------------------
10087 <table_name>pg_authid</table_name><column_name>rolname</column_name>
10088 <table_name>pg_authid</table_name><column_name>rolsuper</column_name>
10092 As seen in the second example, the element name can be omitted if
10093 the content value is a column reference, in which case the column
10094 name is used by default. Otherwise, a name must be specified.
10098 Element names that are not valid XML names are escaped as shown
10099 for <function>xmlelement</function> above. Similarly, content
10100 data is escaped to make valid XML content, unless it is already
10101 of type <type>xml</type>.
10105 Note that XML forests are not valid XML documents if they consist
10106 of more than one element, so it might be useful to wrap
10107 <function>xmlforest</function> expressions in
10108 <function>xmlelement</function>.
10113 <title><literal>xmlpi</literal></title>
10116 <primary>xmlpi</primary>
10120 <function>xmlpi</function>(name <replaceable>target</replaceable> <optional>, <replaceable>content</replaceable></optional>)
10124 The <function>xmlpi</function> expression creates an XML
10125 processing instruction. The content, if present, must not
10126 contain the character sequence <literal>?></literal>.
10132 SELECT xmlpi(name php, 'echo "hello world";');
10135 -----------------------------
10136 <?php echo "hello world";?>
10142 <title><literal>xmlroot</literal></title>
10145 <primary>xmlroot</primary>
10149 <function>xmlroot</function>(<replaceable>xml</replaceable>, version <replaceable>text</replaceable> | no value <optional>, standalone yes|no|no value</optional>)
10153 The <function>xmlroot</function> expression alters the properties
10154 of the root node of an XML value. If a version is specified,
10155 it replaces the value in the root node's version declaration; if a
10156 standalone setting is specified, it replaces the value in the
10157 root node's standalone declaration.
10162 SELECT xmlroot(xmlparse(document '<?xml version="1.1"?><content>abc</content>'),
10163 version '1.0', standalone yes);
10166 ----------------------------------------
10167 <?xml version="1.0" standalone="yes"?>
10168 <content>abc</content>
10173 <sect3 id="functions-xml-xmlagg">
10174 <title><literal>xmlagg</literal></title>
10177 <primary>xmlagg</primary>
10181 <function>xmlagg</function>(<replaceable>xml</replaceable>)
10185 The function <function>xmlagg</function> is, unlike the other
10186 functions described here, an aggregate function. It concatenates the
10187 input values to the aggregate function call,
10188 much like <function>xmlconcat</function> does, except that concatenation
10189 occurs across rows rather than across expressions in a single row.
10190 See <xref linkend="functions-aggregate"> for additional information
10191 about aggregate functions.
10197 CREATE TABLE test (y int, x xml);
10198 INSERT INTO test VALUES (1, '<foo>abc</foo>');
10199 INSERT INTO test VALUES (2, '<bar/>');
10200 SELECT xmlagg(x) FROM test;
10202 ----------------------
10203 <foo>abc</foo><bar/>
10208 To determine the order of the concatenation, an <literal>ORDER BY</>
10209 clause may be added to the aggregate call as described in
10210 <xref linkend="syntax-aggregates">. For example:
10213 SELECT xmlagg(x ORDER BY y DESC) FROM test;
10215 ----------------------
10216 <bar/><foo>abc</foo>
10221 The following non-standard approach used to be recommended
10222 in previous versions, and may still be useful in specific
10226 SELECT xmlagg(x) FROM (SELECT * FROM test ORDER BY y DESC) AS tab;
10228 ----------------------
10229 <bar/><foo>abc</foo>
10235 <sect2 id="functions-xml-predicates">
10236 <title>XML Predicates</title>
10239 The expressions described in this section check properties
10240 of <type>xml</type> values.
10244 <title><literal>IS DOCUMENT</literal></title>
10247 <primary>IS DOCUMENT</primary>
10251 <replaceable>xml</replaceable> IS DOCUMENT
10255 The expression <literal>IS DOCUMENT</literal> returns true if the
10256 argument XML value is a proper XML document, false if it is not
10257 (that is, it is a content fragment), or null if the argument is
10258 null. See <xref linkend="datatype-xml"> about the difference
10259 between documents and content fragments.
10263 <sect3 id="xml-exists">
10264 <title><literal>XMLEXISTS</literal></title>
10267 <primary>XMLEXISTS</primary>
10271 <function>XMLEXISTS</function>(<replaceable>text</replaceable> PASSING <optional>BY REF</optional> <replaceable>xml</replaceable> <optional>BY REF</optional>)
10275 The function <function>xmlexists</function> returns true if the
10276 XPath expression in the first argument returns any nodes, and
10277 false otherwise. (If either argument is null, the result is
10284 SELECT xmlexists('//town[text() = ''Toronto'']' PASSING BY REF '<towns><town>Toronto</town><town>Ottawa</town></towns>');
10294 The <literal>BY REF</literal> clauses have no effect in
10295 PostgreSQL, but are allowed for SQL conformance and compatibility
10296 with other implementations. Per SQL standard, the
10297 first <literal>BY REF</literal> is required, the second is
10298 optional. Also note that the SQL standard specifies
10299 the <function>xmlexists</function> construct to take an XQuery
10300 expression as first argument, but PostgreSQL currently only
10301 supports XPath, which is a subset of XQuery.
10305 <sect3 id="xml-is-well-formed">
10306 <title><literal>xml_is_well_formed</literal></title>
10309 <primary>xml_is_well_formed</primary>
10313 <primary>xml_is_well_formed_document</primary>
10317 <primary>xml_is_well_formed_content</primary>
10321 <function>xml_is_well_formed</function>(<replaceable>text</replaceable>)
10322 <function>xml_is_well_formed_document</function>(<replaceable>text</replaceable>)
10323 <function>xml_is_well_formed_content</function>(<replaceable>text</replaceable>)
10327 These functions check whether a <type>text</> string is well-formed XML,
10328 returning a Boolean result.
10329 <function>xml_is_well_formed_document</function> checks for a well-formed
10330 document, while <function>xml_is_well_formed_content</function> checks
10331 for well-formed content. <function>xml_is_well_formed</function> does
10332 the former if the <xref linkend="guc-xmloption"> configuration
10333 parameter is set to <literal>DOCUMENT</>, or the latter if it is set to
10334 <literal>CONTENT</>. This means that
10335 <function>xml_is_well_formed</function> is useful for seeing whether
10336 a simple cast to type <type>xml</> will succeed, whereas the other two
10337 functions are useful for seeing whether the corresponding variants of
10338 <function>XMLPARSE</> will succeed.
10345 SET xmloption TO DOCUMENT;
10346 SELECT xml_is_well_formed('<>');
10348 --------------------
10352 SELECT xml_is_well_formed('<abc/>');
10354 --------------------
10358 SET xmloption TO CONTENT;
10359 SELECT xml_is_well_formed('abc');
10361 --------------------
10365 SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</pg:foo>');
10366 xml_is_well_formed_document
10367 -----------------------------
10371 SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</my:foo>');
10372 xml_is_well_formed_document
10373 -----------------------------
10378 The last example shows that the checks include whether
10379 namespaces are correctly matched.
10384 <sect2 id="functions-xml-processing">
10385 <title>Processing XML</title>
10388 To process values of data type <type>xml</type>, PostgreSQL offers
10389 the functions <function>xpath</function> and
10390 <function>xpath_exists</function>, which evaluate XPath 1.0
10391 expressions, and the <function>XMLTABLE</function>
10395 <sect3 id="functions-xml-processing-xpath">
10396 <title><literal>xpath</literal></title>
10399 <primary>XPath</primary>
10403 <function>xpath</function>(<replaceable>xpath</replaceable>, <replaceable>xml</replaceable> <optional>, <replaceable>nsarray</replaceable></optional>)
10407 The function <function>xpath</function> evaluates the XPath
10408 expression <replaceable>xpath</replaceable> (a <type>text</> value)
10409 against the XML value
10410 <replaceable>xml</replaceable>. It returns an array of XML values
10411 corresponding to the node set produced by the XPath expression.
10412 If the XPath expression returns a scalar value rather than a node set,
10413 a single-element array is returned.
10417 The second argument must be a well formed XML document. In particular,
10418 it must have a single root node element.
10422 The optional third argument of the function is an array of namespace
10423 mappings. This array should be a two-dimensional <type>text</> array with
10424 the length of the second axis being equal to 2 (i.e., it should be an
10425 array of arrays, each of which consists of exactly 2 elements).
10426 The first element of each array entry is the namespace name (alias), the
10427 second the namespace URI. It is not required that aliases provided in
10428 this array be the same as those being used in the XML document itself (in
10429 other words, both in the XML document and in the <function>xpath</function>
10430 function context, aliases are <emphasis>local</>).
10436 SELECT xpath('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
10437 ARRAY[ARRAY['my', 'http://example.com']]);
10447 To deal with default (anonymous) namespaces, do something like this:
10449 SELECT xpath('//mydefns:b/text()', '<a xmlns="http://example.com"><b>test</b></a>',
10450 ARRAY[ARRAY['mydefns', 'http://example.com']]);
10460 <sect3 id="functions-xml-processing-xpath-exists">
10461 <title><literal>xpath_exists</literal></title>
10464 <primary>xpath_exists</primary>
10468 <function>xpath_exists</function>(<replaceable>xpath</replaceable>, <replaceable>xml</replaceable> <optional>, <replaceable>nsarray</replaceable></optional>)
10472 The function <function>xpath_exists</function> is a specialized form
10473 of the <function>xpath</function> function. Instead of returning the
10474 individual XML values that satisfy the XPath, this function returns a
10475 Boolean indicating whether the query was satisfied or not. This
10476 function is equivalent to the standard <literal>XMLEXISTS</> predicate,
10477 except that it also offers support for a namespace mapping argument.
10483 SELECT xpath_exists('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
10484 ARRAY[ARRAY['my', 'http://example.com']]);
10494 <sect3 id="functions-xml-processing-xmltable">
10495 <title><literal>xmltable</literal></title>
10498 <primary>xmltable</primary>
10501 <indexterm zone="functions-xml-processing-xmltable">
10502 <primary>table function</primary>
10503 <secondary>XMLTABLE</secondary>
10507 <function>xmltable</function>( <optional>XMLNAMESPACES(<replaceable>namespace uri</replaceable> AS <replaceable>namespace name</replaceable><optional>, ...</optional>)</optional>
10508 <replaceable>row_expression</replaceable> PASSING <optional>BY REF</optional> <replaceable>document_expression</replaceable> <optional>BY REF</optional>
10509 COLUMNS <replaceable>name</replaceable> { <replaceable>type</replaceable> <optional>PATH <replaceable>column_expression</replaceable></optional> <optional>DEFAULT <replaceable>default_expression</replaceable></optional> <optional>NOT NULL | NULL</optional>
10511 <optional>, ...</optional>
10516 The <function>xmltable</function> function produces a table based
10517 on the given XML value, an XPath filter to extract rows, and an
10518 optional set of column definitions.
10522 The optional <literal>XMLNAMESPACES</> clause is a comma-separated
10523 list of namespaces. It specifies the XML namespaces used in
10524 the document and their aliases. A default namespace specification
10525 is not currently supported.
10529 The required <replaceable>row_expression</> argument is an XPath
10530 expression that is evaluated against the supplied XML document to
10531 obtain an ordered sequence of XML nodes. This sequence is what
10532 <function>xmltable</> transforms into output rows.
10536 <replaceable>document_expression</> provides the XML document to
10538 The <literal>BY REF</literal> clauses have no effect in PostgreSQL,
10539 but are allowed for SQL conformance and compatibility with other
10541 The argument must be a well-formed XML document; fragments/forests
10546 The mandatory <literal>COLUMNS</literal> clause specifies the list
10547 of columns in the output table.
10548 If the <literal>COLUMNS</> clause is omitted, the rows in the result
10549 set contain a single column of type <literal>xml</> containing the
10550 data matched by <replaceable>row_expression</>.
10551 If <literal>COLUMNS</literal> is specified, each entry describes a
10553 See the syntax summary above for the format.
10554 The column name and type are required; the path, default and
10555 nullability clauses are optional.
10559 A column marked <literal>FOR ORDINALITY</literal> will be populated
10560 with row numbers matching the order in which the
10561 output rows appeared in the original input XML document.
10562 At most one column may be marked <literal>FOR ORDINALITY</literal>.
10566 The <literal>column_expression</> for a column is an XPath expression
10567 that is evaluated for each row, relative to the result of the
10568 <replaceable>row_expression</>, to find the value of the column.
10569 If no <literal>column_expression</> is given, then the column name
10570 is used as an implicit path.
10574 If a column's XPath expression returns multiple elements, an error
10576 If the expression matches an empty tag, the result is an
10577 empty string (not <literal>NULL</>).
10578 Any <literal>xsi:nil</> attributes are ignored.
10582 The text body of the XML matched by the <replaceable>column_expression</>
10583 is used as the column value. Multiple <literal>text()</literal> nodes
10584 within an element are concatenated in order. Any child elements,
10585 processing instructions, and comments are ignored, but the text contents
10586 of child elements are concatenated to the result.
10587 Note that the whitespace-only <literal>text()</> node between two non-text
10588 elements is preserved, and that leading whitespace on a <literal>text()</>
10589 node is not flattened.
10593 If the path expression does not match for a given row but
10594 <replaceable>default_expression</> is specified, the value resulting
10595 from evaluating that expression is used.
10596 If no <literal>DEFAULT</> clause is given for the column,
10597 the field will be set to <literal>NULL</>.
10598 It is possible for a <replaceable>default_expression</> to reference
10599 the value of output columns that appear prior to it in the column list,
10600 so the default of one column may be based on the value of another
10605 Columns may be marked <literal>NOT NULL</>. If the
10606 <replaceable>column_expression</> for a <literal>NOT NULL</> column
10607 does not match anything and there is no <literal>DEFAULT</> or the
10608 <replaceable>default_expression</> also evaluates to null, an error
10613 Unlike regular PostgreSQL functions, <replaceable>column_expression</>
10614 and <replaceable>default_expression</> are not evaluated to a simple
10615 value before calling the function.
10616 <replaceable>column_expression</> is normally evaluated
10617 exactly once per input row, and <replaceable>default_expression</>
10618 is evaluated each time a default is needed for a field.
10619 If the expression qualifies as stable or immutable the repeat
10620 evaluation may be skipped.
10621 Effectively <function>xmltable</> behaves more like a subquery than a
10623 This means that you can usefully use volatile functions like
10624 <function>nextval</> in <replaceable>default_expression</>, and
10625 <replaceable>column_expression</> may depend on other parts of the
10632 CREATE TABLE xmldata AS SELECT
10636 <COUNTRY_ID>AU</COUNTRY_ID>
10637 <COUNTRY_NAME>Australia</COUNTRY_NAME>
10640 <COUNTRY_ID>JP</COUNTRY_ID>
10641 <COUNTRY_NAME>Japan</COUNTRY_NAME>
10642 <PREMIER_NAME>Shinzo Abe</PREMIER_NAME>
10643 <SIZE unit="sq_mi">145935</SIZE>
10646 <COUNTRY_ID>SG</COUNTRY_ID>
10647 <COUNTRY_NAME>Singapore</COUNTRY_NAME>
10648 <SIZE unit="sq_km">697</SIZE>
10655 XMLTABLE('//ROWS/ROW'
10657 COLUMNS id int PATH '@id',
10658 ordinality FOR ORDINALITY,
10659 "COUNTRY_NAME" text,
10660 country_id text PATH 'COUNTRY_ID',
10661 size_sq_km float PATH 'SIZE[@unit = "sq_km"]',
10662 size_other text PATH
10663 'concat(SIZE[@unit!="sq_km"], " ", SIZE[@unit!="sq_km"]/@unit)',
10664 premier_name text PATH 'PREMIER_NAME' DEFAULT 'not specified') ;
10666 id | ordinality | COUNTRY_NAME | country_id | size_sq_km | size_other | premier_name
10667 ----+------------+--------------+------------+------------+--------------+---------------
10668 1 | 1 | Australia | AU | | | not specified
10669 5 | 2 | Japan | JP | | 145935 sq_mi | Shinzo Abe
10670 6 | 3 | Singapore | SG | 697 | | not specified
10673 The following example shows concatenation of multiple text() nodes,
10674 usage of the column name as XPath filter, and the treatment of whitespace,
10675 XML comments and processing instructions:
10678 CREATE TABLE xmlelements AS SELECT
10681 <element> Hello<!-- xyxxz -->2a2<?aaaaa?> <!--x--> bbb<x>xxx</x>CC </element>
10686 FROM xmlelements, XMLTABLE('/root' PASSING data COLUMNS element text);
10688 ----------------------
10695 <sect2 id="functions-xml-mapping">
10696 <title>Mapping Tables to XML</title>
10698 <indexterm zone="functions-xml-mapping">
10699 <primary>XML export</primary>
10703 The following functions map the contents of relational tables to
10704 XML values. They can be thought of as XML export functionality:
10706 table_to_xml(tbl regclass, nulls boolean, tableforest boolean, targetns text)
10707 query_to_xml(query text, nulls boolean, tableforest boolean, targetns text)
10708 cursor_to_xml(cursor refcursor, count int, nulls boolean,
10709 tableforest boolean, targetns text)
10711 The return type of each function is <type>xml</type>.
10715 <function>table_to_xml</function> maps the content of the named
10716 table, passed as parameter <parameter>tbl</parameter>. The
10717 <type>regclass</type> type accepts strings identifying tables using the
10718 usual notation, including optional schema qualifications and
10719 double quotes. <function>query_to_xml</function> executes the
10720 query whose text is passed as parameter
10721 <parameter>query</parameter> and maps the result set.
10722 <function>cursor_to_xml</function> fetches the indicated number of
10723 rows from the cursor specified by the parameter
10724 <parameter>cursor</parameter>. This variant is recommended if
10725 large tables have to be mapped, because the result value is built
10726 up in memory by each function.
10730 If <parameter>tableforest</parameter> is false, then the resulting
10731 XML document looks like this:
10735 <columnname1>data</columnname1>
10736 <columnname2>data</columnname2>
10747 If <parameter>tableforest</parameter> is true, the result is an
10748 XML content fragment that looks like this:
10751 <columnname1>data</columnname1>
10752 <columnname2>data</columnname2>
10762 If no table name is available, that is, when mapping a query or a
10763 cursor, the string <literal>table</literal> is used in the first
10764 format, <literal>row</literal> in the second format.
10768 The choice between these formats is up to the user. The first
10769 format is a proper XML document, which will be important in many
10770 applications. The second format tends to be more useful in the
10771 <function>cursor_to_xml</function> function if the result values are to be
10772 reassembled into one document later on. The functions for
10773 producing XML content discussed above, in particular
10774 <function>xmlelement</function>, can be used to alter the results
10779 The data values are mapped in the same way as described for the
10780 function <function>xmlelement</function> above.
10784 The parameter <parameter>nulls</parameter> determines whether null
10785 values should be included in the output. If true, null values in
10786 columns are represented as:
10788 <columnname xsi:nil="true"/>
10790 where <literal>xsi</literal> is the XML namespace prefix for XML
10791 Schema Instance. An appropriate namespace declaration will be
10792 added to the result value. If false, columns containing null
10793 values are simply omitted from the output.
10797 The parameter <parameter>targetns</parameter> specifies the
10798 desired XML namespace of the result. If no particular namespace
10799 is wanted, an empty string should be passed.
10803 The following functions return XML Schema documents describing the
10804 mappings performed by the corresponding functions above:
10806 table_to_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text)
10807 query_to_xmlschema(query text, nulls boolean, tableforest boolean, targetns text)
10808 cursor_to_xmlschema(cursor refcursor, nulls boolean, tableforest boolean, targetns text)
10810 It is essential that the same parameters are passed in order to
10811 obtain matching XML data mappings and XML Schema documents.
10815 The following functions produce XML data mappings and the
10816 corresponding XML Schema in one document (or forest), linked
10817 together. They can be useful where self-contained and
10818 self-describing results are wanted:
10820 table_to_xml_and_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text)
10821 query_to_xml_and_xmlschema(query text, nulls boolean, tableforest boolean, targetns text)
10826 In addition, the following functions are available to produce
10827 analogous mappings of entire schemas or the entire current
10830 schema_to_xml(schema name, nulls boolean, tableforest boolean, targetns text)
10831 schema_to_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text)
10832 schema_to_xml_and_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text)
10834 database_to_xml(nulls boolean, tableforest boolean, targetns text)
10835 database_to_xmlschema(nulls boolean, tableforest boolean, targetns text)
10836 database_to_xml_and_xmlschema(nulls boolean, tableforest boolean, targetns text)
10839 Note that these potentially produce a lot of data, which needs to
10840 be built up in memory. When requesting content mappings of large
10841 schemas or databases, it might be worthwhile to consider mapping the
10842 tables separately instead, possibly even through a cursor.
10846 The result of a schema content mapping looks like this:
10857 </schemaname>]]></screen>
10859 where the format of a table mapping depends on the
10860 <parameter>tableforest</parameter> parameter as explained above.
10864 The result of a database content mapping looks like this:
10879 </dbname>]]></screen>
10881 where the schema mapping is as above.
10885 As an example of using the output produced by these functions,
10886 <xref linkend="xslt-xml-html"> shows an XSLT stylesheet that
10887 converts the output of
10888 <function>table_to_xml_and_xmlschema</function> to an HTML
10889 document containing a tabular rendition of the table data. In a
10890 similar manner, the results from these functions can be
10891 converted into other XML-based formats.
10894 <figure id="xslt-xml-html">
10895 <title>XSLT Stylesheet for Converting SQL/XML Output to HTML</title>
10896 <programlisting><![CDATA[
10897 <?xml version="1.0"?>
10898 <xsl:stylesheet version="1.0"
10899 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
10900 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
10901 xmlns="http://www.w3.org/1999/xhtml"
10904 <xsl:output method="xml"
10905 doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
10906 doctype-public="-//W3C/DTD XHTML 1.0 Strict//EN"
10909 <xsl:template match="/*">
10910 <xsl:variable name="schema" select="//xsd:schema"/>
10911 <xsl:variable name="tabletypename"
10912 select="$schema/xsd:element[@name=name(current())]/@type"/>
10913 <xsl:variable name="rowtypename"
10914 select="$schema/xsd:complexType[@name=$tabletypename]/xsd:sequence/xsd:element[@name='row']/@type"/>
10918 <title><xsl:value-of select="name(current())"/></title>
10923 <xsl:for-each select="$schema/xsd:complexType[@name=$rowtypename]/xsd:sequence/xsd:element/@name">
10924 <th><xsl:value-of select="."/></th>
10928 <xsl:for-each select="row">
10930 <xsl:for-each select="*">
10931 <td><xsl:value-of select="."/></td>
10941 ]]></programlisting>
10946 <sect1 id="functions-json">
10947 <title>JSON Functions and Operators</title>
10949 <indexterm zone="functions-json">
10950 <primary>JSON</primary>
10951 <secondary>functions and operators</secondary>
10955 <xref linkend="functions-json-op-table"> shows the operators that
10956 are available for use with the two JSON data types (see <xref
10957 linkend="datatype-json">).
10960 <table id="functions-json-op-table">
10961 <title><type>json</> and <type>jsonb</> Operators</title>
10965 <entry>Operator</entry>
10966 <entry>Right Operand Type</entry>
10967 <entry>Description</entry>
10968 <entry>Example</entry>
10969 <entry>Example Result</entry>
10974 <entry><literal>-></literal></entry>
10975 <entry><type>int</type></entry>
10976 <entry>Get JSON array element (indexed from zero, negative
10977 integers count from the end)</entry>
10978 <entry><literal>'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json->2</literal></entry>
10979 <entry><literal>{"c":"baz"}</literal></entry>
10982 <entry><literal>-></literal></entry>
10983 <entry><type>text</type></entry>
10984 <entry>Get JSON object field by key</entry>
10985 <entry><literal>'{"a": {"b":"foo"}}'::json->'a'</literal></entry>
10986 <entry><literal>{"b":"foo"}</literal></entry>
10989 <entry><literal>->></literal></entry>
10990 <entry><type>int</type></entry>
10991 <entry>Get JSON array element as <type>text</></entry>
10992 <entry><literal>'[1,2,3]'::json->>2</literal></entry>
10993 <entry><literal>3</literal></entry>
10996 <entry><literal>->></literal></entry>
10997 <entry><type>text</type></entry>
10998 <entry>Get JSON object field as <type>text</></entry>
10999 <entry><literal>'{"a":1,"b":2}'::json->>'b'</literal></entry>
11000 <entry><literal>2</literal></entry>
11003 <entry><literal>#></literal></entry>
11004 <entry><type>text[]</type></entry>
11005 <entry>Get JSON object at specified path</entry>
11006 <entry><literal>'{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}'</literal></entry>
11007 <entry><literal>{"c": "foo"}</literal></entry>
11010 <entry><literal>#>></literal></entry>
11011 <entry><type>text[]</type></entry>
11012 <entry>Get JSON object at specified path as <type>text</></entry>
11013 <entry><literal>'{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'</literal></entry>
11014 <entry><literal>3</literal></entry>
11022 There are parallel variants of these operators for both the
11023 <type>json</type> and <type>jsonb</type> types.
11024 The field/element/path extraction operators
11025 return the same type as their left-hand input (either <type>json</type>
11026 or <type>jsonb</type>), except for those specified as
11027 returning <type>text</>, which coerce the value to text.
11028 The field/element/path extraction operators return NULL, rather than
11029 failing, if the JSON input does not have the right structure to match
11030 the request; for example if no such element exists. The
11031 field/element/path extraction operators that accept integer JSON
11032 array subscripts all support negative subscripting from the end of
11037 The standard comparison operators shown in <xref
11038 linkend="functions-comparison-op-table"> are available for
11039 <type>jsonb</type>, but not for <type>json</type>. They follow the
11040 ordering rules for B-tree operations outlined at <xref
11041 linkend="json-indexing">.
11044 Some further operators also exist only for <type>jsonb</type>, as shown
11045 in <xref linkend="functions-jsonb-op-table">.
11046 Many of these operators can be indexed by
11047 <type>jsonb</> operator classes. For a full description of
11048 <type>jsonb</> containment and existence semantics, see <xref
11049 linkend="json-containment">. <xref linkend="json-indexing">
11050 describes how these operators can be used to effectively index
11051 <type>jsonb</> data.
11053 <table id="functions-jsonb-op-table">
11054 <title>Additional <type>jsonb</> Operators</title>
11058 <entry>Operator</entry>
11059 <entry>Right Operand Type</entry>
11060 <entry>Description</entry>
11061 <entry>Example</entry>
11066 <entry><literal>@></literal></entry>
11067 <entry><type>jsonb</type></entry>
11068 <entry>Does the left JSON value contain the right JSON
11069 path/value entries at the top level?</entry>
11070 <entry><literal>'{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonb</literal></entry>
11073 <entry><literal><@</literal></entry>
11074 <entry><type>jsonb</type></entry>
11075 <entry>Are the left JSON path/value entries contained at the top level within
11076 the right JSON value?</entry>
11077 <entry><literal>'{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb</literal></entry>
11080 <entry><literal>?</literal></entry>
11081 <entry><type>text</type></entry>
11082 <entry>Does the <emphasis>string</emphasis> exist as a top-level
11083 key within the JSON value?</entry>
11084 <entry><literal>'{"a":1, "b":2}'::jsonb ? 'b'</literal></entry>
11087 <entry><literal>?|</literal></entry>
11088 <entry><type>text[]</type></entry>
11089 <entry>Do any of these array <emphasis>strings</emphasis>
11090 exist as top-level keys?</entry>
11091 <entry><literal>'{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']</literal></entry>
11094 <entry><literal>?&</literal></entry>
11095 <entry><type>text[]</type></entry>
11096 <entry>Do all of these array <emphasis>strings</emphasis> exist
11097 as top-level keys?</entry>
11098 <entry><literal>'["a", "b"]'::jsonb ?& array['a', 'b']</literal></entry>
11101 <entry><literal>||</literal></entry>
11102 <entry><type>jsonb</type></entry>
11103 <entry>Concatenate two <type>jsonb</type> values into a new <type>jsonb</type> value</entry>
11104 <entry><literal>'["a", "b"]'::jsonb || '["c", "d"]'::jsonb</literal></entry>
11107 <entry><literal>-</literal></entry>
11108 <entry><type>text</type></entry>
11109 <entry>Delete key/value pair or <emphasis>string</emphasis>
11110 element from left operand. Key/value pairs are matched based
11111 on their key value.</entry>
11112 <entry><literal>'{"a": "b"}'::jsonb - 'a' </literal></entry>
11115 <entry><literal>-</literal></entry>
11116 <entry><type>text[]</type></entry>
11117 <entry>Delete multiple key/value pairs or <emphasis>string</emphasis>
11118 elements from left operand. Key/value pairs are matched based
11119 on their key value.</entry>
11120 <entry><literal>'{"a": "b", "c": "d"}'::jsonb - '{a,c}'::text[] </literal></entry>
11123 <entry><literal>-</literal></entry>
11124 <entry><type>integer</type></entry>
11125 <entry>Delete the array element with specified index (Negative
11126 integers count from the end). Throws an error if top level
11127 container is not an array.</entry>
11128 <entry><literal>'["a", "b"]'::jsonb - 1 </literal></entry>
11131 <entry><literal>#-</literal></entry>
11132 <entry><type>text[]</type></entry>
11133 <entry>Delete the field or element with specified path (for
11134 JSON arrays, negative integers count from the end)</entry>
11135 <entry><literal>'["a", {"b":1}]'::jsonb #- '{1,b}'</literal></entry>
11143 The <literal>||</> operator concatenates the elements at the top level of
11144 each of its operands. It does not operate recursively. For example, if
11145 both operands are objects with a common key field name, the value of the
11146 field in the result will just be the value from the right hand operand.
11151 <xref linkend="functions-json-creation-table"> shows the functions that are
11152 available for creating <type>json</type> and <type>jsonb</type> values.
11153 (There are no equivalent functions for <type>jsonb</>, of the <literal>row_to_json</>
11154 and <literal>array_to_json</> functions. However, the <literal>to_jsonb</>
11155 function supplies much the same functionality as these functions would.)
11159 <primary>to_json</primary>
11162 <primary>array_to_json</primary>
11165 <primary>row_to_json</primary>
11168 <primary>json_build_array</primary>
11171 <primary>json_build_object</primary>
11174 <primary>json_object</primary>
11177 <primary>to_jsonb</primary>
11180 <primary>jsonb_build_array</primary>
11183 <primary>jsonb_build_object</primary>
11186 <primary>jsonb_object</primary>
11189 <table id="functions-json-creation-table">
11190 <title>JSON Creation Functions</title>
11194 <entry>Function</entry>
11195 <entry>Description</entry>
11196 <entry>Example</entry>
11197 <entry>Example Result</entry>
11202 <entry><para><literal>to_json(anyelement)</literal>
11203 </para><para><literal>to_jsonb(anyelement)</literal>
11206 Returns the value as <type>json</> or <type>jsonb</>.
11207 Arrays and composites are converted
11208 (recursively) to arrays and objects; otherwise, if there is a cast
11209 from the type to <type>json</type>, the cast function will be used to
11210 perform the conversion; otherwise, a scalar value is produced.
11211 For any scalar type other than a number, a Boolean, or a null value,
11212 the text representation will be used, in such a fashion that it is a
11213 valid <type>json</> or <type>jsonb</> value.
11215 <entry><literal>to_json('Fred said "Hi."'::text)</literal></entry>
11216 <entry><literal>"Fred said \"Hi.\""</literal></entry>
11220 <literal>array_to_json(anyarray [, pretty_bool])</literal>
11223 Returns the array as a JSON array. A PostgreSQL multidimensional array
11224 becomes a JSON array of arrays. Line feeds will be added between
11225 dimension-1 elements if <parameter>pretty_bool</parameter> is true.
11227 <entry><literal>array_to_json('{{1,5},{99,100}}'::int[])</literal></entry>
11228 <entry><literal>[[1,5],[99,100]]</literal></entry>
11232 <literal>row_to_json(record [, pretty_bool])</literal>
11235 Returns the row as a JSON object. Line feeds will be added between
11236 level-1 elements if <parameter>pretty_bool</parameter> is true.
11238 <entry><literal>row_to_json(row(1,'foo'))</literal></entry>
11239 <entry><literal>{"f1":1,"f2":"foo"}</literal></entry>
11242 <entry><para><literal>json_build_array(VARIADIC "any")</literal>
11243 </para><para><literal>jsonb_build_array(VARIADIC "any")</literal>
11246 Builds a possibly-heterogeneously-typed JSON array out of a variadic
11249 <entry><literal>json_build_array(1,2,'3',4,5)</literal></entry>
11250 <entry><literal>[1, 2, "3", 4, 5]</literal></entry>
11253 <entry><para><literal>json_build_object(VARIADIC "any")</literal>
11254 </para><para><literal>jsonb_build_object(VARIADIC "any")</literal>
11257 Builds a JSON object out of a variadic argument list. By
11258 convention, the argument list consists of alternating
11261 <entry><literal>json_build_object('foo',1,'bar',2)</literal></entry>
11262 <entry><literal>{"foo": 1, "bar": 2}</literal></entry>
11265 <entry><para><literal>json_object(text[])</literal>
11266 </para><para><literal>jsonb_object(text[])</literal>
11269 Builds a JSON object out of a text array. The array must have either
11270 exactly one dimension with an even number of members, in which case
11271 they are taken as alternating key/value pairs, or two dimensions
11272 such that each inner array has exactly two elements, which
11273 are taken as a key/value pair.
11275 <entry><para><literal>json_object('{a, 1, b, "def", c, 3.5}')</></para>
11276 <para><literal>json_object('{{a, 1},{b, "def"},{c, 3.5}}')</></para></entry>
11277 <entry><literal>{"a": "1", "b": "def", "c": "3.5"}</literal></entry>
11280 <entry><para><literal>json_object(keys text[], values text[])</literal>
11281 </para><para><literal>jsonb_object(keys text[], values text[])</literal>
11284 This form of <function>json_object</> takes keys and values pairwise from two separate
11285 arrays. In all other respects it is identical to the one-argument form.
11287 <entry><literal>json_object('{a, b}', '{1,2}')</literal></entry>
11288 <entry><literal>{"a": "1", "b": "2"}</literal></entry>
11296 <function>array_to_json</> and <function>row_to_json</> have the same
11297 behavior as <function>to_json</> except for offering a pretty-printing
11298 option. The behavior described for <function>to_json</> likewise applies
11299 to each individual value converted by the other JSON creation functions.
11305 The <xref linkend="hstore"> extension has a cast
11306 from <type>hstore</type> to <type>json</type>, so that
11307 <type>hstore</type> values converted via the JSON creation functions
11308 will be represented as JSON objects, not as primitive string values.
11313 <xref linkend="functions-json-processing-table"> shows the functions that
11314 are available for processing <type>json</type> and <type>jsonb</type> values.
11318 <primary>json_array_length</primary>
11321 <primary>jsonb_array_length</primary>
11324 <primary>json_each</primary>
11327 <primary>jsonb_each</primary>
11330 <primary>json_each_text</primary>
11333 <primary>jsonb_each_text</primary>
11336 <primary>json_extract_path</primary>
11339 <primary>jsonb_extract_path</primary>
11342 <primary>json_extract_path_text</primary>
11345 <primary>jsonb_extract_path_text</primary>
11348 <primary>json_object_keys</primary>
11351 <primary>jsonb_object_keys</primary>
11354 <primary>json_populate_record</primary>
11357 <primary>jsonb_populate_record</primary>
11360 <primary>json_populate_recordset</primary>
11363 <primary>jsonb_populate_recordset</primary>
11366 <primary>json_array_elements</primary>
11369 <primary>jsonb_array_elements</primary>
11372 <primary>json_array_elements_text</primary>
11375 <primary>jsonb_array_elements_text</primary>
11378 <primary>json_typeof</primary>
11381 <primary>jsonb_typeof</primary>
11384 <primary>json_to_record</primary>
11387 <primary>jsonb_to_record</primary>
11390 <primary>json_to_recordset</primary>
11393 <primary>jsonb_to_recordset</primary>
11396 <primary>json_strip_nulls</primary>
11399 <primary>jsonb_strip_nulls</primary>
11402 <primary>jsonb_set</primary>
11405 <primary>jsonb_insert</primary>
11408 <primary>jsonb_pretty</primary>
11411 <table id="functions-json-processing-table">
11412 <title>JSON Processing Functions</title>
11416 <entry>Function</entry>
11417 <entry>Return Type</entry>
11418 <entry>Description</entry>
11419 <entry>Example</entry>
11420 <entry>Example Result</entry>
11425 <entry><para><literal>json_array_length(json)</literal>
11426 </para><para><literal>jsonb_array_length(jsonb)</literal>
11428 <entry><type>int</type></entry>
11430 Returns the number of elements in the outermost JSON array.
11432 <entry><literal>json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]')</literal></entry>
11433 <entry><literal>5</literal></entry>
11436 <entry><para><literal>json_each(json)</literal>
11437 </para><para><literal>jsonb_each(jsonb)</literal>
11439 <entry><para><literal>setof key text, value json</literal>
11440 </para><para><literal>setof key text, value jsonb</literal>
11443 Expands the outermost JSON object into a set of key/value pairs.
11445 <entry><literal>select * from json_each('{"a":"foo", "b":"bar"}')</literal></entry>
11456 <entry><para><literal>json_each_text(json)</literal>
11457 </para><para><literal>jsonb_each_text(jsonb)</literal>
11459 <entry><type>setof key text, value text</type></entry>
11461 Expands the outermost JSON object into a set of key/value pairs. The
11462 returned values will be of type <type>text</>.
11464 <entry><literal>select * from json_each_text('{"a":"foo", "b":"bar"}')</literal></entry>
11475 <entry><para><literal>json_extract_path(from_json json, VARIADIC path_elems text[])</literal>
11476 </para><para><literal>jsonb_extract_path(from_json jsonb, VARIADIC path_elems text[])</literal>
11478 <entry><para><type>json</type></para><para><type>jsonb</type>
11481 Returns JSON value pointed to by <replaceable>path_elems</replaceable>
11482 (equivalent to <literal>#></literal> operator).
11484 <entry><literal>json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4')</literal></entry>
11485 <entry><literal>{"f5":99,"f6":"foo"}</literal></entry>
11488 <entry><para><literal>json_extract_path_text(from_json json, VARIADIC path_elems text[])</literal>
11489 </para><para><literal>jsonb_extract_path_text(from_json jsonb, VARIADIC path_elems text[])</literal>
11491 <entry><type>text</type></entry>
11493 Returns JSON value pointed to by <replaceable>path_elems</replaceable>
11495 (equivalent to <literal>#>></literal> operator).
11497 <entry><literal>json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4', 'f6')</literal></entry>
11498 <entry><literal>foo</literal></entry>
11501 <entry><para><literal>json_object_keys(json)</literal>
11502 </para><para><literal>jsonb_object_keys(jsonb)</literal>
11504 <entry><type>setof text</type></entry>
11506 Returns set of keys in the outermost JSON object.
11508 <entry><literal>json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')</literal></entry>
11519 <entry><para><literal>json_populate_record(base anyelement, from_json json)</literal>
11520 </para><para><literal>jsonb_populate_record(base anyelement, from_json jsonb)</literal>
11522 <entry><type>anyelement</type></entry>
11524 Expands the object in <replaceable>from_json</replaceable> to a row
11525 whose columns match the record type defined by <replaceable>base</>
11528 <entry><literal>select * from json_populate_record(null::myrowtype, '{"a":1,"b":2}')</literal></entry>
11538 <entry><para><literal>json_populate_recordset(base anyelement, from_json json)</literal>
11539 </para><para><literal>jsonb_populate_recordset(base anyelement, from_json jsonb)</literal>
11541 <entry><type>setof anyelement</type></entry>
11543 Expands the outermost array of objects
11544 in <replaceable>from_json</replaceable> to a set of rows whose
11545 columns match the record type defined by <replaceable>base</> (see
11548 <entry><literal>select * from json_populate_recordset(null::myrowtype, '[{"a":1,"b":2},{"a":3,"b":4}]')</literal></entry>
11559 <entry><para><literal>json_array_elements(json)</literal>
11560 </para><para><literal>jsonb_array_elements(jsonb)</literal>
11562 <entry><para><type>setof json</type>
11563 </para><para><type>setof jsonb</type>
11566 Expands a JSON array to a set of JSON values.
11568 <entry><literal>select * from json_array_elements('[1,true, [2,false]]')</literal></entry>
11580 <entry><para><literal>json_array_elements_text(json)</literal>
11581 </para><para><literal>jsonb_array_elements_text(jsonb)</literal>
11583 <entry><type>setof text</type></entry>
11585 Expands a JSON array to a set of <type>text</> values.
11587 <entry><literal>select * from json_array_elements_text('["foo", "bar"]')</literal></entry>
11598 <entry><para><literal>json_typeof(json)</literal>
11599 </para><para><literal>jsonb_typeof(jsonb)</literal>
11601 <entry><type>text</type></entry>
11603 Returns the type of the outermost JSON value as a text string.
11605 <literal>object</>, <literal>array</>, <literal>string</>, <literal>number</>,
11606 <literal>boolean</>, and <literal>null</>.
11608 <entry><literal>json_typeof('-123.4')</literal></entry>
11609 <entry><literal>number</literal></entry>
11612 <entry><para><literal>json_to_record(json)</literal>
11613 </para><para><literal>jsonb_to_record(jsonb)</literal>
11615 <entry><type>record</type></entry>
11617 Builds an arbitrary record from a JSON object (see note below). As
11618 with all functions returning <type>record</>, the caller must
11619 explicitly define the structure of the record with an <literal>AS</>
11622 <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>
11632 <entry><para><literal>json_to_recordset(json)</literal>
11633 </para><para><literal>jsonb_to_recordset(jsonb)</literal>
11635 <entry><type>setof record</type></entry>
11637 Builds an arbitrary set of records from a JSON array of objects (see
11638 note below). As with all functions returning <type>record</>, the
11639 caller must explicitly define the structure of the record with
11640 an <literal>AS</> clause.
11642 <entry><literal>select * from json_to_recordset('[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]') as x(a int, b text);</literal></entry>
11653 <entry><para><literal>json_strip_nulls(from_json json)</literal>
11654 </para><para><literal>jsonb_strip_nulls(from_json jsonb)</literal>
11656 <entry><para><type>json</type></para><para><type>jsonb</type></para></entry>
11658 Returns <replaceable>from_json</replaceable>
11659 with all object fields that have null values omitted. Other null values
11662 <entry><literal>json_strip_nulls('[{"f1":1,"f2":null},2,null,3]')</literal></entry>
11663 <entry><literal>[{"f1":1},2,null,3]</literal></entry>
11666 <entry><para><literal>jsonb_set(target jsonb, path text[], new_value jsonb<optional>, <parameter>create_missing</parameter> <type>boolean</type></optional>)</literal>
11668 <entry><para><type>jsonb</type></para></entry>
11670 Returns <replaceable>target</replaceable>
11671 with the section designated by <replaceable>path</replaceable>
11672 replaced by <replaceable>new_value</replaceable>, or with
11673 <replaceable>new_value</replaceable> added if
11674 <replaceable>create_missing</replaceable> is true ( default is
11675 <literal>true</>) and the item
11676 designated by <replaceable>path</replaceable> does not exist.
11677 As with the path orientated operators, negative integers that
11678 appear in <replaceable>path</replaceable> count from the end
11681 <entry><para><literal>jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}','[2,3,4]', false)</literal>
11682 </para><para><literal>jsonb_set('[{"f1":1,"f2":null},2]', '{0,f3}','[2,3,4]')</literal>
11684 <entry><para><literal>[{"f1":[2,3,4],"f2":null},2,null,3]</literal>
11685 </para><para><literal>[{"f1": 1, "f2": null, "f3": [2, 3, 4]}, 2]</literal>
11691 jsonb_insert(target jsonb, path text[], new_value jsonb, <optional><parameter>insert_after</parameter> <type>boolean</type></optional>)
11694 <entry><para><type>jsonb</type></para></entry>
11696 Returns <replaceable>target</replaceable> with
11697 <replaceable>new_value</replaceable> inserted. If
11698 <replaceable>target</replaceable> section designated by
11699 <replaceable>path</replaceable> is in a JSONB array,
11700 <replaceable>new_value</replaceable> will be inserted before target or
11701 after if <replaceable>insert_after</replaceable> is true (default is
11702 <literal>false</>). If <replaceable>target</replaceable> section
11703 designated by <replaceable>path</replaceable> is in JSONB object,
11704 <replaceable>new_value</replaceable> will be inserted only if
11705 <replaceable>target</replaceable> does not exist. As with the path
11706 orientated operators, negative integers that appear in
11707 <replaceable>path</replaceable> count from the end of JSON arrays.
11711 jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"')
11714 jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"', true)
11717 <entry><para><literal>{"a": [0, "new_value", 1, 2]}</literal>
11718 </para><para><literal>{"a": [0, 1, "new_value", 2]}</literal>
11722 <entry><para><literal>jsonb_pretty(from_json jsonb)</literal>
11724 <entry><para><type>text</type></para></entry>
11726 Returns <replaceable>from_json</replaceable>
11727 as indented JSON text.
11729 <entry><literal>jsonb_pretty('[{"f1":1,"f2":null},2,null,3]')</literal></entry>
11750 Many of these functions and operators will convert Unicode escapes in
11751 JSON strings to the appropriate single character. This is a non-issue
11752 if the input is type <type>jsonb</>, because the conversion was already
11753 done; but for <type>json</> input, this may result in throwing an error,
11754 as noted in <xref linkend="datatype-json">.
11760 In <function>json_populate_record</>, <function>json_populate_recordset</>,
11761 <function>json_to_record</> and <function>json_to_recordset</>,
11762 type coercion from the JSON is <quote>best effort</> and may not result
11763 in desired values for some types. JSON keys are matched to
11764 identical column names in the target row type. JSON fields that do not
11765 appear in the target row type will be omitted from the output, and
11766 target columns that do not match any JSON field will simply be NULL.
11772 All the items of the <literal>path</> parameter of <literal>jsonb_set</>
11773 as well as <literal>jsonb_insert</> except the last item must be present
11774 in the <literal>target</>. If <literal>create_missing</> is false, all
11775 items of the <literal>path</> parameter of <literal>jsonb_set</> must be
11776 present. If these conditions are not met the <literal>target</> is
11777 returned unchanged.
11780 If the last path item is an object key, it will be created if it
11781 is absent and given the new value. If the last path item is an array
11782 index, if it is positive the item to set is found by counting from
11783 the left, and if negative by counting from the right - <literal>-1</>
11784 designates the rightmost element, and so on.
11785 If the item is out of the range -array_length .. array_length -1,
11786 and create_missing is true, the new value is added at the beginning
11787 of the array if the item is negative, and at the end of the array if
11794 The <literal>json_typeof</> function's <literal>null</> return value
11795 should not be confused with a SQL NULL. While
11796 calling <literal>json_typeof('null'::json)</> will
11797 return <literal>null</>, calling <literal>json_typeof(NULL::json)</>
11798 will return a SQL NULL.
11804 If the argument to <literal>json_strip_nulls</> contains duplicate
11805 field names in any object, the result could be semantically somewhat
11806 different, depending on the order in which they occur. This is not an
11807 issue for <literal>jsonb_strip_nulls</> since <type>jsonb</type> values never have
11808 duplicate object field names.
11813 See also <xref linkend="functions-aggregate"> for the aggregate
11814 function <function>json_agg</function> which aggregates record
11815 values as JSON, and the aggregate function
11816 <function>json_object_agg</function> which aggregates pairs of values
11817 into a JSON object, and their <type>jsonb</type> equivalents,
11818 <function>jsonb_agg</> and <function>jsonb_object_agg</>.
11823 <sect1 id="functions-sequence">
11824 <title>Sequence Manipulation Functions</title>
11827 <primary>sequence</primary>
11830 <primary>nextval</primary>
11833 <primary>currval</primary>
11836 <primary>lastval</primary>
11839 <primary>setval</primary>
11843 This section describes functions for operating on <firstterm>sequence
11844 objects</firstterm>, also called sequence generators or just sequences.
11845 Sequence objects are special single-row tables created with <xref
11846 linkend="sql-createsequence">.
11847 Sequence objects are commonly used to generate unique identifiers
11848 for rows of a table. The sequence functions, listed in <xref
11849 linkend="functions-sequence-table">, provide simple, multiuser-safe
11850 methods for obtaining successive sequence values from sequence
11854 <table id="functions-sequence-table">
11855 <title>Sequence Functions</title>
11858 <row><entry>Function</entry> <entry>Return Type</entry> <entry>Description</entry></row>
11863 <entry><literal><function>currval(<type>regclass</type>)</function></literal></entry>
11864 <entry><type>bigint</type></entry>
11865 <entry>Return value most recently obtained with
11866 <function>nextval</function> for specified sequence</entry>
11869 <entry><literal><function>lastval()</function></literal></entry>
11870 <entry><type>bigint</type></entry>
11871 <entry>Return value most recently obtained with
11872 <function>nextval</function> for any sequence</entry>
11875 <entry><literal><function>nextval(<type>regclass</type>)</function></literal></entry>
11876 <entry><type>bigint</type></entry>
11877 <entry>Advance sequence and return new value</entry>
11880 <entry><literal><function>setval(<type>regclass</type>, <type>bigint</type>)</function></literal></entry>
11881 <entry><type>bigint</type></entry>
11882 <entry>Set sequence's current value</entry>
11885 <entry><literal><function>setval(<type>regclass</type>, <type>bigint</type>, <type>boolean</type>)</function></literal></entry>
11886 <entry><type>bigint</type></entry>
11887 <entry>Set sequence's current value and <literal>is_called</literal> flag</entry>
11894 The sequence to be operated on by a sequence function is specified by
11895 a <type>regclass</> argument, which is simply the OID of the sequence in the
11896 <structname>pg_class</> system catalog. You do not have to look up the
11897 OID by hand, however, since the <type>regclass</> data type's input
11898 converter will do the work for you. Just write the sequence name enclosed
11899 in single quotes so that it looks like a literal constant. For
11900 compatibility with the handling of ordinary
11901 <acronym>SQL</acronym> names, the string will be converted to lower case
11902 unless it contains double quotes around the sequence name. Thus:
11904 nextval('foo') <lineannotation>operates on sequence <literal>foo</literal></>
11905 nextval('FOO') <lineannotation>operates on sequence <literal>foo</literal></>
11906 nextval('"Foo"') <lineannotation>operates on sequence <literal>Foo</literal></>
11908 The sequence name can be schema-qualified if necessary:
11910 nextval('myschema.foo') <lineannotation>operates on <literal>myschema.foo</literal></>
11911 nextval('"myschema".foo') <lineannotation>same as above</lineannotation>
11912 nextval('foo') <lineannotation>searches search path for <literal>foo</literal></>
11914 See <xref linkend="datatype-oid"> for more information about
11920 Before <productname>PostgreSQL</productname> 8.1, the arguments of the
11921 sequence functions were of type <type>text</>, not <type>regclass</>, and
11922 the above-described conversion from a text string to an OID value would
11923 happen at run time during each call. For backward compatibility, this
11924 facility still exists, but internally it is now handled as an implicit
11925 coercion from <type>text</> to <type>regclass</> before the function is
11930 When you write the argument of a sequence function as an unadorned
11931 literal string, it becomes a constant of type <type>regclass</>.
11932 Since this is really just an OID, it will track the originally
11933 identified sequence despite later renaming, schema reassignment,
11934 etc. This <quote>early binding</> behavior is usually desirable for
11935 sequence references in column defaults and views. But sometimes you might
11936 want <quote>late binding</> where the sequence reference is resolved
11937 at run time. To get late-binding behavior, force the constant to be
11938 stored as a <type>text</> constant instead of <type>regclass</>:
11940 nextval('foo'::text) <lineannotation><literal>foo</literal> is looked up at runtime</>
11942 Note that late binding was the only behavior supported in
11943 <productname>PostgreSQL</productname> releases before 8.1, so you
11944 might need to do this to preserve the semantics of old applications.
11948 Of course, the argument of a sequence function can be an expression
11949 as well as a constant. If it is a text expression then the implicit
11950 coercion will result in a run-time lookup.
11955 The available sequence functions are:
11959 <term><function>nextval</function></term>
11962 Advance the sequence object to its next value and return that
11963 value. This is done atomically: even if multiple sessions
11964 execute <function>nextval</function> concurrently, each will safely receive
11965 a distinct sequence value.
11969 If a sequence object has been created with default parameters,
11970 successive <function>nextval</function> calls will return successive
11971 values beginning with 1. Other behaviors can be obtained by using
11972 special parameters in the <xref linkend="sql-createsequence"> command;
11973 see its command reference page for more information.
11978 To avoid blocking concurrent transactions that obtain numbers from
11979 the same sequence, a <function>nextval</function> operation is never
11980 rolled back; that is, once a value has been fetched it is considered
11981 used and will not be returned again. This is true even if the
11982 surrounding transaction later aborts, or if the calling query ends
11983 up not using the value. For example an <command>INSERT</> with
11984 an <literal>ON CONFLICT</> clause will compute the to-be-inserted
11985 tuple, including doing any required <function>nextval</function>
11986 calls, before detecting any conflict that would cause it to follow
11987 the <literal>ON CONFLICT</> rule instead. Such cases will leave
11988 unused <quote>holes</quote> in the sequence of assigned values.
11989 Thus, <productname>PostgreSQL</> sequence objects <emphasis>cannot
11990 be used to obtain <quote>gapless</> sequences</emphasis>.
11995 This function requires <literal>USAGE</literal>
11996 or <literal>UPDATE</literal> privilege on the sequence.
12002 <term><function>currval</function></term>
12005 Return the value most recently obtained by <function>nextval</function>
12006 for this sequence in the current session. (An error is
12007 reported if <function>nextval</function> has never been called for this
12008 sequence in this session.) Because this is returning
12009 a session-local value, it gives a predictable answer whether or not
12010 other sessions have executed <function>nextval</function> since the
12011 current session did.
12015 This function requires <literal>USAGE</literal>
12016 or <literal>SELECT</literal> privilege on the sequence.
12022 <term><function>lastval</function></term>
12025 Return the value most recently returned by
12026 <function>nextval</> in the current session. This function is
12027 identical to <function>currval</function>, except that instead
12028 of taking the sequence name as an argument it refers to whichever
12029 sequence <function>nextval</function> was most recently applied to
12030 in the current session. It is an error to call
12031 <function>lastval</function> if <function>nextval</function>
12032 has not yet been called in the current session.
12036 This function requires <literal>USAGE</literal>
12037 or <literal>SELECT</literal> privilege on the last used sequence.
12043 <term><function>setval</function></term>
12046 Reset the sequence object's counter value. The two-parameter
12047 form sets the sequence's <literal>last_value</literal> field to the
12048 specified value and sets its <literal>is_called</literal> field to
12049 <literal>true</literal>, meaning that the next
12050 <function>nextval</function> will advance the sequence before
12051 returning a value. The value reported by <function>currval</> is
12052 also set to the specified value. In the three-parameter form,
12053 <literal>is_called</literal> can be set to either <literal>true</literal>
12054 or <literal>false</literal>. <literal>true</> has the same effect as
12055 the two-parameter form. If it is set to <literal>false</literal>, the
12056 next <function>nextval</function> will return exactly the specified
12057 value, and sequence advancement commences with the following
12058 <function>nextval</function>. Furthermore, the value reported by
12059 <function>currval</> is not changed in this case. For example,
12062 SELECT setval('foo', 42); <lineannotation>Next <function>nextval</> will return 43</lineannotation>
12063 SELECT setval('foo', 42, true); <lineannotation>Same as above</lineannotation>
12064 SELECT setval('foo', 42, false); <lineannotation>Next <function>nextval</> will return 42</lineannotation>
12067 The result returned by <function>setval</function> is just the value of its
12072 Because sequences are non-transactional, changes made by
12073 <function>setval</function> are not undone if the transaction rolls
12079 This function requires <literal>UPDATE</literal> privilege on the
12090 <sect1 id="functions-conditional">
12091 <title>Conditional Expressions</title>
12094 <primary>CASE</primary>
12098 <primary>conditional expression</primary>
12102 This section describes the <acronym>SQL</acronym>-compliant conditional expressions
12103 available in <productname>PostgreSQL</productname>.
12108 If your needs go beyond the capabilities of these conditional
12109 expressions, you might want to consider writing a stored procedure
12110 in a more expressive programming language.
12114 <sect2 id="functions-case">
12115 <title><literal>CASE</></title>
12118 The <acronym>SQL</acronym> <token>CASE</token> expression is a
12119 generic conditional expression, similar to if/else statements in
12120 other programming languages:
12123 CASE WHEN <replaceable>condition</replaceable> THEN <replaceable>result</replaceable>
12124 <optional>WHEN ...</optional>
12125 <optional>ELSE <replaceable>result</replaceable></optional>
12129 <token>CASE</token> clauses can be used wherever
12130 an expression is valid. Each <replaceable>condition</replaceable> is an
12131 expression that returns a <type>boolean</type> result. If the condition's
12132 result is true, the value of the <token>CASE</token> expression is the
12133 <replaceable>result</replaceable> that follows the condition, and the
12134 remainder of the <token>CASE</token> expression is not processed. If the
12135 condition's result is not true, any subsequent <token>WHEN</token> clauses
12136 are examined in the same manner. If no <token>WHEN</token>
12137 <replaceable>condition</replaceable> yields true, the value of the
12138 <token>CASE</> expression is the <replaceable>result</replaceable> of the
12139 <token>ELSE</token> clause. If the <token>ELSE</token> clause is
12140 omitted and no condition is true, the result is null.
12146 SELECT * FROM test;
12156 CASE WHEN a=1 THEN 'one'
12157 WHEN a=2 THEN 'two'
12171 The data types of all the <replaceable>result</replaceable>
12172 expressions must be convertible to a single output type.
12173 See <xref linkend="typeconv-union-case"> for more details.
12177 There is a <quote>simple</> form of <token>CASE</token> expression
12178 that is a variant of the general form above:
12181 CASE <replaceable>expression</replaceable>
12182 WHEN <replaceable>value</replaceable> THEN <replaceable>result</replaceable>
12183 <optional>WHEN ...</optional>
12184 <optional>ELSE <replaceable>result</replaceable></optional>
12189 <replaceable>expression</replaceable> is computed, then compared to
12190 each of the <replaceable>value</replaceable> expressions in the
12191 <token>WHEN</token> clauses until one is found that is equal to it. If
12192 no match is found, the <replaceable>result</replaceable> of the
12193 <token>ELSE</token> clause (or a null value) is returned. This is similar
12194 to the <function>switch</function> statement in C.
12198 The example above can be written using the simple
12199 <token>CASE</token> syntax:
12202 CASE a WHEN 1 THEN 'one'
12217 A <token>CASE</token> expression does not evaluate any subexpressions
12218 that are not needed to determine the result. For example, this is a
12219 possible way of avoiding a division-by-zero failure:
12221 SELECT ... WHERE CASE WHEN x <> 0 THEN y/x > 1.5 ELSE false END;
12227 As described in <xref linkend="syntax-express-eval">, there are various
12228 situations in which subexpressions of an expression are evaluated at
12229 different times, so that the principle that <quote><token>CASE</token>
12230 evaluates only necessary subexpressions</quote> is not ironclad. For
12231 example a constant <literal>1/0</> subexpression will usually result in
12232 a division-by-zero failure at planning time, even if it's within
12233 a <token>CASE</token> arm that would never be entered at run time.
12238 <sect2 id="functions-coalesce-nvl-ifnull">
12239 <title><literal>COALESCE</></title>
12242 <primary>COALESCE</primary>
12246 <primary>NVL</primary>
12250 <primary>IFNULL</primary>
12254 <function>COALESCE</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
12258 The <function>COALESCE</function> function returns the first of its
12259 arguments that is not null. Null is returned only if all arguments
12260 are null. It is often used to substitute a default value for
12261 null values when data is retrieved for display, for example:
12263 SELECT COALESCE(description, short_description, '(none)') ...
12265 This returns <varname>description</> if it is not null, otherwise
12266 <varname>short_description</> if it is not null, otherwise <literal>(none)</>.
12270 Like a <token>CASE</token> expression, <function>COALESCE</function> only
12271 evaluates the arguments that are needed to determine the result;
12272 that is, arguments to the right of the first non-null argument are
12273 not evaluated. This SQL-standard function provides capabilities similar
12274 to <function>NVL</> and <function>IFNULL</>, which are used in some other
12279 <sect2 id="functions-nullif">
12280 <title><literal>NULLIF</></title>
12283 <primary>NULLIF</primary>
12287 <function>NULLIF</function>(<replaceable>value1</replaceable>, <replaceable>value2</replaceable>)
12291 The <function>NULLIF</function> function returns a null value if
12292 <replaceable>value1</replaceable> equals <replaceable>value2</replaceable>;
12293 otherwise it returns <replaceable>value1</replaceable>.
12294 This can be used to perform the inverse operation of the
12295 <function>COALESCE</function> example given above:
12297 SELECT NULLIF(value, '(none)') ...
12301 In this example, if <literal>value</literal> is <literal>(none)</>,
12302 null is returned, otherwise the value of <literal>value</literal>
12308 <sect2 id="functions-greatest-least">
12309 <title><literal>GREATEST</literal> and <literal>LEAST</literal></title>
12312 <primary>GREATEST</primary>
12315 <primary>LEAST</primary>
12319 <function>GREATEST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
12322 <function>LEAST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
12326 The <function>GREATEST</> and <function>LEAST</> functions select the
12327 largest or smallest value from a list of any number of expressions.
12328 The expressions must all be convertible to a common data type, which
12329 will be the type of the result
12330 (see <xref linkend="typeconv-union-case"> for details). NULL values
12331 in the list are ignored. The result will be NULL only if all the
12332 expressions evaluate to NULL.
12336 Note that <function>GREATEST</> and <function>LEAST</> are not in
12337 the SQL standard, but are a common extension. Some other databases
12338 make them return NULL if any argument is NULL, rather than only when
12344 <sect1 id="functions-array">
12345 <title>Array Functions and Operators</title>
12348 <xref linkend="array-operators-table"> shows the operators
12349 available for array types.
12352 <table id="array-operators-table">
12353 <title>Array Operators</title>
12357 <entry>Operator</entry>
12358 <entry>Description</entry>
12359 <entry>Example</entry>
12360 <entry>Result</entry>
12365 <entry> <literal>=</literal> </entry>
12366 <entry>equal</entry>
12367 <entry><literal>ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3]</literal></entry>
12368 <entry><literal>t</literal></entry>
12372 <entry> <literal><></literal> </entry>
12373 <entry>not equal</entry>
12374 <entry><literal>ARRAY[1,2,3] <> ARRAY[1,2,4]</literal></entry>
12375 <entry><literal>t</literal></entry>
12379 <entry> <literal><</literal> </entry>
12380 <entry>less than</entry>
12381 <entry><literal>ARRAY[1,2,3] < ARRAY[1,2,4]</literal></entry>
12382 <entry><literal>t</literal></entry>
12386 <entry> <literal>></literal> </entry>
12387 <entry>greater than</entry>
12388 <entry><literal>ARRAY[1,4,3] > ARRAY[1,2,4]</literal></entry>
12389 <entry><literal>t</literal></entry>
12393 <entry> <literal><=</literal> </entry>
12394 <entry>less than or equal</entry>
12395 <entry><literal>ARRAY[1,2,3] <= ARRAY[1,2,3]</literal></entry>
12396 <entry><literal>t</literal></entry>
12400 <entry> <literal>>=</literal> </entry>
12401 <entry>greater than or equal</entry>
12402 <entry><literal>ARRAY[1,4,3] >= ARRAY[1,4,3]</literal></entry>
12403 <entry><literal>t</literal></entry>
12407 <entry> <literal>@></literal> </entry>
12408 <entry>contains</entry>
12409 <entry><literal>ARRAY[1,4,3] @> ARRAY[3,1]</literal></entry>
12410 <entry><literal>t</literal></entry>
12414 <entry> <literal><@</literal> </entry>
12415 <entry>is contained by</entry>
12416 <entry><literal>ARRAY[2,7] <@ ARRAY[1,7,4,2,6]</literal></entry>
12417 <entry><literal>t</literal></entry>
12421 <entry> <literal>&&</literal> </entry>
12422 <entry>overlap (have elements in common)</entry>
12423 <entry><literal>ARRAY[1,4,3] && ARRAY[2,1]</literal></entry>
12424 <entry><literal>t</literal></entry>
12428 <entry> <literal>||</literal> </entry>
12429 <entry>array-to-array concatenation</entry>
12430 <entry><literal>ARRAY[1,2,3] || ARRAY[4,5,6]</literal></entry>
12431 <entry><literal>{1,2,3,4,5,6}</literal></entry>
12435 <entry> <literal>||</literal> </entry>
12436 <entry>array-to-array concatenation</entry>
12437 <entry><literal>ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9]]</literal></entry>
12438 <entry><literal>{{1,2,3},{4,5,6},{7,8,9}}</literal></entry>
12442 <entry> <literal>||</literal> </entry>
12443 <entry>element-to-array concatenation</entry>
12444 <entry><literal>3 || ARRAY[4,5,6]</literal></entry>
12445 <entry><literal>{3,4,5,6}</literal></entry>
12449 <entry> <literal>||</literal> </entry>
12450 <entry>array-to-element concatenation</entry>
12451 <entry><literal>ARRAY[4,5,6] || 7</literal></entry>
12452 <entry><literal>{4,5,6,7}</literal></entry>
12459 Array comparisons compare the array contents element-by-element,
12460 using the default B-tree comparison function for the element data type.
12461 In multidimensional arrays the elements are visited in row-major order
12462 (last subscript varies most rapidly).
12463 If the contents of two arrays are equal but the dimensionality is
12464 different, the first difference in the dimensionality information
12465 determines the sort order. (This is a change from versions of
12466 <productname>PostgreSQL</> prior to 8.2: older versions would claim
12467 that two arrays with the same contents were equal, even if the
12468 number of dimensions or subscript ranges were different.)
12472 See <xref linkend="arrays"> for more details about array operator
12473 behavior. See <xref linkend="indexes-types"> for more details about
12474 which operators support indexed operations.
12478 <xref linkend="array-functions-table"> shows the functions
12479 available for use with array types. See <xref linkend="arrays">
12480 for more information and examples of the use of these functions.
12484 <primary>array_append</primary>
12487 <primary>array_cat</primary>
12490 <primary>array_ndims</primary>
12493 <primary>array_dims</primary>
12496 <primary>array_fill</primary>
12499 <primary>array_length</primary>
12502 <primary>array_lower</primary>
12505 <primary>array_position</primary>
12508 <primary>array_positions</primary>
12511 <primary>array_prepend</primary>
12514 <primary>array_remove</primary>
12517 <primary>array_replace</primary>
12520 <primary>array_to_string</primary>
12523 <primary>array_upper</primary>
12526 <primary>cardinality</primary>
12529 <primary>string_to_array</primary>
12532 <primary>unnest</primary>
12535 <table id="array-functions-table">
12536 <title>Array Functions</title>
12540 <entry>Function</entry>
12541 <entry>Return Type</entry>
12542 <entry>Description</entry>
12543 <entry>Example</entry>
12544 <entry>Result</entry>
12551 <function>array_append</function>(<type>anyarray</type>, <type>anyelement</type>)
12554 <entry><type>anyarray</type></entry>
12555 <entry>append an element to the end of an array</entry>
12556 <entry><literal>array_append(ARRAY[1,2], 3)</literal></entry>
12557 <entry><literal>{1,2,3}</literal></entry>
12562 <function>array_cat</function>(<type>anyarray</type>, <type>anyarray</type>)
12565 <entry><type>anyarray</type></entry>
12566 <entry>concatenate two arrays</entry>
12567 <entry><literal>array_cat(ARRAY[1,2,3], ARRAY[4,5])</literal></entry>
12568 <entry><literal>{1,2,3,4,5}</literal></entry>
12573 <function>array_ndims</function>(<type>anyarray</type>)
12576 <entry><type>int</type></entry>
12577 <entry>returns the number of dimensions of the array</entry>
12578 <entry><literal>array_ndims(ARRAY[[1,2,3], [4,5,6]])</literal></entry>
12579 <entry><literal>2</literal></entry>
12584 <function>array_dims</function>(<type>anyarray</type>)
12587 <entry><type>text</type></entry>
12588 <entry>returns a text representation of array's dimensions</entry>
12589 <entry><literal>array_dims(ARRAY[[1,2,3], [4,5,6]])</literal></entry>
12590 <entry><literal>[1:2][1:3]</literal></entry>
12595 <function>array_fill</function>(<type>anyelement</type>, <type>int[]</type>,
12596 <optional>, <type>int[]</type></optional>)
12599 <entry><type>anyarray</type></entry>
12600 <entry>returns an array initialized with supplied value and
12601 dimensions, optionally with lower bounds other than 1</entry>
12602 <entry><literal>array_fill(7, ARRAY[3], ARRAY[2])</literal></entry>
12603 <entry><literal>[2:4]={7,7,7}</literal></entry>
12608 <function>array_length</function>(<type>anyarray</type>, <type>int</type>)
12611 <entry><type>int</type></entry>
12612 <entry>returns the length of the requested array dimension</entry>
12613 <entry><literal>array_length(array[1,2,3], 1)</literal></entry>
12614 <entry><literal>3</literal></entry>
12619 <function>array_lower</function>(<type>anyarray</type>, <type>int</type>)
12622 <entry><type>int</type></entry>
12623 <entry>returns lower bound of the requested array dimension</entry>
12624 <entry><literal>array_lower('[0:2]={1,2,3}'::int[], 1)</literal></entry>
12625 <entry><literal>0</literal></entry>
12630 <function>array_position</function>(<type>anyarray</type>, <type>anyelement</type> <optional>, <type>int</type></optional>)
12633 <entry><type>int</type></entry>
12634 <entry>returns the subscript of the first occurrence of the second
12635 argument in the array, starting at the element indicated by the third
12636 argument or at the first element (array must be one-dimensional)</entry>
12637 <entry><literal>array_position(ARRAY['sun','mon','tue','wed','thu','fri','sat'], 'mon')</literal></entry>
12638 <entry><literal>2</literal></entry>
12643 <function>array_positions</function>(<type>anyarray</type>, <type>anyelement</type>)
12646 <entry><type>int[]</type></entry>
12647 <entry>returns an array of subscripts of all occurrences of the second
12648 argument in the array given as first argument (array must be
12649 one-dimensional)</entry>
12650 <entry><literal>array_positions(ARRAY['A','A','B','A'], 'A')</literal></entry>
12651 <entry><literal>{1,2,4}</literal></entry>
12656 <function>array_prepend</function>(<type>anyelement</type>, <type>anyarray</type>)
12659 <entry><type>anyarray</type></entry>
12660 <entry>append an element to the beginning of an array</entry>
12661 <entry><literal>array_prepend(1, ARRAY[2,3])</literal></entry>
12662 <entry><literal>{1,2,3}</literal></entry>
12667 <function>array_remove</function>(<type>anyarray</type>, <type>anyelement</type>)
12670 <entry><type>anyarray</type></entry>
12671 <entry>remove all elements equal to the given value from the array
12672 (array must be one-dimensional)</entry>
12673 <entry><literal>array_remove(ARRAY[1,2,3,2], 2)</literal></entry>
12674 <entry><literal>{1,3}</literal></entry>
12679 <function>array_replace</function>(<type>anyarray</type>, <type>anyelement</type>, <type>anyelement</type>)
12682 <entry><type>anyarray</type></entry>
12683 <entry>replace each array element equal to the given value with a new value</entry>
12684 <entry><literal>array_replace(ARRAY[1,2,5,4], 5, 3)</literal></entry>
12685 <entry><literal>{1,2,3,4}</literal></entry>
12690 <function>array_to_string</function>(<type>anyarray</type>, <type>text</type> <optional>, <type>text</type></optional>)
12693 <entry><type>text</type></entry>
12694 <entry>concatenates array elements using supplied delimiter and
12695 optional null string</entry>
12696 <entry><literal>array_to_string(ARRAY[1, 2, 3, NULL, 5], ',', '*')</literal></entry>
12697 <entry><literal>1,2,3,*,5</literal></entry>
12702 <function>array_upper</function>(<type>anyarray</type>, <type>int</type>)
12705 <entry><type>int</type></entry>
12706 <entry>returns upper bound of the requested array dimension</entry>
12707 <entry><literal>array_upper(ARRAY[1,8,3,7], 1)</literal></entry>
12708 <entry><literal>4</literal></entry>
12713 <function>cardinality</function>(<type>anyarray</type>)
12716 <entry><type>int</type></entry>
12717 <entry>returns the total number of elements in the array, or 0 if the array is empty</entry>
12718 <entry><literal>cardinality(ARRAY[[1,2],[3,4]])</literal></entry>
12719 <entry><literal>4</literal></entry>
12724 <function>string_to_array</function>(<type>text</type>, <type>text</type> <optional>, <type>text</type></optional>)
12727 <entry><type>text[]</type></entry>
12728 <entry>splits string into array elements using supplied delimiter and
12729 optional null string</entry>
12730 <entry><literal>string_to_array('xx~^~yy~^~zz', '~^~', 'yy')</literal></entry>
12731 <entry><literal>{xx,NULL,zz}</literal></entry>
12736 <function>unnest</function>(<type>anyarray</type>)
12739 <entry><type>setof anyelement</type></entry>
12740 <entry>expand an array to a set of rows</entry>
12741 <entry><literal>unnest(ARRAY[1,2])</literal></entry>
12742 <entry><literallayout class="monospaced">1
12743 2</literallayout>(2 rows)</entry>
12748 <function>unnest</function>(<type>anyarray</type>, <type>anyarray</type> [, ...])
12751 <entry><type>setof anyelement, anyelement [, ...]</type></entry>
12752 <entry>expand multiple arrays (possibly of different types) to a set
12753 of rows. This is only allowed in the FROM clause; see
12754 <xref linkend="queries-tablefunctions"></entry>
12755 <entry><literal>unnest(ARRAY[1,2],ARRAY['foo','bar','baz'])</literal></entry>
12756 <entry><literallayout class="monospaced">1 foo
12758 NULL baz</literallayout>(3 rows)</entry>
12765 In <function>array_position</function> and <function>array_positions</>,
12766 each array element is compared to the searched value using
12767 <literal>IS NOT DISTINCT FROM</literal> semantics.
12771 In <function>array_position</function>, <literal>NULL</literal> is returned
12772 if the value is not found.
12776 In <function>array_positions</function>, <literal>NULL</literal> is returned
12777 only if the array is <literal>NULL</literal>; if the value is not found in
12778 the array, an empty array is returned instead.
12782 In <function>string_to_array</function>, if the delimiter parameter is
12783 NULL, each character in the input string will become a separate element in
12784 the resulting array. If the delimiter is an empty string, then the entire
12785 input string is returned as a one-element array. Otherwise the input
12786 string is split at each occurrence of the delimiter string.
12790 In <function>string_to_array</function>, if the null-string parameter
12791 is omitted or NULL, none of the substrings of the input will be replaced
12793 In <function>array_to_string</function>, if the null-string parameter
12794 is omitted or NULL, any null elements in the array are simply skipped
12795 and not represented in the output string.
12800 There are two differences in the behavior of <function>string_to_array</>
12801 from pre-9.1 versions of <productname>PostgreSQL</>.
12802 First, it will return an empty (zero-element) array rather than NULL when
12803 the input string is of zero length. Second, if the delimiter string is
12804 NULL, the function splits the input into individual characters, rather
12805 than returning NULL as before.
12810 See also <xref linkend="functions-aggregate"> about the aggregate
12811 function <function>array_agg</function> for use with arrays.
12815 <sect1 id="functions-range">
12816 <title>Range Functions and Operators</title>
12819 See <xref linkend="rangetypes"> for an overview of range types.
12823 <xref linkend="range-operators-table"> shows the operators
12824 available for range types.
12827 <table id="range-operators-table">
12828 <title>Range Operators</title>
12832 <entry>Operator</entry>
12833 <entry>Description</entry>
12834 <entry>Example</entry>
12835 <entry>Result</entry>
12840 <entry> <literal>=</literal> </entry>
12841 <entry>equal</entry>
12842 <entry><literal>int4range(1,5) = '[1,4]'::int4range</literal></entry>
12843 <entry><literal>t</literal></entry>
12847 <entry> <literal><></literal> </entry>
12848 <entry>not equal</entry>
12849 <entry><literal>numrange(1.1,2.2) <> numrange(1.1,2.3)</literal></entry>
12850 <entry><literal>t</literal></entry>
12854 <entry> <literal><</literal> </entry>
12855 <entry>less than</entry>
12856 <entry><literal>int4range(1,10) < int4range(2,3)</literal></entry>
12857 <entry><literal>t</literal></entry>
12861 <entry> <literal>></literal> </entry>
12862 <entry>greater than</entry>
12863 <entry><literal>int4range(1,10) > int4range(1,5)</literal></entry>
12864 <entry><literal>t</literal></entry>
12868 <entry> <literal><=</literal> </entry>
12869 <entry>less than or equal</entry>
12870 <entry><literal>numrange(1.1,2.2) <= numrange(1.1,2.2)</literal></entry>
12871 <entry><literal>t</literal></entry>
12875 <entry> <literal>>=</literal> </entry>
12876 <entry>greater than or equal</entry>
12877 <entry><literal>numrange(1.1,2.2) >= numrange(1.1,2.0)</literal></entry>
12878 <entry><literal>t</literal></entry>
12882 <entry> <literal>@></literal> </entry>
12883 <entry>contains range</entry>
12884 <entry><literal>int4range(2,4) @> int4range(2,3)</literal></entry>
12885 <entry><literal>t</literal></entry>
12889 <entry> <literal>@></literal> </entry>
12890 <entry>contains element</entry>
12891 <entry><literal>'[2011-01-01,2011-03-01)'::tsrange @> '2011-01-10'::timestamp</literal></entry>
12892 <entry><literal>t</literal></entry>
12896 <entry> <literal><@</literal> </entry>
12897 <entry>range is contained by</entry>
12898 <entry><literal>int4range(2,4) <@ int4range(1,7)</literal></entry>
12899 <entry><literal>t</literal></entry>
12903 <entry> <literal><@</literal> </entry>
12904 <entry>element is contained by</entry>
12905 <entry><literal>42 <@ int4range(1,7)</literal></entry>
12906 <entry><literal>f</literal></entry>
12910 <entry> <literal>&&</literal> </entry>
12911 <entry>overlap (have points in common)</entry>
12912 <entry><literal>int8range(3,7) && int8range(4,12)</literal></entry>
12913 <entry><literal>t</literal></entry>
12917 <entry> <literal><<</literal> </entry>
12918 <entry>strictly left of</entry>
12919 <entry><literal>int8range(1,10) << int8range(100,110)</literal></entry>
12920 <entry><literal>t</literal></entry>
12924 <entry> <literal>>></literal> </entry>
12925 <entry>strictly right of</entry>
12926 <entry><literal>int8range(50,60) >> int8range(20,30)</literal></entry>
12927 <entry><literal>t</literal></entry>
12931 <entry> <literal>&<</literal> </entry>
12932 <entry>does not extend to the right of</entry>
12933 <entry><literal>int8range(1,20) &< int8range(18,20)</literal></entry>
12934 <entry><literal>t</literal></entry>
12938 <entry> <literal>&></literal> </entry>
12939 <entry>does not extend to the left of</entry>
12940 <entry><literal>int8range(7,20) &> int8range(5,10)</literal></entry>
12941 <entry><literal>t</literal></entry>
12945 <entry> <literal>-|-</literal> </entry>
12946 <entry>is adjacent to</entry>
12947 <entry><literal>numrange(1.1,2.2) -|- numrange(2.2,3.3)</literal></entry>
12948 <entry><literal>t</literal></entry>
12952 <entry> <literal>+</literal> </entry>
12953 <entry>union</entry>
12954 <entry><literal>numrange(5,15) + numrange(10,20)</literal></entry>
12955 <entry><literal>[5,20)</literal></entry>
12959 <entry> <literal>*</literal> </entry>
12960 <entry>intersection</entry>
12961 <entry><literal>int8range(5,15) * int8range(10,20)</literal></entry>
12962 <entry><literal>[10,15)</literal></entry>
12966 <entry> <literal>-</literal> </entry>
12967 <entry>difference</entry>
12968 <entry><literal>int8range(5,15) - int8range(10,20)</literal></entry>
12969 <entry><literal>[5,10)</literal></entry>
12977 The simple comparison operators <literal><</literal>,
12978 <literal>></literal>, <literal><=</literal>, and
12979 <literal>>=</literal> compare the lower bounds first, and only if those
12980 are equal, compare the upper bounds. These comparisons are not usually
12981 very useful for ranges, but are provided to allow B-tree indexes to be
12982 constructed on ranges.
12986 The left-of/right-of/adjacent operators always return false when an empty
12987 range is involved; that is, an empty range is not considered to be either
12988 before or after any other range.
12992 The union and difference operators will fail if the resulting range would
12993 need to contain two disjoint sub-ranges, as such a range cannot be
12998 <xref linkend="range-functions-table"> shows the functions
12999 available for use with range types.
13003 <primary>lower</primary>
13006 <primary>upper</primary>
13009 <primary>isempty</primary>
13012 <primary>lower_inc</primary>
13015 <primary>upper_inc</primary>
13018 <primary>lower_inf</primary>
13021 <primary>upper_inf</primary>
13024 <table id="range-functions-table">
13025 <title>Range Functions</title>
13029 <entry>Function</entry>
13030 <entry>Return Type</entry>
13031 <entry>Description</entry>
13032 <entry>Example</entry>
13033 <entry>Result</entry>
13040 <function>lower</function>(<type>anyrange</type>)
13043 <entry>range's element type</entry>
13044 <entry>lower bound of range</entry>
13045 <entry><literal>lower(numrange(1.1,2.2))</literal></entry>
13046 <entry><literal>1.1</literal></entry>
13051 <function>upper</function>(<type>anyrange</type>)
13054 <entry>range's element type</entry>
13055 <entry>upper bound of range</entry>
13056 <entry><literal>upper(numrange(1.1,2.2))</literal></entry>
13057 <entry><literal>2.2</literal></entry>
13062 <function>isempty</function>(<type>anyrange</type>)
13065 <entry><type>boolean</type></entry>
13066 <entry>is the range empty?</entry>
13067 <entry><literal>isempty(numrange(1.1,2.2))</literal></entry>
13068 <entry><literal>false</literal></entry>
13073 <function>lower_inc</function>(<type>anyrange</type>)
13076 <entry><type>boolean</type></entry>
13077 <entry>is the lower bound inclusive?</entry>
13078 <entry><literal>lower_inc(numrange(1.1,2.2))</literal></entry>
13079 <entry><literal>true</literal></entry>
13084 <function>upper_inc</function>(<type>anyrange</type>)
13087 <entry><type>boolean</type></entry>
13088 <entry>is the upper bound inclusive?</entry>
13089 <entry><literal>upper_inc(numrange(1.1,2.2))</literal></entry>
13090 <entry><literal>false</literal></entry>
13095 <function>lower_inf</function>(<type>anyrange</type>)
13098 <entry><type>boolean</type></entry>
13099 <entry>is the lower bound infinite?</entry>
13100 <entry><literal>lower_inf('(,)'::daterange)</literal></entry>
13101 <entry><literal>true</literal></entry>
13106 <function>upper_inf</function>(<type>anyrange</type>)
13109 <entry><type>boolean</type></entry>
13110 <entry>is the upper bound infinite?</entry>
13111 <entry><literal>upper_inf('(,)'::daterange)</literal></entry>
13112 <entry><literal>true</literal></entry>
13117 <function>range_merge</function>(<type>anyrange</type>, <type>anyrange</type>)
13120 <entry><type>anyrange</type></entry>
13121 <entry>the smallest range which includes both of the given ranges</entry>
13122 <entry><literal>range_merge('[1,2)'::int4range, '[3,4)'::int4range)</literal></entry>
13123 <entry><literal>[1,4)</literal></entry>
13130 The <function>lower</> and <function>upper</> functions return null
13131 if the range is empty or the requested bound is infinite.
13132 The <function>lower_inc</function>, <function>upper_inc</function>,
13133 <function>lower_inf</function>, and <function>upper_inf</function>
13134 functions all return false for an empty range.
13138 <sect1 id="functions-aggregate">
13139 <title>Aggregate Functions</title>
13141 <indexterm zone="functions-aggregate">
13142 <primary>aggregate function</primary>
13143 <secondary>built-in</secondary>
13147 <firstterm>Aggregate functions</firstterm> compute a single result
13148 from a set of input values. The built-in normal aggregate functions
13150 <xref linkend="functions-aggregate-table"> and
13151 <xref linkend="functions-aggregate-statistics-table">.
13152 The built-in ordered-set aggregate functions
13153 are listed in <xref linkend="functions-orderedset-table"> and
13154 <xref linkend="functions-hypothetical-table">. Grouping operations,
13155 which are closely related to aggregate functions, are listed in
13156 <xref linkend="functions-grouping-table">.
13157 The special syntax considerations for aggregate
13158 functions are explained in <xref linkend="syntax-aggregates">.
13159 Consult <xref linkend="tutorial-agg"> for additional introductory
13163 <table id="functions-aggregate-table">
13164 <title>General-Purpose Aggregate Functions</title>
13169 <entry>Function</entry>
13170 <entry>Argument Type(s)</entry>
13171 <entry>Return Type</entry>
13172 <entry>Partial Mode</entry>
13173 <entry>Description</entry>
13181 <primary>array_agg</primary>
13183 <function>array_agg(<replaceable class="parameter">expression</replaceable>)</function>
13189 array of the argument type
13192 <entry>input values, including nulls, concatenated into an array</entry>
13197 <function>array_agg(<replaceable class="parameter">expression</replaceable>)</function>
13203 same as argument data type
13206 <entry>input arrays concatenated into array of one higher dimension
13207 (inputs must all have same dimensionality,
13208 and cannot be empty or NULL)</entry>
13214 <primary>average</primary>
13217 <primary>avg</primary>
13219 <function>avg(<replaceable class="parameter">expression</replaceable>)</function>
13222 <type>smallint</type>, <type>int</type>,
13223 <type>bigint</type>, <type>real</type>, <type>double
13224 precision</type>, <type>numeric</type>, or <type>interval</type>
13227 <type>numeric</type> for any integer-type argument,
13228 <type>double precision</type> for a floating-point argument,
13229 otherwise the same as the argument data type
13232 <entry>the average (arithmetic mean) of all input values</entry>
13238 <primary>bit_and</primary>
13240 <function>bit_and(<replaceable class="parameter">expression</replaceable>)</function>
13243 <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
13247 same as argument data type
13250 <entry>the bitwise AND of all non-null input values, or null if none</entry>
13256 <primary>bit_or</primary>
13258 <function>bit_or(<replaceable class="parameter">expression</replaceable>)</function>
13261 <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
13265 same as argument data type
13268 <entry>the bitwise OR of all non-null input values, or null if none</entry>
13274 <primary>bool_and</primary>
13276 <function>bool_and(<replaceable class="parameter">expression</replaceable>)</function>
13285 <entry>true if all input values are true, otherwise false</entry>
13291 <primary>bool_or</primary>
13293 <function>bool_or(<replaceable class="parameter">expression</replaceable>)</function>
13302 <entry>true if at least one input value is true, otherwise false</entry>
13308 <primary>count</primary>
13310 <function>count(*)</function>
13313 <entry><type>bigint</type></entry>
13315 <entry>number of input rows</entry>
13319 <entry><function>count(<replaceable class="parameter">expression</replaceable>)</function></entry>
13321 <entry><type>bigint</type></entry>
13324 number of input rows for which the value of <replaceable
13325 class="parameter">expression</replaceable> is not null
13332 <primary>every</primary>
13334 <function>every(<replaceable class="parameter">expression</replaceable>)</function>
13343 <entry>equivalent to <function>bool_and</function></entry>
13349 <primary>json_agg</primary>
13351 <function>json_agg(<replaceable class="parameter">expression</replaceable>)</function>
13360 <entry>aggregates values as a JSON array</entry>
13366 <primary>jsonb_agg</primary>
13368 <function>jsonb_agg(<replaceable class="parameter">expression</replaceable>)</function>
13377 <entry>aggregates values as a JSON array</entry>
13383 <primary>json_object_agg</primary>
13385 <function>json_object_agg(<replaceable class="parameter">name</replaceable>, <replaceable class="parameter">value</replaceable>)</function>
13388 <type>(any, any)</type>
13394 <entry>aggregates name/value pairs as a JSON object</entry>
13400 <primary>jsonb_object_agg</primary>
13402 <function>jsonb_object_agg(<replaceable class="parameter">name</replaceable>, <replaceable class="parameter">value</replaceable>)</function>
13405 <type>(any, any)</type>
13411 <entry>aggregates name/value pairs as a JSON object</entry>
13417 <primary>max</primary>
13419 <function>max(<replaceable class="parameter">expression</replaceable>)</function>
13421 <entry>any numeric, string, date/time, network, or enum type,
13422 or arrays of these types</entry>
13423 <entry>same as argument type</entry>
13426 maximum value of <replaceable
13427 class="parameter">expression</replaceable> across all input
13435 <primary>min</primary>
13437 <function>min(<replaceable class="parameter">expression</replaceable>)</function>
13439 <entry>any numeric, string, date/time, network, or enum type,
13440 or arrays of these types</entry>
13441 <entry>same as argument type</entry>
13444 minimum value of <replaceable
13445 class="parameter">expression</replaceable> across all input
13453 <primary>string_agg</primary>
13456 string_agg(<replaceable class="parameter">expression</replaceable>,
13457 <replaceable class="parameter">delimiter</replaceable>)
13461 (<type>text</type>, <type>text</type>) or (<type>bytea</type>, <type>bytea</type>)
13464 same as argument types
13467 <entry>input values concatenated into a string, separated by delimiter</entry>
13473 <primary>sum</primary>
13475 <function>sum(<replaceable class="parameter">expression</replaceable>)</function>
13478 <type>smallint</type>, <type>int</type>,
13479 <type>bigint</type>, <type>real</type>, <type>double
13480 precision</type>, <type>numeric</type>,
13481 <type>interval</type>, or <type>money</>
13484 <type>bigint</type> for <type>smallint</type> or
13485 <type>int</type> arguments, <type>numeric</type> for
13486 <type>bigint</type> arguments, otherwise the same as the
13490 <entry>sum of <replaceable class="parameter">expression</replaceable> across all input values</entry>
13496 <primary>xmlagg</primary>
13498 <function>xmlagg(<replaceable class="parameter">expression</replaceable>)</function>
13507 <entry>concatenation of XML values (see also <xref linkend="functions-xml-xmlagg">)</entry>
13514 It should be noted that except for <function>count</function>,
13515 these functions return a null value when no rows are selected. In
13516 particular, <function>sum</function> of no rows returns null, not
13517 zero as one might expect, and <function>array_agg</function>
13518 returns null rather than an empty array when there are no input
13519 rows. The <function>coalesce</function> function can be used to
13520 substitute zero or an empty array for null when necessary.
13524 Aggregate functions which support <firstterm>Partial Mode</firstterm>
13525 are eligible to participate in various optimizations, such as parallel
13531 <primary>ANY</primary>
13534 <primary>SOME</primary>
13537 Boolean aggregates <function>bool_and</function> and
13538 <function>bool_or</function> correspond to standard SQL aggregates
13539 <function>every</function> and <function>any</function> or
13540 <function>some</function>.
13541 As for <function>any</function> and <function>some</function>,
13542 it seems that there is an ambiguity built into the standard syntax:
13544 SELECT b1 = ANY((SELECT b2 FROM t2 ...)) FROM t1 ...;
13546 Here <function>ANY</function> can be considered either as introducing
13547 a subquery, or as being an aggregate function, if the subquery
13548 returns one row with a Boolean value.
13549 Thus the standard name cannot be given to these aggregates.
13555 Users accustomed to working with other SQL database management
13556 systems might be disappointed by the performance of the
13557 <function>count</function> aggregate when it is applied to the
13558 entire table. A query like:
13560 SELECT count(*) FROM sometable;
13562 will require effort proportional to the size of the table:
13563 <productname>PostgreSQL</productname> will need to scan either the
13564 entire table or the entirety of an index which includes all rows in
13570 The aggregate functions <function>array_agg</function>,
13571 <function>json_agg</function>, <function>jsonb_agg</function>,
13572 <function>json_object_agg</function>, <function>jsonb_object_agg</function>,
13573 <function>string_agg</function>,
13574 and <function>xmlagg</function>, as well as similar user-defined
13575 aggregate functions, produce meaningfully different result values
13576 depending on the order of the input values. This ordering is
13577 unspecified by default, but can be controlled by writing an
13578 <literal>ORDER BY</> clause within the aggregate call, as shown in
13579 <xref linkend="syntax-aggregates">.
13580 Alternatively, supplying the input values from a sorted subquery
13581 will usually work. For example:
13584 SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;
13587 Beware that this approach can fail if the outer query level contains
13588 additional processing, such as a join, because that might cause the
13589 subquery's output to be reordered before the aggregate is computed.
13593 <xref linkend="functions-aggregate-statistics-table"> shows
13594 aggregate functions typically used in statistical analysis.
13595 (These are separated out merely to avoid cluttering the listing
13596 of more-commonly-used aggregates.) Where the description mentions
13597 <replaceable class="parameter">N</replaceable>, it means the
13598 number of input rows for which all the input expressions are non-null.
13599 In all cases, null is returned if the computation is meaningless,
13600 for example when <replaceable class="parameter">N</replaceable> is zero.
13604 <primary>statistics</primary>
13607 <primary>linear regression</primary>
13610 <table id="functions-aggregate-statistics-table">
13611 <title>Aggregate Functions for Statistics</title>
13616 <entry>Function</entry>
13617 <entry>Argument Type</entry>
13618 <entry>Return Type</entry>
13619 <entry>Partial Mode</entry>
13620 <entry>Description</entry>
13629 <primary>correlation</primary>
13632 <primary>corr</primary>
13634 <function>corr(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13637 <type>double precision</type>
13640 <type>double precision</type>
13643 <entry>correlation coefficient</entry>
13649 <primary>covariance</primary>
13650 <secondary>population</secondary>
13653 <primary>covar_pop</primary>
13655 <function>covar_pop(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13658 <type>double precision</type>
13661 <type>double precision</type>
13664 <entry>population covariance</entry>
13670 <primary>covariance</primary>
13671 <secondary>sample</secondary>
13674 <primary>covar_samp</primary>
13676 <function>covar_samp(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13679 <type>double precision</type>
13682 <type>double precision</type>
13685 <entry>sample covariance</entry>
13691 <primary>regr_avgx</primary>
13693 <function>regr_avgx(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13696 <type>double precision</type>
13699 <type>double precision</type>
13702 <entry>average of the independent variable
13703 (<literal>sum(<replaceable class="parameter">X</replaceable>)/<replaceable class="parameter">N</replaceable></literal>)</entry>
13709 <primary>regr_avgy</primary>
13711 <function>regr_avgy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13714 <type>double precision</type>
13717 <type>double precision</type>
13720 <entry>average of the dependent variable
13721 (<literal>sum(<replaceable class="parameter">Y</replaceable>)/<replaceable class="parameter">N</replaceable></literal>)</entry>
13727 <primary>regr_count</primary>
13729 <function>regr_count(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13732 <type>double precision</type>
13735 <type>bigint</type>
13738 <entry>number of input rows in which both expressions are nonnull</entry>
13744 <primary>regression intercept</primary>
13747 <primary>regr_intercept</primary>
13749 <function>regr_intercept(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13752 <type>double precision</type>
13755 <type>double precision</type>
13758 <entry>y-intercept of the least-squares-fit linear equation
13759 determined by the (<replaceable
13760 class="parameter">X</replaceable>, <replaceable
13761 class="parameter">Y</replaceable>) pairs</entry>
13767 <primary>regr_r2</primary>
13769 <function>regr_r2(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13772 <type>double precision</type>
13775 <type>double precision</type>
13778 <entry>square of the correlation coefficient</entry>
13784 <primary>regression slope</primary>
13787 <primary>regr_slope</primary>
13789 <function>regr_slope(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13792 <type>double precision</type>
13795 <type>double precision</type>
13798 <entry>slope of the least-squares-fit linear equation determined
13799 by the (<replaceable class="parameter">X</replaceable>,
13800 <replaceable class="parameter">Y</replaceable>) pairs</entry>
13806 <primary>regr_sxx</primary>
13808 <function>regr_sxx(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13811 <type>double precision</type>
13814 <type>double precision</type>
13817 <entry><literal>sum(<replaceable
13818 class="parameter">X</replaceable>^2) - sum(<replaceable
13819 class="parameter">X</replaceable>)^2/<replaceable
13820 class="parameter">N</replaceable></literal> (<quote>sum of
13821 squares</quote> of the independent variable)</entry>
13827 <primary>regr_sxy</primary>
13829 <function>regr_sxy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13832 <type>double precision</type>
13835 <type>double precision</type>
13838 <entry><literal>sum(<replaceable
13839 class="parameter">X</replaceable>*<replaceable
13840 class="parameter">Y</replaceable>) - sum(<replaceable
13841 class="parameter">X</replaceable>) * sum(<replaceable
13842 class="parameter">Y</replaceable>)/<replaceable
13843 class="parameter">N</replaceable></literal> (<quote>sum of
13844 products</quote> of independent times dependent
13851 <primary>regr_syy</primary>
13853 <function>regr_syy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13856 <type>double precision</type>
13859 <type>double precision</type>
13862 <entry><literal>sum(<replaceable
13863 class="parameter">Y</replaceable>^2) - sum(<replaceable
13864 class="parameter">Y</replaceable>)^2/<replaceable
13865 class="parameter">N</replaceable></literal> (<quote>sum of
13866 squares</quote> of the dependent variable)</entry>
13872 <primary>standard deviation</primary>
13875 <primary>stddev</primary>
13877 <function>stddev(<replaceable class="parameter">expression</replaceable>)</function>
13880 <type>smallint</type>, <type>int</type>,
13881 <type>bigint</type>, <type>real</type>, <type>double
13882 precision</type>, or <type>numeric</type>
13885 <type>double precision</type> for floating-point arguments,
13886 otherwise <type>numeric</type>
13889 <entry>historical alias for <function>stddev_samp</function></entry>
13895 <primary>standard deviation</primary>
13896 <secondary>population</secondary>
13899 <primary>stddev_pop</primary>
13901 <function>stddev_pop(<replaceable class="parameter">expression</replaceable>)</function>
13904 <type>smallint</type>, <type>int</type>,
13905 <type>bigint</type>, <type>real</type>, <type>double
13906 precision</type>, or <type>numeric</type>
13909 <type>double precision</type> for floating-point arguments,
13910 otherwise <type>numeric</type>
13913 <entry>population standard deviation of the input values</entry>
13919 <primary>standard deviation</primary>
13920 <secondary>sample</secondary>
13923 <primary>stddev_samp</primary>
13925 <function>stddev_samp(<replaceable class="parameter">expression</replaceable>)</function>
13928 <type>smallint</type>, <type>int</type>,
13929 <type>bigint</type>, <type>real</type>, <type>double
13930 precision</type>, or <type>numeric</type>
13933 <type>double precision</type> for floating-point arguments,
13934 otherwise <type>numeric</type>
13937 <entry>sample standard deviation of the input values</entry>
13943 <primary>variance</primary>
13945 <function>variance</function>(<replaceable class="parameter">expression</replaceable>)
13948 <type>smallint</type>, <type>int</type>,
13949 <type>bigint</type>, <type>real</type>, <type>double
13950 precision</type>, or <type>numeric</type>
13953 <type>double precision</type> for floating-point arguments,
13954 otherwise <type>numeric</type>
13957 <entry>historical alias for <function>var_samp</function></entry>
13963 <primary>variance</primary>
13964 <secondary>population</secondary>
13967 <primary>var_pop</primary>
13969 <function>var_pop</function>(<replaceable class="parameter">expression</replaceable>)
13972 <type>smallint</type>, <type>int</type>,
13973 <type>bigint</type>, <type>real</type>, <type>double
13974 precision</type>, or <type>numeric</type>
13977 <type>double precision</type> for floating-point arguments,
13978 otherwise <type>numeric</type>
13981 <entry>population variance of the input values (square of the population standard deviation)</entry>
13987 <primary>variance</primary>
13988 <secondary>sample</secondary>
13991 <primary>var_samp</primary>
13993 <function>var_samp</function>(<replaceable class="parameter">expression</replaceable>)
13996 <type>smallint</type>, <type>int</type>,
13997 <type>bigint</type>, <type>real</type>, <type>double
13998 precision</type>, or <type>numeric</type>
14001 <type>double precision</type> for floating-point arguments,
14002 otherwise <type>numeric</type>
14005 <entry>sample variance of the input values (square of the sample standard deviation)</entry>
14012 <xref linkend="functions-orderedset-table"> shows some
14013 aggregate functions that use the <firstterm>ordered-set aggregate</>
14014 syntax. These functions are sometimes referred to as <quote>inverse
14015 distribution</> functions.
14019 <primary>ordered-set aggregate</primary>
14020 <secondary>built-in</secondary>
14023 <primary>inverse distribution</primary>
14026 <table id="functions-orderedset-table">
14027 <title>Ordered-Set Aggregate Functions</title>
14032 <entry>Function</entry>
14033 <entry>Direct Argument Type(s)</entry>
14034 <entry>Aggregated Argument Type(s)</entry>
14035 <entry>Return Type</entry>
14036 <entry>Partial Mode</entry>
14037 <entry>Description</entry>
14046 <primary>mode</primary>
14047 <secondary>statistical</secondary>
14049 <function>mode() WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
14057 same as sort expression
14061 returns the most frequent input value (arbitrarily choosing the first
14062 one if there are multiple equally-frequent results)
14069 <primary>percentile</primary>
14070 <secondary>continuous</secondary>
14072 <function>percentile_cont(<replaceable class="parameter">fraction</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
14075 <type>double precision</type>
14078 <type>double precision</type> or <type>interval</type>
14081 same as sort expression
14085 continuous percentile: returns a value corresponding to the specified
14086 fraction in the ordering, interpolating between adjacent input items if
14093 <function>percentile_cont(<replaceable class="parameter">fractions</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
14096 <type>double precision[]</type>
14099 <type>double precision</type> or <type>interval</type>
14102 array of sort expression's type
14106 multiple continuous percentile: returns an array of results matching
14107 the shape of the <replaceable>fractions</replaceable> parameter, with each
14108 non-null element replaced by the value corresponding to that percentile
14115 <primary>percentile</primary>
14116 <secondary>discrete</secondary>
14118 <function>percentile_disc(<replaceable class="parameter">fraction</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
14121 <type>double precision</type>
14127 same as sort expression
14131 discrete percentile: returns the first input value whose position in
14132 the ordering equals or exceeds the specified fraction
14138 <function>percentile_disc(<replaceable class="parameter">fractions</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
14141 <type>double precision[]</type>
14147 array of sort expression's type
14151 multiple discrete percentile: returns an array of results matching the
14152 shape of the <replaceable>fractions</replaceable> parameter, with each non-null
14153 element replaced by the input value corresponding to that percentile
14162 All the aggregates listed in <xref linkend="functions-orderedset-table">
14163 ignore null values in their sorted input. For those that take
14164 a <replaceable>fraction</replaceable> parameter, the fraction value must be
14165 between 0 and 1; an error is thrown if not. However, a null fraction value
14166 simply produces a null result.
14170 <primary>hypothetical-set aggregate</primary>
14171 <secondary>built-in</secondary>
14175 Each of the aggregates listed in
14176 <xref linkend="functions-hypothetical-table"> is associated with a
14177 window function of the same name defined in
14178 <xref linkend="functions-window">. In each case, the aggregate result
14179 is the value that the associated window function would have
14180 returned for the <quote>hypothetical</> row constructed from
14181 <replaceable>args</replaceable>, if such a row had been added to the sorted
14182 group of rows computed from the <replaceable>sorted_args</replaceable>.
14185 <table id="functions-hypothetical-table">
14186 <title>Hypothetical-Set Aggregate Functions</title>
14191 <entry>Function</entry>
14192 <entry>Direct Argument Type(s)</entry>
14193 <entry>Aggregated Argument Type(s)</entry>
14194 <entry>Return Type</entry>
14195 <entry>Partial Mode</entry>
14196 <entry>Description</entry>
14205 <primary>rank</primary>
14206 <secondary>hypothetical</secondary>
14208 <function>rank(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
14211 <literal>VARIADIC</> <type>"any"</type>
14214 <literal>VARIADIC</> <type>"any"</type>
14217 <type>bigint</type>
14221 rank of the hypothetical row, with gaps for duplicate rows
14228 <primary>dense_rank</primary>
14229 <secondary>hypothetical</secondary>
14231 <function>dense_rank(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
14234 <literal>VARIADIC</> <type>"any"</type>
14237 <literal>VARIADIC</> <type>"any"</type>
14240 <type>bigint</type>
14244 rank of the hypothetical row, without gaps
14251 <primary>percent_rank</primary>
14252 <secondary>hypothetical</secondary>
14254 <function>percent_rank(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
14257 <literal>VARIADIC</> <type>"any"</type>
14260 <literal>VARIADIC</> <type>"any"</type>
14263 <type>double precision</type>
14267 relative rank of the hypothetical row, ranging from 0 to 1
14274 <primary>cume_dist</primary>
14275 <secondary>hypothetical</secondary>
14277 <function>cume_dist(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
14280 <literal>VARIADIC</> <type>"any"</type>
14283 <literal>VARIADIC</> <type>"any"</type>
14286 <type>double precision</type>
14290 relative rank of the hypothetical row, ranging from
14291 1/<replaceable>N</> to 1
14300 For each of these hypothetical-set aggregates, the list of direct arguments
14301 given in <replaceable>args</replaceable> must match the number and types of
14302 the aggregated arguments given in <replaceable>sorted_args</replaceable>.
14303 Unlike most built-in aggregates, these aggregates are not strict, that is
14304 they do not drop input rows containing nulls. Null values sort according
14305 to the rule specified in the <literal>ORDER BY</> clause.
14308 <table id="functions-grouping-table">
14309 <title>Grouping Operations</title>
14314 <entry>Function</entry>
14315 <entry>Return Type</entry>
14316 <entry>Description</entry>
14325 <primary>GROUPING</primary>
14327 <function>GROUPING(<replaceable class="parameter">args...</replaceable>)</function>
14330 <type>integer</type>
14333 Integer bit mask indicating which arguments are not being included in the current
14342 Grouping operations are used in conjunction with grouping sets (see
14343 <xref linkend="queries-grouping-sets">) to distinguish result rows. The
14344 arguments to the <literal>GROUPING</> operation are not actually evaluated,
14345 but they must match exactly expressions given in the <literal>GROUP BY</>
14346 clause of the associated query level. Bits are assigned with the rightmost
14347 argument being the least-significant bit; each bit is 0 if the corresponding
14348 expression is included in the grouping criteria of the grouping set generating
14349 the result row, and 1 if it is not. For example:
14351 <prompt>=></> <userinput>SELECT * FROM items_sold;</>
14352 make | model | sales
14353 -------+-------+-------
14360 <prompt>=></> <userinput>SELECT make, model, GROUPING(make,model), sum(sales) FROM items_sold GROUP BY ROLLUP(make,model);</>
14361 make | model | grouping | sum
14362 -------+-------+----------+-----
14364 Foo | Tour | 0 | 20
14365 Bar | City | 0 | 15
14366 Bar | Sport | 0 | 5
14376 <sect1 id="functions-window">
14377 <title>Window Functions</title>
14379 <indexterm zone="functions-window">
14380 <primary>window function</primary>
14381 <secondary>built-in</secondary>
14385 <firstterm>Window functions</firstterm> provide the ability to perform
14386 calculations across sets of rows that are related to the current query
14387 row. See <xref linkend="tutorial-window"> for an introduction to this
14388 feature, and <xref linkend="syntax-window-functions"> for syntax
14393 The built-in window functions are listed in
14394 <xref linkend="functions-window-table">. Note that these functions
14395 <emphasis>must</> be invoked using window function syntax; that is an
14396 <literal>OVER</> clause is required.
14400 In addition to these functions, any built-in or user-defined normal
14401 aggregate function (but not ordered-set or hypothetical-set aggregates)
14402 can be used as a window function; see
14403 <xref linkend="functions-aggregate"> for a list of the built-in aggregates.
14404 Aggregate functions act as window functions only when an <literal>OVER</>
14405 clause follows the call; otherwise they act as regular aggregates.
14408 <table id="functions-window-table">
14409 <title>General-Purpose Window Functions</title>
14414 <entry>Function</entry>
14415 <entry>Return Type</entry>
14416 <entry>Description</entry>
14424 <primary>row_number</primary>
14426 <function>row_number()</function>
14429 <type>bigint</type>
14431 <entry>number of the current row within its partition, counting from 1</entry>
14437 <primary>rank</primary>
14439 <function>rank()</function>
14442 <type>bigint</type>
14444 <entry>rank of the current row with gaps; same as <function>row_number</> of its first peer</entry>
14450 <primary>dense_rank</primary>
14452 <function>dense_rank()</function>
14455 <type>bigint</type>
14457 <entry>rank of the current row without gaps; this function counts peer groups</entry>
14463 <primary>percent_rank</primary>
14465 <function>percent_rank()</function>
14468 <type>double precision</type>
14470 <entry>relative rank of the current row: (<function>rank</> - 1) / (total rows - 1)</entry>
14476 <primary>cume_dist</primary>
14478 <function>cume_dist()</function>
14481 <type>double precision</type>
14483 <entry>relative rank of the current row: (number of rows preceding or peer with current row) / (total rows)</entry>
14489 <primary>ntile</primary>
14491 <function>ntile(<replaceable class="parameter">num_buckets</replaceable> <type>integer</>)</function>
14494 <type>integer</type>
14496 <entry>integer ranging from 1 to the argument value, dividing the
14497 partition as equally as possible</entry>
14503 <primary>lag</primary>
14506 lag(<replaceable class="parameter">value</replaceable> <type>anyelement</>
14507 [, <replaceable class="parameter">offset</replaceable> <type>integer</>
14508 [, <replaceable class="parameter">default</replaceable> <type>anyelement</> ]])
14512 <type>same type as <replaceable class="parameter">value</replaceable></type>
14515 returns <replaceable class="parameter">value</replaceable> evaluated at
14516 the row that is <replaceable class="parameter">offset</replaceable>
14517 rows before the current row within the partition; if there is no such
14518 row, instead return <replaceable class="parameter">default</replaceable>
14519 (which must be of the same type as
14520 <replaceable class="parameter">value</replaceable>).
14521 Both <replaceable class="parameter">offset</replaceable> and
14522 <replaceable class="parameter">default</replaceable> are evaluated
14523 with respect to the current row. If omitted,
14524 <replaceable class="parameter">offset</replaceable> defaults to 1 and
14525 <replaceable class="parameter">default</replaceable> to null
14532 <primary>lead</primary>
14535 lead(<replaceable class="parameter">value</replaceable> <type>anyelement</>
14536 [, <replaceable class="parameter">offset</replaceable> <type>integer</>
14537 [, <replaceable class="parameter">default</replaceable> <type>anyelement</> ]])
14541 <type>same type as <replaceable class="parameter">value</replaceable></type>
14544 returns <replaceable class="parameter">value</replaceable> evaluated at
14545 the row that is <replaceable class="parameter">offset</replaceable>
14546 rows after the current row within the partition; if there is no such
14547 row, instead return <replaceable class="parameter">default</replaceable>
14548 (which must be of the same type as
14549 <replaceable class="parameter">value</replaceable>).
14550 Both <replaceable class="parameter">offset</replaceable> and
14551 <replaceable class="parameter">default</replaceable> are evaluated
14552 with respect to the current row. If omitted,
14553 <replaceable class="parameter">offset</replaceable> defaults to 1 and
14554 <replaceable class="parameter">default</replaceable> to null
14561 <primary>first_value</primary>
14563 <function>first_value(<replaceable class="parameter">value</replaceable> <type>any</>)</function>
14566 <type>same type as <replaceable class="parameter">value</replaceable></type>
14569 returns <replaceable class="parameter">value</replaceable> evaluated
14570 at the row that is the first row of the window frame
14577 <primary>last_value</primary>
14579 <function>last_value(<replaceable class="parameter">value</replaceable> <type>any</>)</function>
14582 <type>same type as <replaceable class="parameter">value</replaceable></type>
14585 returns <replaceable class="parameter">value</replaceable> evaluated
14586 at the row that is the last row of the window frame
14593 <primary>nth_value</primary>
14596 nth_value(<replaceable class="parameter">value</replaceable> <type>any</>, <replaceable class="parameter">nth</replaceable> <type>integer</>)
14600 <type>same type as <replaceable class="parameter">value</replaceable></type>
14603 returns <replaceable class="parameter">value</replaceable> evaluated
14604 at the row that is the <replaceable class="parameter">nth</replaceable>
14605 row of the window frame (counting from 1); null if no such row
14613 All of the functions listed in
14614 <xref linkend="functions-window-table"> depend on the sort ordering
14615 specified by the <literal>ORDER BY</> clause of the associated window
14616 definition. Rows that are not distinct in the <literal>ORDER BY</>
14617 ordering are said to be <firstterm>peers</>; the four ranking functions
14618 are defined so that they give the same answer for any two peer rows.
14622 Note that <function>first_value</>, <function>last_value</>, and
14623 <function>nth_value</> consider only the rows within the <quote>window
14624 frame</>, which by default contains the rows from the start of the
14625 partition through the last peer of the current row. This is
14626 likely to give unhelpful results for <function>last_value</> and
14627 sometimes also <function>nth_value</>. You can redefine the frame by
14628 adding a suitable frame specification (<literal>RANGE</> or
14629 <literal>ROWS</>) to the <literal>OVER</> clause.
14630 See <xref linkend="syntax-window-functions"> for more information
14631 about frame specifications.
14635 When an aggregate function is used as a window function, it aggregates
14636 over the rows within the current row's window frame.
14637 An aggregate used with <literal>ORDER BY</> and the default window frame
14638 definition produces a <quote>running sum</> type of behavior, which may or
14639 may not be what's wanted. To obtain
14640 aggregation over the whole partition, omit <literal>ORDER BY</> or use
14641 <literal>ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING</>.
14642 Other frame specifications can be used to obtain other effects.
14647 The SQL standard defines a <literal>RESPECT NULLS</> or
14648 <literal>IGNORE NULLS</> option for <function>lead</>, <function>lag</>,
14649 <function>first_value</>, <function>last_value</>, and
14650 <function>nth_value</>. This is not implemented in
14651 <productname>PostgreSQL</productname>: the behavior is always the
14652 same as the standard's default, namely <literal>RESPECT NULLS</>.
14653 Likewise, the standard's <literal>FROM FIRST</> or <literal>FROM LAST</>
14654 option for <function>nth_value</> is not implemented: only the
14655 default <literal>FROM FIRST</> behavior is supported. (You can achieve
14656 the result of <literal>FROM LAST</> by reversing the <literal>ORDER BY</>
14663 <sect1 id="functions-subquery">
14664 <title>Subquery Expressions</title>
14667 <primary>EXISTS</primary>
14671 <primary>IN</primary>
14675 <primary>NOT IN</primary>
14679 <primary>ANY</primary>
14683 <primary>ALL</primary>
14687 <primary>SOME</primary>
14691 <primary>subquery</primary>
14695 This section describes the <acronym>SQL</acronym>-compliant subquery
14696 expressions available in <productname>PostgreSQL</productname>.
14697 All of the expression forms documented in this section return
14698 Boolean (true/false) results.
14701 <sect2 id="functions-subquery-exists">
14702 <title><literal>EXISTS</literal></title>
14705 EXISTS (<replaceable>subquery</replaceable>)
14709 The argument of <token>EXISTS</token> is an arbitrary <command>SELECT</> statement,
14710 or <firstterm>subquery</firstterm>. The
14711 subquery is evaluated to determine whether it returns any rows.
14712 If it returns at least one row, the result of <token>EXISTS</token> is
14713 <quote>true</>; if the subquery returns no rows, the result of <token>EXISTS</token>
14714 is <quote>false</>.
14718 The subquery can refer to variables from the surrounding query,
14719 which will act as constants during any one evaluation of the subquery.
14723 The subquery will generally only be executed long enough to determine
14724 whether at least one row is returned, not all the way to completion.
14725 It is unwise to write a subquery that has side effects (such as
14726 calling sequence functions); whether the side effects occur
14727 might be unpredictable.
14731 Since the result depends only on whether any rows are returned,
14732 and not on the contents of those rows, the output list of the
14733 subquery is normally unimportant. A common coding convention is
14734 to write all <literal>EXISTS</> tests in the form
14735 <literal>EXISTS(SELECT 1 WHERE ...)</literal>. There are exceptions to
14736 this rule however, such as subqueries that use <token>INTERSECT</token>.
14740 This simple example is like an inner join on <literal>col2</>, but
14741 it produces at most one output row for each <literal>tab1</> row,
14742 even if there are several matching <literal>tab2</> rows:
14746 WHERE EXISTS (SELECT 1 FROM tab2 WHERE col2 = tab1.col2);
14751 <sect2 id="functions-subquery-in">
14752 <title><literal>IN</literal></title>
14755 <replaceable>expression</replaceable> IN (<replaceable>subquery</replaceable>)
14759 The right-hand side is a parenthesized
14760 subquery, which must return exactly one column. The left-hand expression
14761 is evaluated and compared to each row of the subquery result.
14762 The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
14763 The result is <quote>false</> if no equal row is found (including the
14764 case where the subquery returns no rows).
14768 Note that if the left-hand expression yields null, or if there are
14769 no equal right-hand values and at least one right-hand row yields
14770 null, the result of the <token>IN</token> construct will be null, not false.
14771 This is in accordance with SQL's normal rules for Boolean combinations
14776 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14777 be evaluated completely.
14781 <replaceable>row_constructor</replaceable> IN (<replaceable>subquery</replaceable>)
14785 The left-hand side of this form of <token>IN</token> is a row constructor,
14786 as described in <xref linkend="sql-syntax-row-constructors">.
14787 The right-hand side is a parenthesized
14788 subquery, which must return exactly as many columns as there are
14789 expressions in the left-hand row. The left-hand expressions are
14790 evaluated and compared row-wise to each row of the subquery result.
14791 The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
14792 The result is <quote>false</> if no equal row is found (including the
14793 case where the subquery returns no rows).
14797 As usual, null values in the rows are combined per
14798 the normal rules of SQL Boolean expressions. Two rows are considered
14799 equal if all their corresponding members are non-null and equal; the rows
14800 are unequal if any corresponding members are non-null and unequal;
14801 otherwise the result of that row comparison is unknown (null).
14802 If all the per-row results are either unequal or null, with at least one
14803 null, then the result of <token>IN</token> is null.
14807 <sect2 id="functions-subquery-notin">
14808 <title><literal>NOT IN</literal></title>
14811 <replaceable>expression</replaceable> NOT IN (<replaceable>subquery</replaceable>)
14815 The right-hand side is a parenthesized
14816 subquery, which must return exactly one column. The left-hand expression
14817 is evaluated and compared to each row of the subquery result.
14818 The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
14819 are found (including the case where the subquery returns no rows).
14820 The result is <quote>false</> if any equal row is found.
14824 Note that if the left-hand expression yields null, or if there are
14825 no equal right-hand values and at least one right-hand row yields
14826 null, the result of the <token>NOT IN</token> construct will be null, not true.
14827 This is in accordance with SQL's normal rules for Boolean combinations
14832 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14833 be evaluated completely.
14837 <replaceable>row_constructor</replaceable> NOT IN (<replaceable>subquery</replaceable>)
14841 The left-hand side of this form of <token>NOT IN</token> is a row constructor,
14842 as described in <xref linkend="sql-syntax-row-constructors">.
14843 The right-hand side is a parenthesized
14844 subquery, which must return exactly as many columns as there are
14845 expressions in the left-hand row. The left-hand expressions are
14846 evaluated and compared row-wise to each row of the subquery result.
14847 The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
14848 are found (including the case where the subquery returns no rows).
14849 The result is <quote>false</> if any equal row is found.
14853 As usual, null values in the rows are combined per
14854 the normal rules of SQL Boolean expressions. Two rows are considered
14855 equal if all their corresponding members are non-null and equal; the rows
14856 are unequal if any corresponding members are non-null and unequal;
14857 otherwise the result of that row comparison is unknown (null).
14858 If all the per-row results are either unequal or null, with at least one
14859 null, then the result of <token>NOT IN</token> is null.
14863 <sect2 id="functions-subquery-any-some">
14864 <title><literal>ANY</literal>/<literal>SOME</literal></title>
14867 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>subquery</replaceable>)
14868 <replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>subquery</replaceable>)
14872 The right-hand side is a parenthesized
14873 subquery, which must return exactly one column. The left-hand expression
14874 is evaluated and compared to each row of the subquery result using the
14875 given <replaceable>operator</replaceable>, which must yield a Boolean
14877 The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
14878 The result is <quote>false</> if no true result is found (including the
14879 case where the subquery returns no rows).
14883 <token>SOME</token> is a synonym for <token>ANY</token>.
14884 <token>IN</token> is equivalent to <literal>= ANY</literal>.
14888 Note that if there are no successes and at least one right-hand row yields
14889 null for the operator's result, the result of the <token>ANY</token> construct
14890 will be null, not false.
14891 This is in accordance with SQL's normal rules for Boolean combinations
14896 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14897 be evaluated completely.
14901 <replaceable>row_constructor</replaceable> <replaceable>operator</> ANY (<replaceable>subquery</replaceable>)
14902 <replaceable>row_constructor</replaceable> <replaceable>operator</> SOME (<replaceable>subquery</replaceable>)
14906 The left-hand side of this form of <token>ANY</token> is a row constructor,
14907 as described in <xref linkend="sql-syntax-row-constructors">.
14908 The right-hand side is a parenthesized
14909 subquery, which must return exactly as many columns as there are
14910 expressions in the left-hand row. The left-hand expressions are
14911 evaluated and compared row-wise to each row of the subquery result,
14912 using the given <replaceable>operator</replaceable>.
14913 The result of <token>ANY</token> is <quote>true</> if the comparison
14914 returns true for any subquery row.
14915 The result is <quote>false</> if the comparison returns false for every
14916 subquery row (including the case where the subquery returns no
14918 The result is NULL if the comparison does not return true for any row,
14919 and it returns NULL for at least one row.
14923 See <xref linkend="row-wise-comparison"> for details about the meaning
14924 of a row constructor comparison.
14928 <sect2 id="functions-subquery-all">
14929 <title><literal>ALL</literal></title>
14932 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
14936 The right-hand side is a parenthesized
14937 subquery, which must return exactly one column. The left-hand expression
14938 is evaluated and compared to each row of the subquery result using the
14939 given <replaceable>operator</replaceable>, which must yield a Boolean
14941 The result of <token>ALL</token> is <quote>true</> if all rows yield true
14942 (including the case where the subquery returns no rows).
14943 The result is <quote>false</> if any false result is found.
14944 The result is NULL if the comparison does not return false for any row,
14945 and it returns NULL for at least one row.
14949 <token>NOT IN</token> is equivalent to <literal><> ALL</literal>.
14953 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14954 be evaluated completely.
14958 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
14962 The left-hand side of this form of <token>ALL</token> is a row constructor,
14963 as described in <xref linkend="sql-syntax-row-constructors">.
14964 The right-hand side is a parenthesized
14965 subquery, which must return exactly as many columns as there are
14966 expressions in the left-hand row. The left-hand expressions are
14967 evaluated and compared row-wise to each row of the subquery result,
14968 using the given <replaceable>operator</replaceable>.
14969 The result of <token>ALL</token> is <quote>true</> if the comparison
14970 returns true for all subquery rows (including the
14971 case where the subquery returns no rows).
14972 The result is <quote>false</> if the comparison returns false for any
14974 The result is NULL if the comparison does not return false for any
14975 subquery row, and it returns NULL for at least one row.
14979 See <xref linkend="row-wise-comparison"> for details about the meaning
14980 of a row constructor comparison.
14985 <title>Single-row Comparison</title>
14987 <indexterm zone="functions-subquery">
14988 <primary>comparison</primary>
14989 <secondary>subquery result row</secondary>
14993 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> (<replaceable>subquery</replaceable>)
14997 The left-hand side is a row constructor,
14998 as described in <xref linkend="sql-syntax-row-constructors">.
14999 The right-hand side is a parenthesized subquery, which must return exactly
15000 as many columns as there are expressions in the left-hand row. Furthermore,
15001 the subquery cannot return more than one row. (If it returns zero rows,
15002 the result is taken to be null.) The left-hand side is evaluated and
15003 compared row-wise to the single subquery result row.
15007 See <xref linkend="row-wise-comparison"> for details about the meaning
15008 of a row constructor comparison.
15014 <sect1 id="functions-comparisons">
15015 <title>Row and Array Comparisons</title>
15018 <primary>IN</primary>
15022 <primary>NOT IN</primary>
15026 <primary>ANY</primary>
15030 <primary>ALL</primary>
15034 <primary>SOME</primary>
15038 <primary>composite type</primary>
15039 <secondary>comparison</secondary>
15043 <primary>row-wise comparison</primary>
15047 <primary>comparison</primary>
15048 <secondary>composite type</secondary>
15052 <primary>comparison</primary>
15053 <secondary>row constructor</secondary>
15057 <primary>IS DISTINCT FROM</primary>
15061 <primary>IS NOT DISTINCT FROM</primary>
15065 This section describes several specialized constructs for making
15066 multiple comparisons between groups of values. These forms are
15067 syntactically related to the subquery forms of the previous section,
15068 but do not involve subqueries.
15069 The forms involving array subexpressions are
15070 <productname>PostgreSQL</productname> extensions; the rest are
15071 <acronym>SQL</acronym>-compliant.
15072 All of the expression forms documented in this section return
15073 Boolean (true/false) results.
15076 <sect2 id="functions-comparisons-in-scalar">
15077 <title><literal>IN</literal></title>
15080 <replaceable>expression</replaceable> IN (<replaceable>value</replaceable> <optional>, ...</optional>)
15084 The right-hand side is a parenthesized list
15085 of scalar expressions. The result is <quote>true</> if the left-hand expression's
15086 result is equal to any of the right-hand expressions. This is a shorthand
15090 <replaceable>expression</replaceable> = <replaceable>value1</replaceable>
15092 <replaceable>expression</replaceable> = <replaceable>value2</replaceable>
15099 Note that if the left-hand expression yields null, or if there are
15100 no equal right-hand values and at least one right-hand expression yields
15101 null, the result of the <token>IN</token> construct will be null, not false.
15102 This is in accordance with SQL's normal rules for Boolean combinations
15108 <title><literal>NOT IN</literal></title>
15111 <replaceable>expression</replaceable> NOT IN (<replaceable>value</replaceable> <optional>, ...</optional>)
15115 The right-hand side is a parenthesized list
15116 of scalar expressions. The result is <quote>true</quote> if the left-hand expression's
15117 result is unequal to all of the right-hand expressions. This is a shorthand
15121 <replaceable>expression</replaceable> <> <replaceable>value1</replaceable>
15123 <replaceable>expression</replaceable> <> <replaceable>value2</replaceable>
15130 Note that if the left-hand expression yields null, or if there are
15131 no equal right-hand values and at least one right-hand expression yields
15132 null, the result of the <token>NOT IN</token> construct will be null, not true
15133 as one might naively expect.
15134 This is in accordance with SQL's normal rules for Boolean combinations
15140 <literal>x NOT IN y</literal> is equivalent to <literal>NOT (x IN y)</literal> in all
15141 cases. However, null values are much more likely to trip up the novice when
15142 working with <token>NOT IN</token> than when working with <token>IN</token>.
15143 It is best to express your condition positively if possible.
15149 <title><literal>ANY</literal>/<literal>SOME</literal> (array)</title>
15152 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>array expression</replaceable>)
15153 <replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>array expression</replaceable>)
15157 The right-hand side is a parenthesized expression, which must yield an
15159 The left-hand expression
15160 is evaluated and compared to each element of the array using the
15161 given <replaceable>operator</replaceable>, which must yield a Boolean
15163 The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
15164 The result is <quote>false</> if no true result is found (including the
15165 case where the array has zero elements).
15169 If the array expression yields a null array, the result of
15170 <token>ANY</token> will be null. If the left-hand expression yields null,
15171 the result of <token>ANY</token> is ordinarily null (though a non-strict
15172 comparison operator could possibly yield a different result).
15173 Also, if the right-hand array contains any null elements and no true
15174 comparison result is obtained, the result of <token>ANY</token>
15175 will be null, not false (again, assuming a strict comparison operator).
15176 This is in accordance with SQL's normal rules for Boolean combinations
15181 <token>SOME</token> is a synonym for <token>ANY</token>.
15186 <title><literal>ALL</literal> (array)</title>
15189 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>array expression</replaceable>)
15193 The right-hand side is a parenthesized expression, which must yield an
15195 The left-hand expression
15196 is evaluated and compared to each element of the array using the
15197 given <replaceable>operator</replaceable>, which must yield a Boolean
15199 The result of <token>ALL</token> is <quote>true</> if all comparisons yield true
15200 (including the case where the array has zero elements).
15201 The result is <quote>false</> if any false result is found.
15205 If the array expression yields a null array, the result of
15206 <token>ALL</token> will be null. If the left-hand expression yields null,
15207 the result of <token>ALL</token> is ordinarily null (though a non-strict
15208 comparison operator could possibly yield a different result).
15209 Also, if the right-hand array contains any null elements and no false
15210 comparison result is obtained, the result of <token>ALL</token>
15211 will be null, not true (again, assuming a strict comparison operator).
15212 This is in accordance with SQL's normal rules for Boolean combinations
15217 <sect2 id="row-wise-comparison">
15218 <title>Row Constructor Comparison</title>
15221 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> <replaceable>row_constructor</replaceable>
15225 Each side is a row constructor,
15226 as described in <xref linkend="sql-syntax-row-constructors">.
15227 The two row values must have the same number of fields.
15228 Each side is evaluated and they are compared row-wise. Row constructor
15229 comparisons are allowed when the <replaceable>operator</replaceable> is
15231 <literal><></>,
15234 <literal>></> or
15236 Every row element must be of a type which has a default B-tree operator
15237 class or the attempted comparison may generate an error.
15242 Errors related to the number or types of elements might not occur if
15243 the comparison is resolved using earlier columns.
15248 The <literal>=</> and <literal><></> cases work slightly differently
15249 from the others. Two rows are considered
15250 equal if all their corresponding members are non-null and equal; the rows
15251 are unequal if any corresponding members are non-null and unequal;
15252 otherwise the result of the row comparison is unknown (null).
15256 For the <literal><</>, <literal><=</>, <literal>></> and
15257 <literal>>=</> cases, the row elements are compared left-to-right,
15258 stopping as soon as an unequal or null pair of elements is found.
15259 If either of this pair of elements is null, the result of the
15260 row comparison is unknown (null); otherwise comparison of this pair
15261 of elements determines the result. For example,
15262 <literal>ROW(1,2,NULL) < ROW(1,3,0)</>
15263 yields true, not null, because the third pair of elements are not
15269 Prior to <productname>PostgreSQL</productname> 8.2, the
15270 <literal><</>, <literal><=</>, <literal>></> and <literal>>=</>
15271 cases were not handled per SQL specification. A comparison like
15272 <literal>ROW(a,b) < ROW(c,d)</>
15274 <literal>a < c AND b < d</>
15275 whereas the correct behavior is equivalent to
15276 <literal>a < c OR (a = c AND b < d)</>.
15281 <replaceable>row_constructor</replaceable> IS DISTINCT FROM <replaceable>row_constructor</replaceable>
15285 This construct is similar to a <literal><></literal> row comparison,
15286 but it does not yield null for null inputs. Instead, any null value is
15287 considered unequal to (distinct from) any non-null value, and any two
15288 nulls are considered equal (not distinct). Thus the result will
15289 either be true or false, never null.
15293 <replaceable>row_constructor</replaceable> IS NOT DISTINCT FROM <replaceable>row_constructor</replaceable>
15297 This construct is similar to a <literal>=</literal> row comparison,
15298 but it does not yield null for null inputs. Instead, any null value is
15299 considered unequal to (distinct from) any non-null value, and any two
15300 nulls are considered equal (not distinct). Thus the result will always
15301 be either true or false, never null.
15306 <sect2 id="composite-type-comparison">
15307 <title>Composite Type Comparison</title>
15310 <replaceable>record</replaceable> <replaceable>operator</replaceable> <replaceable>record</replaceable>
15314 The SQL specification requires row-wise comparison to return NULL if the
15315 result depends on comparing two NULL values or a NULL and a non-NULL.
15316 <productname>PostgreSQL</productname> does this only when comparing the
15317 results of two row constructors (as in
15318 <xref linkend="row-wise-comparison">) or comparing a row constructor
15319 to the output of a subquery (as in <xref linkend="functions-subquery">).
15320 In other contexts where two composite-type values are compared, two
15321 NULL field values are considered equal, and a NULL is considered larger
15322 than a non-NULL. This is necessary in order to have consistent sorting
15323 and indexing behavior for composite types.
15327 Each side is evaluated and they are compared row-wise. Composite type
15328 comparisons are allowed when the <replaceable>operator</replaceable> is
15330 <literal><></>,
15333 <literal>></> or
15335 or has semantics similar to one of these. (To be specific, an operator
15336 can be a row comparison operator if it is a member of a B-tree operator
15337 class, or is the negator of the <literal>=</> member of a B-tree operator
15338 class.) The default behavior of the above operators is the same as for
15339 <literal>IS [ NOT ] DISTINCT FROM</literal> for row constructors (see
15340 <xref linkend="row-wise-comparison">).
15344 To support matching of rows which include elements without a default
15345 B-tree operator class, the following operators are defined for composite
15348 <literal>*<></>,
15350 <literal>*<=</>,
15351 <literal>*></>, and
15352 <literal>*>=</>.
15353 These operators compare the internal binary representation of the two
15354 rows. Two rows might have a different binary representation even
15355 though comparisons of the two rows with the equality operator is true.
15356 The ordering of rows under these comparison operators is deterministic
15357 but not otherwise meaningful. These operators are used internally for
15358 materialized views and might be useful for other specialized purposes
15359 such as replication but are not intended to be generally useful for
15365 <sect1 id="functions-srf">
15366 <title>Set Returning Functions</title>
15368 <indexterm zone="functions-srf">
15369 <primary>set returning functions</primary>
15370 <secondary>functions</secondary>
15374 <primary>generate_series</primary>
15378 This section describes functions that possibly return more than one row.
15379 The most widely used functions in this class are series generating
15380 functions, as detailed in <xref linkend="functions-srf-series"> and
15381 <xref linkend="functions-srf-subscripts">. Other, more specialized
15382 set-returning functions are described elsewhere in this manual.
15383 See <xref linkend="queries-tablefunctions"> for ways to combine multiple
15384 set-returning functions.
15387 <table id="functions-srf-series">
15388 <title>Series Generating Functions</title>
15392 <entry>Function</entry>
15393 <entry>Argument Type</entry>
15394 <entry>Return Type</entry>
15395 <entry>Description</entry>
15401 <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>)</function></literal></entry>
15402 <entry><type>int</type>, <type>bigint</type> or <type>numeric</type></entry>
15403 <entry><type>setof int</type>, <type>setof bigint</type>, or <type>setof numeric</type> (same as argument type)</entry>
15405 Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
15406 with a step size of one
15411 <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>, <parameter>step</parameter>)</function></literal></entry>
15412 <entry><type>int</type>, <type>bigint</type> or <type>numeric</type></entry>
15413 <entry><type>setof int</type>, <type>setof bigint</type> or <type>setof numeric</type> (same as argument type)</entry>
15415 Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
15416 with a step size of <parameter>step</parameter>
15421 <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>, <parameter>step</parameter> <type>interval</>)</function></literal></entry>
15422 <entry><type>timestamp</type> or <type>timestamp with time zone</type></entry>
15423 <entry><type>setof timestamp</type> or <type>setof timestamp with time zone</type> (same as argument type)</entry>
15425 Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
15426 with a step size of <parameter>step</parameter>
15435 When <parameter>step</parameter> is positive, zero rows are returned if
15436 <parameter>start</parameter> is greater than <parameter>stop</parameter>.
15437 Conversely, when <parameter>step</parameter> is negative, zero rows are
15438 returned if <parameter>start</parameter> is less than <parameter>stop</parameter>.
15439 Zero rows are also returned for <literal>NULL</literal> inputs. It is an error
15440 for <parameter>step</parameter> to be zero. Some examples follow:
15442 SELECT * FROM generate_series(2,4);
15450 SELECT * FROM generate_series(5,1,-2);
15458 SELECT * FROM generate_series(4,3);
15463 SELECT generate_series(1.1, 4, 1.3);
15471 -- this example relies on the date-plus-integer operator
15472 SELECT current_date + s.a AS dates FROM generate_series(0,14,7) AS s(a);
15480 SELECT * FROM generate_series('2008-03-01 00:00'::timestamp,
15481 '2008-03-04 12:00', '10 hours');
15483 ---------------------
15484 2008-03-01 00:00:00
15485 2008-03-01 10:00:00
15486 2008-03-01 20:00:00
15487 2008-03-02 06:00:00
15488 2008-03-02 16:00:00
15489 2008-03-03 02:00:00
15490 2008-03-03 12:00:00
15491 2008-03-03 22:00:00
15492 2008-03-04 08:00:00
15497 <table id="functions-srf-subscripts">
15498 <title>Subscript Generating Functions</title>
15502 <entry>Function</entry>
15503 <entry>Return Type</entry>
15504 <entry>Description</entry>
15510 <entry><literal><function>generate_subscripts(<parameter>array anyarray</parameter>, <parameter>dim int</parameter>)</function></literal></entry>
15511 <entry><type>setof int</type></entry>
15513 Generate a series comprising the given array's subscripts.
15518 <entry><literal><function>generate_subscripts(<parameter>array anyarray</parameter>, <parameter>dim int</parameter>, <parameter>reverse boolean</parameter>)</function></literal></entry>
15519 <entry><type>setof int</type></entry>
15521 Generate a series comprising the given array's subscripts. When
15522 <parameter>reverse</parameter> is true, the series is returned in
15532 <primary>generate_subscripts</primary>
15536 <function>generate_subscripts</> is a convenience function that generates
15537 the set of valid subscripts for the specified dimension of the given
15539 Zero rows are returned for arrays that do not have the requested dimension,
15540 or for NULL arrays (but valid subscripts are returned for NULL array
15541 elements). Some examples follow:
15544 SELECT generate_subscripts('{NULL,1,NULL,2}'::int[], 1) AS s;
15553 -- presenting an array, the subscript and the subscripted
15554 -- value requires a subquery
15555 SELECT * FROM arrays;
15557 --------------------
15562 SELECT a AS array, s AS subscript, a[s] AS value
15563 FROM (SELECT generate_subscripts(a, 1) AS s, a FROM arrays) foo;
15564 array | subscript | value
15565 ---------------+-----------+-------
15568 {100,200,300} | 1 | 100
15569 {100,200,300} | 2 | 200
15570 {100,200,300} | 3 | 300
15573 -- unnest a 2D array
15574 CREATE OR REPLACE FUNCTION unnest2(anyarray)
15575 RETURNS SETOF anyelement AS $$
15577 from generate_subscripts($1,1) g1(i),
15578 generate_subscripts($1,2) g2(j);
15579 $$ LANGUAGE sql IMMUTABLE;
15581 SELECT * FROM unnest2(ARRAY[[1,2],[3,4]]);
15593 <primary>ordinality</primary>
15597 When a function in the <literal>FROM</literal> clause is suffixed
15598 by <literal>WITH ORDINALITY</literal>, a <type>bigint</type> column is
15599 appended to the output which starts from 1 and increments by 1 for each row
15600 of the function's output. This is most useful in the case of set returning
15601 functions such as <function>unnest()</>.
15604 -- set returning function WITH ORDINALITY
15605 SELECT * FROM pg_ls_dir('.') WITH ORDINALITY AS t(ls,n);
15607 -----------------+----
15610 postmaster.opts | 3
15612 postgresql.conf | 5
15633 <sect1 id="functions-info">
15634 <title>System Information Functions</title>
15637 <xref linkend="functions-info-session-table"> shows several
15638 functions that extract session and system information.
15642 In addition to the functions listed in this section, there are a number of
15643 functions related to the statistics system that also provide system
15644 information. See <xref linkend="monitoring-stats-views"> for more
15648 <table id="functions-info-session-table">
15649 <title>Session Information Functions</title>
15652 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
15657 <entry><literal><function>current_catalog</function></literal></entry>
15658 <entry><type>name</type></entry>
15659 <entry>name of current database (called <quote>catalog</quote> in the SQL standard)</entry>
15663 <entry><literal><function>current_database()</function></literal></entry>
15664 <entry><type>name</type></entry>
15665 <entry>name of current database</entry>
15669 <entry><literal><function>current_query()</function></literal></entry>
15670 <entry><type>text</type></entry>
15671 <entry>text of the currently executing query, as submitted
15672 by the client (might contain more than one statement)</entry>
15676 <entry><literal><function>current_schema</function>[()]</literal></entry>
15677 <entry><type>name</type></entry>
15678 <entry>name of current schema</entry>
15682 <entry><literal><function>current_schemas(<type>boolean</type>)</function></literal></entry>
15683 <entry><type>name[]</type></entry>
15684 <entry>names of schemas in search path, optionally including implicit schemas</entry>
15688 <entry><literal><function>current_user</function></literal></entry>
15689 <entry><type>name</type></entry>
15690 <entry>user name of current execution context</entry>
15694 <entry><literal><function>inet_client_addr()</function></literal></entry>
15695 <entry><type>inet</type></entry>
15696 <entry>address of the remote connection</entry>
15700 <entry><literal><function>inet_client_port()</function></literal></entry>
15701 <entry><type>int</type></entry>
15702 <entry>port of the remote connection</entry>
15706 <entry><literal><function>inet_server_addr()</function></literal></entry>
15707 <entry><type>inet</type></entry>
15708 <entry>address of the local connection</entry>
15712 <entry><literal><function>inet_server_port()</function></literal></entry>
15713 <entry><type>int</type></entry>
15714 <entry>port of the local connection</entry>
15718 <!-- See also the entry for this in monitoring.sgml -->
15719 <entry><literal><function>pg_backend_pid()</function></literal></entry>
15720 <entry><type>int</type></entry>
15722 Process ID of the server process attached to the current session
15727 <entry><literal><function>pg_blocking_pids(<type>int</type>)</function></literal></entry>
15728 <entry><type>int[]</type></entry>
15729 <entry>Process ID(s) that are blocking specified server process ID</entry>
15733 <entry><literal><function>pg_conf_load_time()</function></literal></entry>
15734 <entry><type>timestamp with time zone</type></entry>
15735 <entry>configuration load time</entry>
15739 <entry><literal><function>pg_current_logfile(<optional><type>text</></optional>)</function></literal></entry>
15740 <entry><type>text</type></entry>
15741 <entry>Primary log file name, or log in the requested format,
15742 currently in use by the logging collector</entry>
15746 <entry><literal><function>pg_my_temp_schema()</function></literal></entry>
15747 <entry><type>oid</type></entry>
15748 <entry>OID of session's temporary schema, or 0 if none</entry>
15752 <entry><literal><function>pg_is_other_temp_schema(<type>oid</type>)</function></literal></entry>
15753 <entry><type>boolean</type></entry>
15754 <entry>is schema another session's temporary schema?</entry>
15758 <entry><literal><function>pg_listening_channels()</function></literal></entry>
15759 <entry><type>setof text</type></entry>
15760 <entry>channel names that the session is currently listening on</entry>
15764 <entry><literal><function>pg_notification_queue_usage()</function></literal></entry>
15765 <entry><type>double</type></entry>
15766 <entry>fraction of the asynchronous notification queue currently occupied (0-1)</entry>
15770 <entry><literal><function>pg_postmaster_start_time()</function></literal></entry>
15771 <entry><type>timestamp with time zone</type></entry>
15772 <entry>server start time</entry>
15776 <entry><literal><function>pg_trigger_depth()</function></literal></entry>
15777 <entry><type>int</type></entry>
15778 <entry>current nesting level of <productname>PostgreSQL</> triggers
15779 (0 if not called, directly or indirectly, from inside a trigger)</entry>
15783 <entry><literal><function>session_user</function></literal></entry>
15784 <entry><type>name</type></entry>
15785 <entry>session user name</entry>
15789 <entry><literal><function>user</function></literal></entry>
15790 <entry><type>name</type></entry>
15791 <entry>equivalent to <function>current_user</function></entry>
15795 <entry><literal><function>version()</function></literal></entry>
15796 <entry><type>text</type></entry>
15797 <entry><productname>PostgreSQL</> version information. See also <xref linkend="guc-server-version-num"> for a machine-readable version.</entry>
15805 <function>current_catalog</function>, <function>current_schema</function>,
15806 <function>current_user</function>, <function>session_user</function>,
15807 and <function>user</function> have special syntactic status
15808 in <acronym>SQL</acronym>: they must be called without trailing
15809 parentheses. (In PostgreSQL, parentheses can optionally be used with
15810 <function>current_schema</function>, but not with the others.)
15815 <primary>current_catalog</primary>
15819 <primary>current_database</primary>
15823 <primary>current_query</primary>
15827 <primary>current_schema</primary>
15831 <primary>current_schemas</primary>
15835 <primary>current_user</primary>
15839 <primary>pg_backend_pid</primary>
15843 <primary>schema</primary>
15844 <secondary>current</secondary>
15848 <primary>search path</primary>
15849 <secondary>current</secondary>
15853 <primary>session_user</primary>
15857 <primary>user</primary>
15858 <secondary>current</secondary>
15862 <primary>user</primary>
15866 The <function>session_user</function> is normally the user who initiated
15867 the current database connection; but superusers can change this setting
15868 with <xref linkend="sql-set-session-authorization">.
15869 The <function>current_user</function> is the user identifier
15870 that is applicable for permission checking. Normally it is equal
15871 to the session user, but it can be changed with
15872 <xref linkend="sql-set-role">.
15873 It also changes during the execution of
15874 functions with the attribute <literal>SECURITY DEFINER</literal>.
15875 In Unix parlance, the session user is the <quote>real user</quote> and
15876 the current user is the <quote>effective user</quote>.
15880 <function>current_schema</function> returns the name of the schema that is
15881 first in the search path (or a null value if the search path is
15882 empty). This is the schema that will be used for any tables or
15883 other named objects that are created without specifying a target schema.
15884 <function>current_schemas(boolean)</function> returns an array of the names of all
15885 schemas presently in the search path. The Boolean option determines whether or not
15886 implicitly included system schemas such as <literal>pg_catalog</> are included in the
15887 returned search path.
15892 The search path can be altered at run time. The command is:
15894 SET search_path TO <replaceable>schema</> <optional>, <replaceable>schema</>, ...</optional>
15900 <primary>inet_client_addr</primary>
15904 <primary>inet_client_port</primary>
15908 <primary>inet_server_addr</primary>
15912 <primary>inet_server_port</primary>
15916 <function>inet_client_addr</function> returns the IP address of the
15917 current client, and <function>inet_client_port</function> returns the
15919 <function>inet_server_addr</function> returns the IP address on which
15920 the server accepted the current connection, and
15921 <function>inet_server_port</function> returns the port number.
15922 All these functions return NULL if the current connection is via a
15923 Unix-domain socket.
15927 <primary>pg_blocking_pids</primary>
15931 <function>pg_blocking_pids</function> returns an array of the process IDs
15932 of the sessions that are blocking the server process with the specified
15933 process ID, or an empty array if there is no such server process or it is
15934 not blocked. One server process blocks another if it either holds a lock
15935 that conflicts with the blocked process's lock request (hard block), or is
15936 waiting for a lock that would conflict with the blocked process's lock
15937 request and is ahead of it in the wait queue (soft block). When using
15938 parallel queries the result always lists client-visible process IDs (that
15939 is, <function>pg_backend_pid</> results) even if the actual lock is held
15940 or awaited by a child worker process. As a result of that, there may be
15941 duplicated PIDs in the result. Also note that when a prepared transaction
15942 holds a conflicting lock, it will be represented by a zero process ID in
15943 the result of this function.
15944 Frequent calls to this function could have some impact on database
15945 performance, because it needs exclusive access to the lock manager's
15946 shared state for a short time.
15950 <primary>pg_conf_load_time</primary>
15954 <function>pg_conf_load_time</function> returns the
15955 <type>timestamp with time zone</type> when the
15956 server configuration files were last loaded.
15957 (If the current session was alive at the time, this will be the time
15958 when the session itself re-read the configuration files, so the
15959 reading will vary a little in different sessions. Otherwise it is
15960 the time when the postmaster process re-read the configuration files.)
15964 <primary>pg_current_logfile</primary>
15968 <primary>Logging</primary>
15969 <secondary>pg_current_logfile function</secondary>
15973 <primary>current_logfiles</primary>
15974 <secondary>and the pg_current_logfile function</secondary>
15978 <primary>Logging</primary>
15979 <secondary>current_logfiles file and the pg_current_logfile
15980 function</secondary>
15984 <function>pg_current_logfile</function> returns, as <type>text</type>,
15985 the path of the log file(s) currently in use by the logging collector.
15986 The path includes the <xref linkend="guc-log-directory"> directory
15987 and the log file name. Log collection must be enabled or the return value
15988 is <literal>NULL</literal>. When multiple log files exist, each in a
15989 different format, <function>pg_current_logfile</function> called
15990 without arguments returns the path of the file having the first format
15991 found in the ordered list: <systemitem>stderr</>, <systemitem>csvlog</>.
15992 <literal>NULL</literal> is returned when no log file has any of these
15993 formats. To request a specific file format supply, as <type>text</type>,
15994 either <systemitem>csvlog</> or <systemitem>stderr</> as the value of the
15995 optional parameter. The return value is <literal>NULL</literal> when the
15996 log format requested is not a configured
15997 <xref linkend="guc-log-destination">. The
15998 <function>pg_current_logfiles</function> reflects the contents of the
15999 <filename>current_logfiles</> file.
16003 <primary>pg_my_temp_schema</primary>
16007 <primary>pg_is_other_temp_schema</primary>
16011 <function>pg_my_temp_schema</function> returns the OID of the current
16012 session's temporary schema, or zero if it has none (because it has not
16013 created any temporary tables).
16014 <function>pg_is_other_temp_schema</function> returns true if the
16015 given OID is the OID of another session's temporary schema.
16016 (This can be useful, for example, to exclude other sessions' temporary
16017 tables from a catalog display.)
16021 <primary>pg_listening_channels</primary>
16025 <primary>pg_notification_queue_usage</primary>
16029 <function>pg_listening_channels</function> returns a set of names of
16030 asynchronous notification channels that the current session is listening
16031 to. <function>pg_notification_queue_usage</function> returns the
16032 fraction of the total available space for notifications currently
16033 occupied by notifications that are waiting to be processed, as a
16034 <type>double</type> in the range 0-1.
16035 See <xref linkend="sql-listen"> and <xref linkend="sql-notify">
16036 for more information.
16040 <primary>pg_postmaster_start_time</primary>
16044 <function>pg_postmaster_start_time</function> returns the
16045 <type>timestamp with time zone</type> when the
16050 <primary>version</primary>
16054 <function>version</function> returns a string describing the
16055 <productname>PostgreSQL</productname> server's version. You can also
16056 get this information from <xref linkend="guc-server-version"> or
16057 for a machine-readable version, <xref linkend="guc-server-version-num">.
16058 Software developers should use <literal>server_version_num</literal>
16059 (available since 8.2) or <xref linkend="libpq-pqserverversion"> instead
16060 of parsing the text version.
16064 <primary>privilege</primary>
16065 <secondary>querying</secondary>
16069 <xref linkend="functions-info-access-table"> lists functions that
16070 allow the user to query object access privileges programmatically.
16071 See <xref linkend="ddl-priv"> for more information about
16075 <table id="functions-info-access-table">
16076 <title>Access Privilege Inquiry Functions</title>
16079 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16084 <entry><literal><function>has_any_column_privilege</function>(<parameter>user</parameter>,
16085 <parameter>table</parameter>,
16086 <parameter>privilege</parameter>)</literal>
16088 <entry><type>boolean</type></entry>
16089 <entry>does user have privilege for any column of table</entry>
16092 <entry><literal><function>has_any_column_privilege</function>(<parameter>table</parameter>,
16093 <parameter>privilege</parameter>)</literal>
16095 <entry><type>boolean</type></entry>
16096 <entry>does current user have privilege for any column of table</entry>
16099 <entry><literal><function>has_column_privilege</function>(<parameter>user</parameter>,
16100 <parameter>table</parameter>,
16101 <parameter>column</parameter>,
16102 <parameter>privilege</parameter>)</literal>
16104 <entry><type>boolean</type></entry>
16105 <entry>does user have privilege for column</entry>
16108 <entry><literal><function>has_column_privilege</function>(<parameter>table</parameter>,
16109 <parameter>column</parameter>,
16110 <parameter>privilege</parameter>)</literal>
16112 <entry><type>boolean</type></entry>
16113 <entry>does current user have privilege for column</entry>
16116 <entry><literal><function>has_database_privilege</function>(<parameter>user</parameter>,
16117 <parameter>database</parameter>,
16118 <parameter>privilege</parameter>)</literal>
16120 <entry><type>boolean</type></entry>
16121 <entry>does user have privilege for database</entry>
16124 <entry><literal><function>has_database_privilege</function>(<parameter>database</parameter>,
16125 <parameter>privilege</parameter>)</literal>
16127 <entry><type>boolean</type></entry>
16128 <entry>does current user have privilege for database</entry>
16131 <entry><literal><function>has_foreign_data_wrapper_privilege</function>(<parameter>user</parameter>,
16132 <parameter>fdw</parameter>,
16133 <parameter>privilege</parameter>)</literal>
16135 <entry><type>boolean</type></entry>
16136 <entry>does user have privilege for foreign-data wrapper</entry>
16139 <entry><literal><function>has_foreign_data_wrapper_privilege</function>(<parameter>fdw</parameter>,
16140 <parameter>privilege</parameter>)</literal>
16142 <entry><type>boolean</type></entry>
16143 <entry>does current user have privilege for foreign-data wrapper</entry>
16146 <entry><literal><function>has_function_privilege</function>(<parameter>user</parameter>,
16147 <parameter>function</parameter>,
16148 <parameter>privilege</parameter>)</literal>
16150 <entry><type>boolean</type></entry>
16151 <entry>does user have privilege for function</entry>
16154 <entry><literal><function>has_function_privilege</function>(<parameter>function</parameter>,
16155 <parameter>privilege</parameter>)</literal>
16157 <entry><type>boolean</type></entry>
16158 <entry>does current user have privilege for function</entry>
16161 <entry><literal><function>has_language_privilege</function>(<parameter>user</parameter>,
16162 <parameter>language</parameter>,
16163 <parameter>privilege</parameter>)</literal>
16165 <entry><type>boolean</type></entry>
16166 <entry>does user have privilege for language</entry>
16169 <entry><literal><function>has_language_privilege</function>(<parameter>language</parameter>,
16170 <parameter>privilege</parameter>)</literal>
16172 <entry><type>boolean</type></entry>
16173 <entry>does current user have privilege for language</entry>
16176 <entry><literal><function>has_schema_privilege</function>(<parameter>user</parameter>,
16177 <parameter>schema</parameter>,
16178 <parameter>privilege</parameter>)</literal>
16180 <entry><type>boolean</type></entry>
16181 <entry>does user have privilege for schema</entry>
16184 <entry><literal><function>has_schema_privilege</function>(<parameter>schema</parameter>,
16185 <parameter>privilege</parameter>)</literal>
16187 <entry><type>boolean</type></entry>
16188 <entry>does current user have privilege for schema</entry>
16191 <entry><literal><function>has_sequence_privilege</function>(<parameter>user</parameter>,
16192 <parameter>sequence</parameter>,
16193 <parameter>privilege</parameter>)</literal>
16195 <entry><type>boolean</type></entry>
16196 <entry>does user have privilege for sequence</entry>
16199 <entry><literal><function>has_sequence_privilege</function>(<parameter>sequence</parameter>,
16200 <parameter>privilege</parameter>)</literal>
16202 <entry><type>boolean</type></entry>
16203 <entry>does current user have privilege for sequence</entry>
16206 <entry><literal><function>has_server_privilege</function>(<parameter>user</parameter>,
16207 <parameter>server</parameter>,
16208 <parameter>privilege</parameter>)</literal>
16210 <entry><type>boolean</type></entry>
16211 <entry>does user have privilege for foreign server</entry>
16214 <entry><literal><function>has_server_privilege</function>(<parameter>server</parameter>,
16215 <parameter>privilege</parameter>)</literal>
16217 <entry><type>boolean</type></entry>
16218 <entry>does current user have privilege for foreign server</entry>
16221 <entry><literal><function>has_table_privilege</function>(<parameter>user</parameter>,
16222 <parameter>table</parameter>,
16223 <parameter>privilege</parameter>)</literal>
16225 <entry><type>boolean</type></entry>
16226 <entry>does user have privilege for table</entry>
16229 <entry><literal><function>has_table_privilege</function>(<parameter>table</parameter>,
16230 <parameter>privilege</parameter>)</literal>
16232 <entry><type>boolean</type></entry>
16233 <entry>does current user have privilege for table</entry>
16236 <entry><literal><function>has_tablespace_privilege</function>(<parameter>user</parameter>,
16237 <parameter>tablespace</parameter>,
16238 <parameter>privilege</parameter>)</literal>
16240 <entry><type>boolean</type></entry>
16241 <entry>does user have privilege for tablespace</entry>
16244 <entry><literal><function>has_tablespace_privilege</function>(<parameter>tablespace</parameter>,
16245 <parameter>privilege</parameter>)</literal>
16247 <entry><type>boolean</type></entry>
16248 <entry>does current user have privilege for tablespace</entry>
16251 <entry><literal><function>has_type_privilege</function>(<parameter>user</parameter>,
16252 <parameter>type</parameter>,
16253 <parameter>privilege</parameter>)</literal>
16255 <entry><type>boolean</type></entry>
16256 <entry>does user have privilege for type</entry>
16259 <entry><literal><function>has_type_privilege</function>(<parameter>type</parameter>,
16260 <parameter>privilege</parameter>)</literal>
16262 <entry><type>boolean</type></entry>
16263 <entry>does current user have privilege for type</entry>
16266 <entry><literal><function>pg_has_role</function>(<parameter>user</parameter>,
16267 <parameter>role</parameter>,
16268 <parameter>privilege</parameter>)</literal>
16270 <entry><type>boolean</type></entry>
16271 <entry>does user have privilege for role</entry>
16274 <entry><literal><function>pg_has_role</function>(<parameter>role</parameter>,
16275 <parameter>privilege</parameter>)</literal>
16277 <entry><type>boolean</type></entry>
16278 <entry>does current user have privilege for role</entry>
16281 <entry><literal><function>row_security_active</function>(<parameter>table</parameter>)</literal>
16283 <entry><type>boolean</type></entry>
16284 <entry>does current user have row level security active for table</entry>
16291 <primary>has_any_column_privilege</primary>
16294 <primary>has_column_privilege</primary>
16297 <primary>has_database_privilege</primary>
16300 <primary>has_function_privilege</primary>
16303 <primary>has_foreign_data_wrapper_privilege</primary>
16306 <primary>has_language_privilege</primary>
16309 <primary>has_schema_privilege</primary>
16312 <primary>has_server_privilege</primary>
16315 <primary>has_sequence_privilege</primary>
16318 <primary>has_table_privilege</primary>
16321 <primary>has_tablespace_privilege</primary>
16324 <primary>has_type_privilege</primary>
16327 <primary>pg_has_role</primary>
16330 <primary>row_security_active</primary>
16334 <function>has_table_privilege</function> checks whether a user
16335 can access a table in a particular way. The user can be
16336 specified by name, by OID (<literal>pg_authid.oid</literal>),
16337 <literal>public</> to indicate the PUBLIC pseudo-role, or if the argument is
16339 <function>current_user</function> is assumed. The table can be specified
16340 by name or by OID. (Thus, there are actually six variants of
16341 <function>has_table_privilege</function>, which can be distinguished by
16342 the number and types of their arguments.) When specifying by name,
16343 the name can be schema-qualified if necessary.
16344 The desired access privilege type
16345 is specified by a text string, which must evaluate to one of the
16346 values <literal>SELECT</literal>, <literal>INSERT</literal>,
16347 <literal>UPDATE</literal>, <literal>DELETE</literal>, <literal>TRUNCATE</>,
16348 <literal>REFERENCES</literal>, or <literal>TRIGGER</literal>. Optionally,
16349 <literal>WITH GRANT OPTION</> can be added to a privilege type to test
16350 whether the privilege is held with grant option. Also, multiple privilege
16351 types can be listed separated by commas, in which case the result will
16352 be <literal>true</> if any of the listed privileges is held.
16353 (Case of the privilege string is not significant, and extra whitespace
16354 is allowed between but not within privilege names.)
16357 SELECT has_table_privilege('myschema.mytable', 'select');
16358 SELECT has_table_privilege('joe', 'mytable', 'INSERT, SELECT WITH GRANT OPTION');
16363 <function>has_sequence_privilege</function> checks whether a user
16364 can access a sequence in a particular way. The possibilities for its
16365 arguments are analogous to <function>has_table_privilege</function>.
16366 The desired access privilege type must evaluate to one of
16367 <literal>USAGE</literal>,
16368 <literal>SELECT</literal>, or
16369 <literal>UPDATE</literal>.
16373 <function>has_any_column_privilege</function> checks whether a user can
16374 access any column of a table in a particular way.
16375 Its argument possibilities
16376 are analogous to <function>has_table_privilege</>,
16377 except that the desired access privilege type must evaluate to some
16379 <literal>SELECT</literal>,
16380 <literal>INSERT</literal>,
16381 <literal>UPDATE</literal>, or
16382 <literal>REFERENCES</literal>. Note that having any of these privileges
16383 at the table level implicitly grants it for each column of the table,
16384 so <function>has_any_column_privilege</function> will always return
16385 <literal>true</> if <function>has_table_privilege</> does for the same
16386 arguments. But <function>has_any_column_privilege</> also succeeds if
16387 there is a column-level grant of the privilege for at least one column.
16391 <function>has_column_privilege</function> checks whether a user
16392 can access a column in a particular way.
16393 Its argument possibilities
16394 are analogous to <function>has_table_privilege</function>,
16395 with the addition that the column can be specified either by name
16396 or attribute number.
16397 The desired access privilege type must evaluate to some combination of
16398 <literal>SELECT</literal>,
16399 <literal>INSERT</literal>,
16400 <literal>UPDATE</literal>, or
16401 <literal>REFERENCES</literal>. Note that having any of these privileges
16402 at the table level implicitly grants it for each column of the table.
16406 <function>has_database_privilege</function> checks whether a user
16407 can access a database in a particular way.
16408 Its argument possibilities
16409 are analogous to <function>has_table_privilege</function>.
16410 The desired access privilege type must evaluate to some combination of
16411 <literal>CREATE</literal>,
16412 <literal>CONNECT</literal>,
16413 <literal>TEMPORARY</literal>, or
16414 <literal>TEMP</literal> (which is equivalent to
16415 <literal>TEMPORARY</literal>).
16419 <function>has_function_privilege</function> checks whether a user
16420 can access a function in a particular way.
16421 Its argument possibilities
16422 are analogous to <function>has_table_privilege</function>.
16423 When specifying a function by a text string rather than by OID,
16424 the allowed input is the same as for the <type>regprocedure</> data type
16425 (see <xref linkend="datatype-oid">).
16426 The desired access privilege type must evaluate to
16427 <literal>EXECUTE</literal>.
16430 SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');
16435 <function>has_foreign_data_wrapper_privilege</function> checks whether a user
16436 can access a foreign-data wrapper in a particular way.
16437 Its argument possibilities
16438 are analogous to <function>has_table_privilege</function>.
16439 The desired access privilege type must evaluate to
16440 <literal>USAGE</literal>.
16444 <function>has_language_privilege</function> checks whether a user
16445 can access a procedural language in a particular way.
16446 Its argument possibilities
16447 are analogous to <function>has_table_privilege</function>.
16448 The desired access privilege type must evaluate to
16449 <literal>USAGE</literal>.
16453 <function>has_schema_privilege</function> checks whether a user
16454 can access a schema in a particular way.
16455 Its argument possibilities
16456 are analogous to <function>has_table_privilege</function>.
16457 The desired access privilege type must evaluate to some combination of
16458 <literal>CREATE</literal> or
16459 <literal>USAGE</literal>.
16463 <function>has_server_privilege</function> checks whether a user
16464 can access a foreign server in a particular way.
16465 Its argument possibilities
16466 are analogous to <function>has_table_privilege</function>.
16467 The desired access privilege type must evaluate to
16468 <literal>USAGE</literal>.
16472 <function>has_tablespace_privilege</function> checks whether a user
16473 can access a tablespace in a particular way.
16474 Its argument possibilities
16475 are analogous to <function>has_table_privilege</function>.
16476 The desired access privilege type must evaluate to
16477 <literal>CREATE</literal>.
16481 <function>has_type_privilege</function> checks whether a user
16482 can access a type in a particular way.
16483 Its argument possibilities
16484 are analogous to <function>has_table_privilege</function>.
16485 When specifying a type by a text string rather than by OID,
16486 the allowed input is the same as for the <type>regtype</> data type
16487 (see <xref linkend="datatype-oid">).
16488 The desired access privilege type must evaluate to
16489 <literal>USAGE</literal>.
16493 <function>pg_has_role</function> checks whether a user
16494 can access a role in a particular way.
16495 Its argument possibilities
16496 are analogous to <function>has_table_privilege</function>,
16497 except that <literal>public</> is not allowed as a user name.
16498 The desired access privilege type must evaluate to some combination of
16499 <literal>MEMBER</literal> or
16500 <literal>USAGE</literal>.
16501 <literal>MEMBER</literal> denotes direct or indirect membership in
16502 the role (that is, the right to do <command>SET ROLE</>), while
16503 <literal>USAGE</literal> denotes whether the privileges of the role
16504 are immediately available without doing <command>SET ROLE</>.
16508 <function>row_security_active</function> checks whether row level
16509 security is active for the specified table in the context of the
16510 <function>current_user</function> and environment. The table can
16511 be specified by name or by OID.
16515 <xref linkend="functions-info-schema-table"> shows functions that
16516 determine whether a certain object is <firstterm>visible</> in the
16517 current schema search path.
16518 For example, a table is said to be visible if its
16519 containing schema is in the search path and no table of the same
16520 name appears earlier in the search path. This is equivalent to the
16521 statement that the table can be referenced by name without explicit
16522 schema qualification. To list the names of all visible tables:
16524 SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
16529 <primary>search path</primary>
16530 <secondary>object visibility</secondary>
16533 <table id="functions-info-schema-table">
16534 <title>Schema Visibility Inquiry Functions</title>
16537 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16542 <entry><literal><function>pg_collation_is_visible(<parameter>collation_oid</parameter>)</function></literal>
16544 <entry><type>boolean</type></entry>
16545 <entry>is collation visible in search path</entry>
16548 <entry><literal><function>pg_conversion_is_visible(<parameter>conversion_oid</parameter>)</function></literal>
16550 <entry><type>boolean</type></entry>
16551 <entry>is conversion visible in search path</entry>
16554 <entry><literal><function>pg_function_is_visible(<parameter>function_oid</parameter>)</function></literal>
16556 <entry><type>boolean</type></entry>
16557 <entry>is function visible in search path</entry>
16560 <entry><literal><function>pg_opclass_is_visible(<parameter>opclass_oid</parameter>)</function></literal>
16562 <entry><type>boolean</type></entry>
16563 <entry>is operator class visible in search path</entry>
16566 <entry><literal><function>pg_operator_is_visible(<parameter>operator_oid</parameter>)</function></literal>
16568 <entry><type>boolean</type></entry>
16569 <entry>is operator visible in search path</entry>
16572 <entry><literal><function>pg_opfamily_is_visible(<parameter>opclass_oid</parameter>)</function></literal>
16574 <entry><type>boolean</type></entry>
16575 <entry>is operator family visible in search path</entry>
16578 <entry><literal><function>pg_table_is_visible(<parameter>table_oid</parameter>)</function></literal>
16580 <entry><type>boolean</type></entry>
16581 <entry>is table visible in search path</entry>
16584 <entry><literal><function>pg_ts_config_is_visible(<parameter>config_oid</parameter>)</function></literal>
16586 <entry><type>boolean</type></entry>
16587 <entry>is text search configuration visible in search path</entry>
16590 <entry><literal><function>pg_ts_dict_is_visible(<parameter>dict_oid</parameter>)</function></literal>
16592 <entry><type>boolean</type></entry>
16593 <entry>is text search dictionary visible in search path</entry>
16596 <entry><literal><function>pg_ts_parser_is_visible(<parameter>parser_oid</parameter>)</function></literal>
16598 <entry><type>boolean</type></entry>
16599 <entry>is text search parser visible in search path</entry>
16602 <entry><literal><function>pg_ts_template_is_visible(<parameter>template_oid</parameter>)</function></literal>
16604 <entry><type>boolean</type></entry>
16605 <entry>is text search template visible in search path</entry>
16608 <entry><literal><function>pg_type_is_visible(<parameter>type_oid</parameter>)</function></literal>
16610 <entry><type>boolean</type></entry>
16611 <entry>is type (or domain) visible in search path</entry>
16618 <primary>pg_collation_is_visible</primary>
16621 <primary>pg_conversion_is_visible</primary>
16624 <primary>pg_function_is_visible</primary>
16627 <primary>pg_opclass_is_visible</primary>
16630 <primary>pg_operator_is_visible</primary>
16633 <primary>pg_opfamily_is_visible</primary>
16636 <primary>pg_table_is_visible</primary>
16639 <primary>pg_ts_config_is_visible</primary>
16642 <primary>pg_ts_dict_is_visible</primary>
16645 <primary>pg_ts_parser_is_visible</primary>
16648 <primary>pg_ts_template_is_visible</primary>
16651 <primary>pg_type_is_visible</primary>
16655 Each function performs the visibility check for one type of database
16656 object. Note that <function>pg_table_is_visible</function> can also be used
16657 with views, materialized views, indexes, sequences and foreign tables;
16658 <function>pg_type_is_visible</function> can also be used with domains.
16659 For functions and operators, an object in
16660 the search path is visible if there is no object of the same name
16661 <emphasis>and argument data type(s)</> earlier in the path. For operator
16662 classes, both name and associated index access method are considered.
16666 All these functions require object OIDs to identify the object to be
16667 checked. If you want to test an object by name, it is convenient to use
16668 the OID alias types (<type>regclass</>, <type>regtype</>,
16669 <type>regprocedure</>, <type>regoperator</>, <type>regconfig</>,
16670 or <type>regdictionary</>),
16673 SELECT pg_type_is_visible('myschema.widget'::regtype);
16675 Note that it would not make much sense to test a non-schema-qualified
16676 type name in this way — if the name can be recognized at all, it must be visible.
16680 <primary>format_type</primary>
16684 <primary>pg_get_constraintdef</primary>
16688 <primary>pg_get_expr</primary>
16692 <primary>pg_get_functiondef</primary>
16696 <primary>pg_get_function_arguments</primary>
16700 <primary>pg_get_function_identity_arguments</primary>
16704 <primary>pg_get_function_result</primary>
16708 <primary>pg_get_indexdef</primary>
16712 <primary>pg_get_keywords</primary>
16716 <primary>pg_get_ruledef</primary>
16720 <primary>pg_get_serial_sequence</primary>
16724 <primary>pg_get_triggerdef</primary>
16728 <primary>pg_get_userbyid</primary>
16732 <primary>pg_get_viewdef</primary>
16736 <primary>pg_index_column_has_property</primary>
16740 <primary>pg_index_has_property</primary>
16744 <primary>pg_indexam_has_property</primary>
16748 <primary>pg_options_to_table</primary>
16752 <primary>pg_tablespace_databases</primary>
16756 <primary>pg_tablespace_location</primary>
16760 <primary>pg_typeof</primary>
16764 <primary>collation for</primary>
16768 <primary>to_regclass</primary>
16772 <primary>to_regproc</primary>
16776 <primary>to_regprocedure</primary>
16780 <primary>to_regoper</primary>
16784 <primary>to_regoperator</primary>
16788 <primary>to_regtype</primary>
16792 <primary>to_regnamespace</primary>
16796 <primary>to_regrole</primary>
16800 <xref linkend="functions-info-catalog-table"> lists functions that
16801 extract information from the system catalogs.
16804 <table id="functions-info-catalog-table">
16805 <title>System Catalog Information Functions</title>
16808 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16813 <entry><literal><function>format_type(<parameter>type_oid</parameter>, <parameter>typemod</>)</function></literal></entry>
16814 <entry><type>text</type></entry>
16815 <entry>get SQL name of a data type</entry>
16818 <entry><literal><function>pg_get_constraintdef(<parameter>constraint_oid</parameter>)</function></literal></entry>
16819 <entry><type>text</type></entry>
16820 <entry>get definition of a constraint</entry>
16823 <entry><literal><function>pg_get_constraintdef(<parameter>constraint_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16824 <entry><type>text</type></entry>
16825 <entry>get definition of a constraint</entry>
16828 <entry><literal><function>pg_get_expr(<parameter>pg_node_tree</parameter>, <parameter>relation_oid</>)</function></literal></entry>
16829 <entry><type>text</type></entry>
16830 <entry>decompile internal form of an expression, assuming that any Vars
16831 in it refer to the relation indicated by the second parameter</entry>
16834 <entry><literal><function>pg_get_expr(<parameter>pg_node_tree</parameter>, <parameter>relation_oid</>, <parameter>pretty_bool</>)</function></literal></entry>
16835 <entry><type>text</type></entry>
16836 <entry>decompile internal form of an expression, assuming that any Vars
16837 in it refer to the relation indicated by the second parameter</entry>
16840 <entry><literal><function>pg_get_functiondef(<parameter>func_oid</parameter>)</function></literal></entry>
16841 <entry><type>text</type></entry>
16842 <entry>get definition of a function</entry>
16845 <entry><literal><function>pg_get_function_arguments(<parameter>func_oid</parameter>)</function></literal></entry>
16846 <entry><type>text</type></entry>
16847 <entry>get argument list of function's definition (with default values)</entry>
16850 <entry><literal><function>pg_get_function_identity_arguments(<parameter>func_oid</parameter>)</function></literal></entry>
16851 <entry><type>text</type></entry>
16852 <entry>get argument list to identify a function (without default values)</entry>
16855 <entry><literal><function>pg_get_function_result(<parameter>func_oid</parameter>)</function></literal></entry>
16856 <entry><type>text</type></entry>
16857 <entry>get <literal>RETURNS</> clause for function</entry>
16860 <entry><literal><function>pg_get_indexdef(<parameter>index_oid</parameter>)</function></literal></entry>
16861 <entry><type>text</type></entry>
16862 <entry>get <command>CREATE INDEX</> command for index</entry>
16865 <entry><literal><function>pg_get_indexdef(<parameter>index_oid</parameter>, <parameter>column_no</>, <parameter>pretty_bool</>)</function></literal></entry>
16866 <entry><type>text</type></entry>
16867 <entry>get <command>CREATE INDEX</> command for index,
16868 or definition of just one index column when
16869 <parameter>column_no</> is not zero</entry>
16872 <entry><literal><function>pg_get_keywords()</function></literal></entry>
16873 <entry><type>setof record</type></entry>
16874 <entry>get list of SQL keywords and their categories</entry>
16877 <entry><literal><function>pg_get_ruledef(<parameter>rule_oid</parameter>)</function></literal></entry>
16878 <entry><type>text</type></entry>
16879 <entry>get <command>CREATE RULE</> command for rule</entry>
16882 <entry><literal><function>pg_get_ruledef(<parameter>rule_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16883 <entry><type>text</type></entry>
16884 <entry>get <command>CREATE RULE</> command for rule</entry>
16887 <entry><literal><function>pg_get_serial_sequence(<parameter>table_name</parameter>, <parameter>column_name</parameter>)</function></literal></entry>
16888 <entry><type>text</type></entry>
16889 <entry>get name of the sequence that a <type>serial</type>, <type>smallserial</type> or <type>bigserial</type> column
16893 <entry><function>pg_get_triggerdef</function>(<parameter>trigger_oid</parameter>)</entry>
16894 <entry><type>text</type></entry>
16895 <entry>get <command>CREATE [ CONSTRAINT ] TRIGGER</> command for trigger</entry>
16898 <entry><function>pg_get_triggerdef</function>(<parameter>trigger_oid</parameter>, <parameter>pretty_bool</>)</entry>
16899 <entry><type>text</type></entry>
16900 <entry>get <command>CREATE [ CONSTRAINT ] TRIGGER</> command for trigger</entry>
16903 <entry><literal><function>pg_get_userbyid(<parameter>role_oid</parameter>)</function></literal></entry>
16904 <entry><type>name</type></entry>
16905 <entry>get role name with given OID</entry>
16908 <entry><literal><function>pg_get_viewdef(<parameter>view_name</parameter>)</function></literal></entry>
16909 <entry><type>text</type></entry>
16910 <entry>get underlying <command>SELECT</command> command for view or materialized view (<emphasis>deprecated</emphasis>)</entry>
16913 <entry><literal><function>pg_get_viewdef(<parameter>view_name</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16914 <entry><type>text</type></entry>
16915 <entry>get underlying <command>SELECT</command> command for view or materialized view (<emphasis>deprecated</emphasis>)</entry>
16918 <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>)</function></literal></entry>
16919 <entry><type>text</type></entry>
16920 <entry>get underlying <command>SELECT</command> command for view or materialized view</entry>
16923 <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16924 <entry><type>text</type></entry>
16925 <entry>get underlying <command>SELECT</command> command for view or materialized view</entry>
16928 <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>, <parameter>wrap_column_int</>)</function></literal></entry>
16929 <entry><type>text</type></entry>
16930 <entry>get underlying <command>SELECT</command> command for view or
16931 materialized view; lines with fields are wrapped to specified
16932 number of columns, pretty-printing is implied</entry>
16935 <entry><literal><function>pg_index_column_has_property(<parameter>index_oid</parameter>, <parameter>column_no</>, <parameter>prop_name</>)</function></literal></entry>
16936 <entry><type>boolean</type></entry>
16937 <entry>test whether an index column has a specified property</entry>
16940 <entry><literal><function>pg_index_has_property(<parameter>index_oid</parameter>, <parameter>prop_name</>)</function></literal></entry>
16941 <entry><type>boolean</type></entry>
16942 <entry>test whether an index has a specified property</entry>
16945 <entry><literal><function>pg_indexam_has_property(<parameter>am_oid</parameter>, <parameter>prop_name</>)</function></literal></entry>
16946 <entry><type>boolean</type></entry>
16947 <entry>test whether an index access method has a specified property</entry>
16950 <entry><literal><function>pg_options_to_table(<parameter>reloptions</parameter>)</function></literal></entry>
16951 <entry><type>setof record</type></entry>
16952 <entry>get the set of storage option name/value pairs</entry>
16955 <entry><literal><function>pg_tablespace_databases(<parameter>tablespace_oid</parameter>)</function></literal></entry>
16956 <entry><type>setof oid</type></entry>
16957 <entry>get the set of database OIDs that have objects in the tablespace</entry>
16960 <entry><literal><function>pg_tablespace_location(<parameter>tablespace_oid</parameter>)</function></literal></entry>
16961 <entry><type>text</type></entry>
16962 <entry>get the path in the file system that this tablespace is located in</entry>
16965 <entry><literal><function>pg_typeof(<parameter>any</parameter>)</function></literal></entry>
16966 <entry><type>regtype</type></entry>
16967 <entry>get the data type of any value</entry>
16970 <entry><literal><function>collation for (<parameter>any</parameter>)</function></literal></entry>
16971 <entry><type>text</type></entry>
16972 <entry>get the collation of the argument</entry>
16975 <entry><literal><function>to_regclass(<parameter>rel_name</parameter>)</function></literal></entry>
16976 <entry><type>regclass</type></entry>
16977 <entry>get the OID of the named relation</entry>
16980 <entry><literal><function>to_regproc(<parameter>func_name</parameter>)</function></literal></entry>
16981 <entry><type>regproc</type></entry>
16982 <entry>get the OID of the named function</entry>
16985 <entry><literal><function>to_regprocedure(<parameter>func_name</parameter>)</function></literal></entry>
16986 <entry><type>regprocedure</type></entry>
16987 <entry>get the OID of the named function</entry>
16990 <entry><literal><function>to_regoper(<parameter>operator_name</parameter>)</function></literal></entry>
16991 <entry><type>regoper</type></entry>
16992 <entry>get the OID of the named operator</entry>
16995 <entry><literal><function>to_regoperator(<parameter>operator_name</parameter>)</function></literal></entry>
16996 <entry><type>regoperator</type></entry>
16997 <entry>get the OID of the named operator</entry>
17000 <entry><literal><function>to_regtype(<parameter>type_name</parameter>)</function></literal></entry>
17001 <entry><type>regtype</type></entry>
17002 <entry>get the OID of the named type</entry>
17005 <entry><literal><function>to_regnamespace(<parameter>schema_name</parameter>)</function></literal></entry>
17006 <entry><type>regnamespace</type></entry>
17007 <entry>get the OID of the named schema</entry>
17010 <entry><literal><function>to_regrole(<parameter>role_name</parameter>)</function></literal></entry>
17011 <entry><type>regrole</type></entry>
17012 <entry>get the OID of the named role</entry>
17019 <function>format_type</function> returns the SQL name of a data type that
17020 is identified by its type OID and possibly a type modifier. Pass NULL
17021 for the type modifier if no specific modifier is known.
17025 <function>pg_get_keywords</function> returns a set of records describing
17026 the SQL keywords recognized by the server. The <structfield>word</> column
17027 contains the keyword. The <structfield>catcode</> column contains a
17028 category code: <literal>U</> for unreserved, <literal>C</> for column name,
17029 <literal>T</> for type or function name, or <literal>R</> for reserved.
17030 The <structfield>catdesc</> column contains a possibly-localized string
17031 describing the category.
17035 <function>pg_get_constraintdef</function>,
17036 <function>pg_get_indexdef</function>, <function>pg_get_ruledef</function>,
17037 and <function>pg_get_triggerdef</function>, respectively reconstruct the
17038 creating command for a constraint, index, rule, or trigger. (Note that this
17039 is a decompiled reconstruction, not the original text of the command.)
17040 <function>pg_get_expr</function> decompiles the internal form of an
17041 individual expression, such as the default value for a column. It can be
17042 useful when examining the contents of system catalogs. If the expression
17043 might contain Vars, specify the OID of the relation they refer to as the
17044 second parameter; if no Vars are expected, zero is sufficient.
17045 <function>pg_get_viewdef</function> reconstructs the <command>SELECT</>
17046 query that defines a view. Most of these functions come in two variants,
17047 one of which can optionally <quote>pretty-print</> the result. The
17048 pretty-printed format is more readable, but the default format is more
17049 likely to be interpreted the same way by future versions of
17050 <productname>PostgreSQL</>; avoid using pretty-printed output for dump
17051 purposes. Passing <literal>false</> for the pretty-print parameter yields
17052 the same result as the variant that does not have the parameter at all.
17056 <function>pg_get_functiondef</> returns a complete
17057 <command>CREATE OR REPLACE FUNCTION</> statement for a function.
17058 <function>pg_get_function_arguments</function> returns the argument list
17059 of a function, in the form it would need to appear in within
17060 <command>CREATE FUNCTION</>.
17061 <function>pg_get_function_result</function> similarly returns the
17062 appropriate <literal>RETURNS</> clause for the function.
17063 <function>pg_get_function_identity_arguments</function> returns the
17064 argument list necessary to identify a function, in the form it
17065 would need to appear in within <command>ALTER FUNCTION</>, for
17066 instance. This form omits default values.
17070 <function>pg_get_serial_sequence</function> returns the name of the
17071 sequence associated with a column, or NULL if no sequence is associated
17072 with the column. The first input parameter is a table name with
17073 optional schema, and the second parameter is a column name. Because
17074 the first parameter is potentially a schema and table, it is not treated
17075 as a double-quoted identifier, meaning it is lower cased by default,
17076 while the second parameter, being just a column name, is treated as
17077 double-quoted and has its case preserved. The function returns a value
17078 suitably formatted for passing to sequence functions (see <xref
17079 linkend="functions-sequence">). This association can be modified or
17080 removed with <command>ALTER SEQUENCE OWNED BY</>. (The function
17081 probably should have been called
17082 <function>pg_get_owned_sequence</function>; its current name reflects the fact
17083 that it's typically used with <type>serial</> or <type>bigserial</>
17088 <function>pg_get_userbyid</function> extracts a role's name given
17093 <function>pg_index_column_has_property</function>,
17094 <function>pg_index_has_property</function>, and
17095 <function>pg_indexam_has_property</function> return whether the
17096 specified index column, index, or index access method possesses the named
17097 property. <literal>NULL</literal> is returned if the property name is not
17098 known or does not apply to the particular object, or if the OID or column
17099 number does not identify a valid object. Refer to
17100 <xref linkend="functions-info-index-column-props"> for column properties,
17101 <xref linkend="functions-info-index-props"> for index properties, and
17102 <xref linkend="functions-info-indexam-props"> for access method properties.
17103 (Note that extension access methods can define additional property names
17104 for their indexes.)
17107 <table id="functions-info-index-column-props">
17108 <title>Index Column Properties</title>
17111 <row><entry>Name</entry><entry>Description</entry></row>
17115 <entry><literal>asc</literal></entry>
17116 <entry>Does the column sort in ascending order on a forward scan?
17120 <entry><literal>desc</literal></entry>
17121 <entry>Does the column sort in descending order on a forward scan?
17125 <entry><literal>nulls_first</literal></entry>
17126 <entry>Does the column sort with nulls first on a forward scan?
17130 <entry><literal>nulls_last</literal></entry>
17131 <entry>Does the column sort with nulls last on a forward scan?
17135 <entry><literal>orderable</literal></entry>
17136 <entry>Does the column possess any defined sort ordering?
17140 <entry><literal>distance_orderable</literal></entry>
17141 <entry>Can the column be scanned in order by a <quote>distance</>
17142 operator, for example <literal>ORDER BY col <-> constant</> ?
17146 <entry><literal>returnable</literal></entry>
17147 <entry>Can the column value be returned by an index-only scan?
17151 <entry><literal>search_array</literal></entry>
17152 <entry>Does the column natively support <literal>col = ANY(array)</>
17157 <entry><literal>search_nulls</literal></entry>
17158 <entry>Does the column support <literal>IS NULL</> and
17159 <literal>IS NOT NULL</> searches?
17166 <table id="functions-info-index-props">
17167 <title>Index Properties</title>
17170 <row><entry>Name</entry><entry>Description</entry></row>
17174 <entry><literal>clusterable</literal></entry>
17175 <entry>Can the index be used in a <literal>CLUSTER</> command?
17179 <entry><literal>index_scan</literal></entry>
17180 <entry>Does the index support plain (non-bitmap) scans?
17184 <entry><literal>bitmap_scan</literal></entry>
17185 <entry>Does the index support bitmap scans?
17189 <entry><literal>backward_scan</literal></entry>
17190 <entry>Can the index be scanned backwards?
17197 <table id="functions-info-indexam-props">
17198 <title>Index Access Method Properties</title>
17201 <row><entry>Name</entry><entry>Description</entry></row>
17205 <entry><literal>can_order</literal></entry>
17206 <entry>Does the access method support <literal>ASC</>,
17207 <literal>DESC</> and related keywords in
17208 <literal>CREATE INDEX</>?
17212 <entry><literal>can_unique</literal></entry>
17213 <entry>Does the access method support unique indexes?
17217 <entry><literal>can_multi_col</literal></entry>
17218 <entry>Does the access method support indexes with multiple columns?
17222 <entry><literal>can_exclude</literal></entry>
17223 <entry>Does the access method support exclusion constraints?
17231 <function>pg_options_to_table</function> returns the set of storage
17232 option name/value pairs
17233 (<replaceable>option_name</>/<replaceable>option_value</>) when passed
17234 <structname>pg_class</>.<structfield>reloptions</> or
17235 <structname>pg_attribute</>.<structfield>attoptions</>.
17239 <function>pg_tablespace_databases</function> allows a tablespace to be
17240 examined. It returns the set of OIDs of databases that have objects stored
17241 in the tablespace. If this function returns any rows, the tablespace is not
17242 empty and cannot be dropped. To display the specific objects populating the
17243 tablespace, you will need to connect to the databases identified by
17244 <function>pg_tablespace_databases</function> and query their
17245 <structname>pg_class</> catalogs.
17249 <function>pg_typeof</function> returns the OID of the data type of the
17250 value that is passed to it. This can be helpful for troubleshooting or
17251 dynamically constructing SQL queries. The function is declared as
17252 returning <type>regtype</>, which is an OID alias type (see
17253 <xref linkend="datatype-oid">); this means that it is the same as an
17254 OID for comparison purposes but displays as a type name. For example:
17256 SELECT pg_typeof(33);
17263 SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
17272 The expression <literal>collation for</literal> returns the collation of the
17273 value that is passed to it. Example:
17275 SELECT collation for (description) FROM pg_description LIMIT 1;
17281 SELECT collation for ('foo' COLLATE "de_DE");
17287 The value might be quoted and schema-qualified. If no collation is derived
17288 for the argument expression, then a null value is returned. If the argument
17289 is not of a collatable data type, then an error is raised.
17293 The <function>to_regclass</function>, <function>to_regproc</function>,
17294 <function>to_regprocedure</function>, <function>to_regoper</function>,
17295 <function>to_regoperator</function>, <function>to_regtype</function>,
17296 <function>to_regnamespace</function>, and <function>to_regrole</function>
17297 functions translate relation, function, operator, type, schema, and role
17298 names (given as <type>text</>) to objects of
17299 type <type>regclass</>, <type>regproc</>, <type>regprocedure</type>,
17300 <type>regoper</>, <type>regoperator</type>, <type>regtype</>,
17301 <type>regnamespace</>, and <type>regrole</>
17302 respectively. These functions differ from a cast from
17303 text in that they don't accept a numeric OID, and that they return null
17304 rather than throwing an error if the name is not found (or, for
17305 <function>to_regproc</function> and <function>to_regoper</function>, if
17306 the given name matches multiple objects).
17310 <primary>pg_describe_object</primary>
17314 <primary>pg_identify_object</primary>
17318 <primary>pg_identify_object_as_address</primary>
17322 <primary>pg_get_object_address</primary>
17326 <xref linkend="functions-info-object-table"> lists functions related to
17327 database object identification and addressing.
17330 <table id="functions-info-object-table">
17331 <title>Object Information and Addressing Functions</title>
17334 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
17339 <entry><literal><function>pg_describe_object(<parameter>catalog_id</parameter>, <parameter>object_id</parameter>, <parameter>object_sub_id</parameter>)</function></literal></entry>
17340 <entry><type>text</type></entry>
17341 <entry>get description of a database object</entry>
17344 <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>
17345 <entry><parameter>type</> <type>text</>, <parameter>schema</> <type>text</>, <parameter>name</> <type>text</>, <parameter>identity</> <type>text</></entry>
17346 <entry>get identity of a database object</entry>
17349 <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>
17350 <entry><parameter>type</> <type>text</>, <parameter>name</> <type>text[]</>, <parameter>args</> <type>text[]</></entry>
17351 <entry>get external representation of a database object's address</entry>
17354 <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>
17355 <entry><parameter>catalog_id</> <type>oid</>, <parameter>object_id</> <type>oid</>, <parameter>object_sub_id</> <type>int32</></entry>
17356 <entry>get address of a database object, from its external representation</entry>
17363 <function>pg_describe_object</function> returns a textual description of a database
17364 object specified by catalog OID, object OID and a (possibly zero) sub-object ID.
17365 This description is intended to be human-readable, and might be translated,
17366 depending on server configuration.
17367 This is useful to determine the identity of an object as stored in the
17368 <structname>pg_depend</structname> catalog.
17372 <function>pg_identify_object</function> returns a row containing enough information
17373 to uniquely identify the database object specified by catalog OID, object OID and a
17374 (possibly zero) sub-object ID. This information is intended to be machine-readable,
17375 and is never translated.
17376 <parameter>type</> identifies the type of database object;
17377 <parameter>schema</> is the schema name that the object belongs in, or
17378 <literal>NULL</> for object types that do not belong to schemas;
17379 <parameter>name</> is the name of the object, quoted if necessary, only
17380 present if it can be used (alongside schema name, if pertinent) as a unique
17381 identifier of the object, otherwise <literal>NULL</>;
17382 <parameter>identity</> is the complete object identity, with the precise format
17383 depending on object type, and each part within the format being
17384 schema-qualified and quoted as necessary.
17388 <function>pg_identify_object_as_address</function> returns a row containing
17389 enough information to uniquely identify the database object specified by
17390 catalog OID, object OID and a (possibly zero) sub-object ID. The returned
17391 information is independent of the current server, that is, it could be used
17392 to identify an identically named object in another server.
17393 <parameter>type</> identifies the type of database object;
17394 <parameter>name</> and <parameter>args</> are text arrays that together
17395 form a reference to the object. These three columns can be passed to
17396 <function>pg_get_object_address</> to obtain the internal address
17398 This function is the inverse of <function>pg_get_object_address</function>.
17402 <function>pg_get_object_address</function> returns a row containing enough
17403 information to uniquely identify the database object specified by its
17404 type and object name and argument arrays. The returned values are the
17405 ones that would be used in system catalogs such as <structname>pg_depend</>
17406 and can be passed to other system functions such as
17407 <function>pg_identify_object</> or <function>pg_describe_object</>.
17408 <parameter>catalog_id</> is the OID of the system catalog containing the
17410 <parameter>object_id</> is the OID of the object itself, and
17411 <parameter>object_sub_id</> is the object sub-ID, or zero if none.
17412 This function is the inverse of <function>pg_identify_object_as_address</function>.
17416 <primary>col_description</primary>
17420 <primary>obj_description</primary>
17424 <primary>shobj_description</primary>
17428 <primary>comment</primary>
17429 <secondary sortas="database objects">about database objects</secondary>
17433 The functions shown in <xref linkend="functions-info-comment-table">
17434 extract comments previously stored with the <xref linkend="sql-comment">
17435 command. A null value is returned if no
17436 comment could be found for the specified parameters.
17439 <table id="functions-info-comment-table">
17440 <title>Comment Information Functions</title>
17443 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
17448 <entry><literal><function>col_description(<parameter>table_oid</parameter>, <parameter>column_number</parameter>)</function></literal></entry>
17449 <entry><type>text</type></entry>
17450 <entry>get comment for a table column</entry>
17453 <entry><literal><function>obj_description(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</function></literal></entry>
17454 <entry><type>text</type></entry>
17455 <entry>get comment for a database object</entry>
17458 <entry><literal><function>obj_description(<parameter>object_oid</parameter>)</function></literal></entry>
17459 <entry><type>text</type></entry>
17460 <entry>get comment for a database object (<emphasis>deprecated</emphasis>)</entry>
17463 <entry><literal><function>shobj_description(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</function></literal></entry>
17464 <entry><type>text</type></entry>
17465 <entry>get comment for a shared database object</entry>
17472 <function>col_description</function> returns the comment for a table
17473 column, which is specified by the OID of its table and its column number.
17474 (<function>obj_description</function> cannot be used for table columns
17475 since columns do not have OIDs of their own.)
17479 The two-parameter form of <function>obj_description</function> returns the
17480 comment for a database object specified by its OID and the name of the
17481 containing system catalog. For example,
17482 <literal>obj_description(123456,'pg_class')</literal>
17483 would retrieve the comment for the table with OID 123456.
17484 The one-parameter form of <function>obj_description</function> requires only
17485 the object OID. It is deprecated since there is no guarantee that
17486 OIDs are unique across different system catalogs; therefore, the wrong
17487 comment might be returned.
17491 <function>shobj_description</function> is used just like
17492 <function>obj_description</function> except it is used for retrieving
17493 comments on shared objects. Some system catalogs are global to all
17494 databases within each cluster, and the descriptions for objects in them
17495 are stored globally as well.
17499 <primary>txid_current</primary>
17503 <primary>txid_current_if_assigned</primary>
17507 <primary>txid_current_snapshot</primary>
17511 <primary>txid_snapshot_xip</primary>
17515 <primary>txid_snapshot_xmax</primary>
17519 <primary>txid_snapshot_xmin</primary>
17523 <primary>txid_visible_in_snapshot</primary>
17527 The functions shown in <xref linkend="functions-txid-snapshot">
17528 provide server transaction information in an exportable form. The main
17529 use of these functions is to determine which transactions were committed
17530 between two snapshots.
17533 <table id="functions-txid-snapshot">
17534 <title>Transaction IDs and Snapshots</title>
17537 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
17542 <entry><literal><function>txid_current()</function></literal></entry>
17543 <entry><type>bigint</type></entry>
17544 <entry>get current transaction ID, assigning a new one if the current transaction does not have one</entry>
17547 <entry><literal><function>txid_current_if_assigned()</function></literal></entry>
17548 <entry><type>bigint</type></entry>
17549 <entry>same as <function>txid_current()</function> but returns null instead of assigning an xid if none is already assigned</entry>
17552 <entry><literal><function>txid_current_snapshot()</function></literal></entry>
17553 <entry><type>txid_snapshot</type></entry>
17554 <entry>get current snapshot</entry>
17557 <entry><literal><function>txid_snapshot_xip(<parameter>txid_snapshot</parameter>)</function></literal></entry>
17558 <entry><type>setof bigint</type></entry>
17559 <entry>get in-progress transaction IDs in snapshot</entry>
17562 <entry><literal><function>txid_snapshot_xmax(<parameter>txid_snapshot</parameter>)</function></literal></entry>
17563 <entry><type>bigint</type></entry>
17564 <entry>get <literal>xmax</literal> of snapshot</entry>
17567 <entry><literal><function>txid_snapshot_xmin(<parameter>txid_snapshot</parameter>)</function></literal></entry>
17568 <entry><type>bigint</type></entry>
17569 <entry>get <literal>xmin</literal> of snapshot</entry>
17572 <entry><literal><function>txid_visible_in_snapshot(<parameter>bigint</parameter>, <parameter>txid_snapshot</parameter>)</function></literal></entry>
17573 <entry><type>boolean</type></entry>
17574 <entry>is transaction ID visible in snapshot? (do not use with subtransaction ids)</entry>
17581 The internal transaction ID type (<type>xid</>) is 32 bits wide and
17582 wraps around every 4 billion transactions. However, these functions
17583 export a 64-bit format that is extended with an <quote>epoch</> counter
17584 so it will not wrap around during the life of an installation.
17585 The data type used by these functions, <type>txid_snapshot</type>,
17586 stores information about transaction ID
17587 visibility at a particular moment in time. Its components are
17588 described in <xref linkend="functions-txid-snapshot-parts">.
17591 <table id="functions-txid-snapshot-parts">
17592 <title>Snapshot Components</title>
17596 <entry>Name</entry>
17597 <entry>Description</entry>
17604 <entry><type>xmin</type></entry>
17606 Earliest transaction ID (txid) that is still active. All earlier
17607 transactions will either be committed and visible, or rolled
17613 <entry><type>xmax</type></entry>
17615 First as-yet-unassigned txid. All txids greater than or equal to this
17616 are not yet started as of the time of the snapshot, and thus invisible.
17621 <entry><type>xip_list</type></entry>
17623 Active txids at the time of the snapshot. The list
17624 includes only those active txids between <literal>xmin</>
17625 and <literal>xmax</>; there might be active txids higher
17626 than <literal>xmax</>. A txid that is <literal>xmin <= txid <
17627 xmax</literal> and not in this list was already completed
17628 at the time of the snapshot, and thus either visible or
17629 dead according to its commit status. The list does not
17630 include txids of subtransactions.
17639 <type>txid_snapshot</>'s textual representation is
17640 <literal><replaceable>xmin</>:<replaceable>xmax</>:<replaceable>xip_list</></literal>.
17641 For example <literal>10:20:10,14,15</literal> means
17642 <literal>xmin=10, xmax=20, xip_list=10, 14, 15</literal>.
17646 The functions shown in <xref linkend="functions-commit-timestamp">
17647 provide information about transactions that have been already committed.
17648 These functions mainly provide information about when the transactions
17649 were committed. They only provide useful data when
17650 <xref linkend="guc-track-commit-timestamp"> configuration option is enabled
17651 and only for transactions that were committed after it was enabled.
17654 <table id="functions-commit-timestamp">
17655 <title>Committed transaction information</title>
17658 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
17664 <indexterm><primary>pg_xact_commit_timestamp</primary></indexterm>
17665 <literal><function>pg_xact_commit_timestamp(<parameter>xid</parameter>)</function></literal>
17667 <entry><type>timestamp with time zone</type></entry>
17668 <entry>get commit timestamp of a transaction</entry>
17673 <indexterm><primary>pg_last_committed_xact</primary></indexterm>
17674 <literal><function>pg_last_committed_xact()</function></literal>
17676 <entry><parameter>xid</> <type>xid</>, <parameter>timestamp</> <type>timestamp with time zone</></entry>
17677 <entry>get transaction ID and commit timestamp of latest committed transaction</entry>
17684 The functions shown in <xref linkend="functions-controldata">
17685 print information initialized during <command>initdb</>, such
17686 as the catalog version. They also show information about write-ahead
17687 logging and checkpoint processing. This information is cluster-wide,
17688 and not specific to any one database. They provide most of the same
17689 information, from the same source, as
17690 <xref linkend="APP-PGCONTROLDATA">, although in a form better suited
17691 to <acronym>SQL</acronym> functions.
17694 <table id="functions-controldata">
17695 <title>Control Data Functions</title>
17698 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
17704 <indexterm><primary>pg_control_checkpoint</primary></indexterm>
17705 <literal><function>pg_control_checkpoint()</function></literal>
17707 <entry><type>record</type></entry>
17709 Returns information about current checkpoint state.
17715 <indexterm><primary>pg_control_system</primary></indexterm>
17716 <literal><function>pg_control_system()</function></literal>
17718 <entry><type>record</type></entry>
17720 Returns information about current control file state.
17726 <indexterm><primary>pg_control_init</primary></indexterm>
17727 <literal><function>pg_control_init()</function></literal>
17729 <entry><type>record</type></entry>
17731 Returns information about cluster initialization state.
17737 <indexterm><primary>pg_control_recovery</primary></indexterm>
17738 <literal><function>pg_control_recovery()</function></literal>
17740 <entry><type>record</type></entry>
17742 Returns information about recovery state.
17751 <function>pg_control_checkpoint</> returns a record, shown in
17752 <xref linkend="functions-pg-control-checkpoint">
17755 <table id="functions-pg-control-checkpoint">
17756 <title><function>pg_control_checkpoint</> Columns</title>
17760 <entry>Column Name</entry>
17761 <entry>Data Type</entry>
17768 <entry><literal>checkpoint_location</literal></entry>
17769 <entry><type>pg_lsn</type></entry>
17773 <entry><literal>prior_location</literal></entry>
17774 <entry><type>pg_lsn</type></entry>
17778 <entry><literal>redo_location</literal></entry>
17779 <entry><type>pg_lsn</type></entry>
17783 <entry><literal>redo_wal_file</literal></entry>
17784 <entry><type>text</type></entry>
17788 <entry><literal>timeline_id</literal></entry>
17789 <entry><type>integer</type></entry>
17793 <entry><literal>prev_timeline_id</literal></entry>
17794 <entry><type>integer</type></entry>
17798 <entry><literal>full_page_writes</literal></entry>
17799 <entry><type>boolean</type></entry>
17803 <entry><literal>next_xid</literal></entry>
17804 <entry><type>text</type></entry>
17808 <entry><literal>next_oid</literal></entry>
17809 <entry><type>oid</type></entry>
17813 <entry><literal>next_multixact_id</literal></entry>
17814 <entry><type>xid</type></entry>
17818 <entry><literal>next_multi_offset</literal></entry>
17819 <entry><type>xid</type></entry>
17823 <entry><literal>oldest_xid</literal></entry>
17824 <entry><type>xid</type></entry>
17828 <entry><literal>oldest_xid_dbid</literal></entry>
17829 <entry><type>oid</type></entry>
17833 <entry><literal>oldest_active_xid</literal></entry>
17834 <entry><type>xid</type></entry>
17838 <entry><literal>oldest_multi_xid</literal></entry>
17839 <entry><type>xid</type></entry>
17843 <entry><literal>oldest_multi_dbid</literal></entry>
17844 <entry><type>oid</type></entry>
17848 <entry><literal>oldest_commit_ts_xid</literal></entry>
17849 <entry><type>xid</type></entry>
17853 <entry><literal>newest_commit_ts_xid</literal></entry>
17854 <entry><type>xid</type></entry>
17858 <entry><literal>checkpoint_time</literal></entry>
17859 <entry><type>timestamp with time zone</type></entry>
17867 <function>pg_control_system</> returns a record, shown in
17868 <xref linkend="functions-pg-control-system">
17871 <table id="functions-pg-control-system">
17872 <title><function>pg_control_system</> Columns</title>
17876 <entry>Column Name</entry>
17877 <entry>Data Type</entry>
17884 <entry><literal>pg_control_version</literal></entry>
17885 <entry><type>integer</type></entry>
17889 <entry><literal>catalog_version_no</literal></entry>
17890 <entry><type>integer</type></entry>
17894 <entry><literal>system_identifier</literal></entry>
17895 <entry><type>bigint</type></entry>
17899 <entry><literal>pg_control_last_modified</literal></entry>
17900 <entry><type>timestamp with time zone</type></entry>
17908 <function>pg_control_init</> returns a record, shown in
17909 <xref linkend="functions-pg-control-init">
17912 <table id="functions-pg-control-init">
17913 <title><function>pg_control_init</> Columns</title>
17917 <entry>Column Name</entry>
17918 <entry>Data Type</entry>
17925 <entry><literal>max_data_alignment</literal></entry>
17926 <entry><type>integer</type></entry>
17930 <entry><literal>database_block_size</literal></entry>
17931 <entry><type>integer</type></entry>
17935 <entry><literal>blocks_per_segment</literal></entry>
17936 <entry><type>integer</type></entry>
17940 <entry><literal>wal_block_size</literal></entry>
17941 <entry><type>integer</type></entry>
17945 <entry><literal>bytes_per_wal_segment</literal></entry>
17946 <entry><type>integer</type></entry>
17950 <entry><literal>max_identifier_length</literal></entry>
17951 <entry><type>integer</type></entry>
17955 <entry><literal>max_index_columns</literal></entry>
17956 <entry><type>integer</type></entry>
17960 <entry><literal>max_toast_chunk_size</literal></entry>
17961 <entry><type>integer</type></entry>
17965 <entry><literal>large_object_chunk_size</literal></entry>
17966 <entry><type>integer</type></entry>
17970 <entry><literal>float4_pass_by_value</literal></entry>
17971 <entry><type>boolean</type></entry>
17975 <entry><literal>float8_pass_by_value</literal></entry>
17976 <entry><type>boolean</type></entry>
17980 <entry><literal>data_page_checksum_version</literal></entry>
17981 <entry><type>integer</type></entry>
17989 <function>pg_control_recovery</> returns a record, shown in
17990 <xref linkend="functions-pg-control-recovery">
17993 <table id="functions-pg-control-recovery">
17994 <title><function>pg_control_recovery</> Columns</title>
17998 <entry>Column Name</entry>
17999 <entry>Data Type</entry>
18006 <entry><literal>min_recovery_end_location</literal></entry>
18007 <entry><type>pg_lsn</type></entry>
18011 <entry><literal>min_recovery_end_timeline</literal></entry>
18012 <entry><type>integer</type></entry>
18016 <entry><literal>backup_start_location</literal></entry>
18017 <entry><type>pg_lsn</type></entry>
18021 <entry><literal>backup_end_location</literal></entry>
18022 <entry><type>pg_lsn</type></entry>
18026 <entry><literal>end_of_backup_record_required</literal></entry>
18027 <entry><type>boolean</type></entry>
18036 <sect1 id="functions-admin">
18037 <title>System Administration Functions</title>
18040 The functions described in this section are used to control and
18041 monitor a <productname>PostgreSQL</> installation.
18044 <sect2 id="functions-admin-set">
18045 <title>Configuration Settings Functions</title>
18048 <xref linkend="functions-admin-set-table"> shows the functions
18049 available to query and alter run-time configuration parameters.
18052 <table id="functions-admin-set-table">
18053 <title>Configuration Settings Functions</title>
18056 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
18063 <primary>current_setting</primary>
18065 <literal><function>current_setting(<parameter>setting_name</parameter> [, <parameter>missing_ok</parameter> ])</function></literal>
18067 <entry><type>text</type></entry>
18068 <entry>get current value of setting</entry>
18073 <primary>set_config</primary>
18075 <literal><function>set_config(<parameter>setting_name</parameter>,
18076 <parameter>new_value</parameter>,
18077 <parameter>is_local</parameter>)</function></literal>
18079 <entry><type>text</type></entry>
18080 <entry>set parameter and return new value</entry>
18087 <primary>SET</primary>
18091 <primary>SHOW</primary>
18095 <primary>configuration</primary>
18096 <secondary sortas="server">of the server</secondary>
18097 <tertiary>functions</tertiary>
18101 The function <function>current_setting</function> yields the
18102 current value of the setting <parameter>setting_name</parameter>.
18103 It corresponds to the <acronym>SQL</acronym> command
18104 <command>SHOW</command>. An example:
18106 SELECT current_setting('datestyle');
18114 If there is no setting named <parameter>setting_name</parameter>,
18115 <function>current_setting</function> throws an error
18116 unless <parameter>missing_ok</parameter> is supplied and is
18117 <literal>true</literal>.
18121 <function>set_config</function> sets the parameter
18122 <parameter>setting_name</parameter> to
18123 <parameter>new_value</parameter>. If
18124 <parameter>is_local</parameter> is <literal>true</literal>, the
18125 new value will only apply to the current transaction. If you want
18126 the new value to apply for the current session, use
18127 <literal>false</literal> instead. The function corresponds to the
18128 SQL command <command>SET</command>. An example:
18130 SELECT set_config('log_statement_stats', 'off', false);
18141 <sect2 id="functions-admin-signal">
18142 <title>Server Signaling Functions</title>
18145 <primary>pg_cancel_backend</primary>
18148 <primary>pg_reload_conf</primary>
18151 <primary>pg_rotate_logfile</primary>
18154 <primary>pg_terminate_backend</primary>
18158 <primary>signal</primary>
18159 <secondary sortas="backend">backend processes</secondary>
18163 The functions shown in <xref
18164 linkend="functions-admin-signal-table"> send control signals to
18165 other server processes. Use of these functions is restricted to
18166 superusers by default but access may be granted to others using
18167 <command>GRANT</command>, with noted exceptions.
18170 <table id="functions-admin-signal-table">
18171 <title>Server Signaling Functions</title>
18174 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18181 <literal><function>pg_cancel_backend(<parameter>pid</parameter> <type>int</>)</function></literal>
18183 <entry><type>boolean</type></entry>
18184 <entry>Cancel a backend's current query. This is also allowed if the
18185 calling role is a member of the role whose backend is being canceled or
18186 the calling role has been granted <literal>pg_signal_backend</literal>,
18187 however only superusers can cancel superuser backends.
18192 <literal><function>pg_reload_conf()</function></literal>
18194 <entry><type>boolean</type></entry>
18195 <entry>Cause server processes to reload their configuration files</entry>
18199 <literal><function>pg_rotate_logfile()</function></literal>
18201 <entry><type>boolean</type></entry>
18202 <entry>Rotate server's log file</entry>
18206 <literal><function>pg_terminate_backend(<parameter>pid</parameter> <type>int</>)</function></literal>
18208 <entry><type>boolean</type></entry>
18209 <entry>Terminate a backend. This is also allowed if the calling role
18210 is a member of the role whose backend is being terminated or the
18211 calling role has been granted <literal>pg_signal_backend</literal>,
18212 however only superusers can terminate superuser backends.
18220 Each of these functions returns <literal>true</literal> if
18221 successful and <literal>false</literal> otherwise.
18225 <function>pg_cancel_backend</> and <function>pg_terminate_backend</>
18226 send signals (<systemitem>SIGINT</> or <systemitem>SIGTERM</>
18227 respectively) to backend processes identified by process ID.
18228 The process ID of an active backend can be found from
18229 the <structfield>pid</structfield> column of the
18230 <structname>pg_stat_activity</structname> view, or by listing the
18231 <command>postgres</command> processes on the server (using
18232 <application>ps</> on Unix or the <application>Task
18233 Manager</> on <productname>Windows</>).
18234 The role of an active backend can be found from the
18235 <structfield>usename</structfield> column of the
18236 <structname>pg_stat_activity</structname> view.
18240 <function>pg_reload_conf</> sends a <systemitem>SIGHUP</> signal
18241 to the server, causing configuration files
18242 to be reloaded by all server processes.
18246 <function>pg_rotate_logfile</> signals the log-file manager to switch
18247 to a new output file immediately. This works only when the built-in
18248 log collector is running, since otherwise there is no log-file manager
18254 <sect2 id="functions-admin-backup">
18255 <title>Backup Control Functions</title>
18258 <primary>backup</primary>
18261 <primary>pg_create_restore_point</primary>
18264 <primary>pg_current_wal_flush_location</primary>
18267 <primary>pg_current_wal_insert_location</primary>
18270 <primary>pg_current_wal_location</primary>
18273 <primary>pg_start_backup</primary>
18276 <primary>pg_stop_backup</primary>
18279 <primary>pg_is_in_backup</primary>
18282 <primary>pg_backup_start_time</primary>
18285 <primary>pg_switch_wal</primary>
18288 <primary>pg_walfile_name</primary>
18291 <primary>pg_walfile_name_offset</primary>
18294 <primary>pg_wal_location_diff</primary>
18298 The functions shown in <xref
18299 linkend="functions-admin-backup-table"> assist in making on-line backups.
18300 These functions cannot be executed during recovery (except
18301 <function>pg_is_in_backup</function>, <function>pg_backup_start_time</function>
18302 and <function>pg_wal_location_diff</function>).
18305 <table id="functions-admin-backup-table">
18306 <title>Backup Control Functions</title>
18309 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18316 <literal><function>pg_create_restore_point(<parameter>name</> <type>text</>)</function></literal>
18318 <entry><type>pg_lsn</type></entry>
18319 <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>
18323 <literal><function>pg_current_wal_flush_location()</function></literal>
18325 <entry><type>pg_lsn</type></entry>
18326 <entry>Get current transaction log flush location</entry>
18330 <literal><function>pg_current_wal_insert_location()</function></literal>
18332 <entry><type>pg_lsn</type></entry>
18333 <entry>Get current transaction log insert location</entry>
18337 <literal><function>pg_current_wal_location()</function></literal>
18339 <entry><type>pg_lsn</type></entry>
18340 <entry>Get current transaction log write location</entry>
18344 <literal><function>pg_start_backup(<parameter>label</> <type>text</> <optional>, <parameter>fast</> <type>boolean</> <optional>, <parameter>exclusive</> <type>boolean</> </optional></optional>)</function></literal>
18346 <entry><type>pg_lsn</type></entry>
18347 <entry>Prepare for performing on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
18351 <literal><function>pg_stop_backup()</function></literal>
18353 <entry><type>pg_lsn</type></entry>
18354 <entry>Finish performing exclusive on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
18358 <literal><function>pg_stop_backup(<parameter>exclusive</> <type>boolean</>)</function></literal>
18360 <entry><type>setof record</type></entry>
18361 <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>
18365 <literal><function>pg_is_in_backup()</function></literal>
18367 <entry><type>bool</type></entry>
18368 <entry>True if an on-line exclusive backup is still in progress.</entry>
18372 <literal><function>pg_backup_start_time()</function></literal>
18374 <entry><type>timestamp with time zone</type></entry>
18375 <entry>Get start time of an on-line exclusive backup in progress.</entry>
18379 <literal><function>pg_switch_wal()</function></literal>
18381 <entry><type>pg_lsn</type></entry>
18382 <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>
18386 <literal><function>pg_walfile_name(<parameter>location</> <type>pg_lsn</>)</function></literal>
18388 <entry><type>text</type></entry>
18389 <entry>Convert transaction log location string to file name</entry>
18393 <literal><function>pg_walfile_name_offset(<parameter>location</> <type>pg_lsn</>)</function></literal>
18395 <entry><type>text</>, <type>integer</></entry>
18396 <entry>Convert transaction log location string to file name and decimal byte offset within file</entry>
18400 <literal><function>pg_wal_location_diff(<parameter>location</> <type>pg_lsn</>, <parameter>location</> <type>pg_lsn</>)</function></literal>
18402 <entry><type>numeric</></entry>
18403 <entry>Calculate the difference between two transaction log locations</entry>
18410 <function>pg_start_backup</> accepts an arbitrary user-defined label for
18411 the backup. (Typically this would be the name under which the backup dump
18412 file will be stored.) When used in exclusive mode, the function writes a
18413 backup label file (<filename>backup_label</>) and, if there are any links
18414 in the <filename>pg_tblspc/</> directory, a tablespace map file
18415 (<filename>tablespace_map</>) into the database cluster's data directory,
18416 performs a checkpoint, and then returns the backup's starting transaction
18417 log location as text. The user can ignore this result value, but it is
18418 provided in case it is useful. When used in non-exclusive mode, the
18419 contents of these files are instead returned by the
18420 <function>pg_stop_backup</> function, and should be written to the backup
18424 postgres=# select pg_start_backup('label_goes_here');
18430 There is an optional second parameter of type <type>boolean</type>. If <literal>true</>,
18431 it specifies executing <function>pg_start_backup</> as quickly as
18432 possible. This forces an immediate checkpoint which will cause a
18433 spike in I/O operations, slowing any concurrently executing queries.
18437 In an exclusive backup, <function>pg_stop_backup</> removes the label file
18438 and, if it exists, the <filename>tablespace_map</> file created by
18439 <function>pg_start_backup</>. In a non-exclusive backup, the contents of
18440 the <filename>backup_label</> and <filename>tablespace_map</> are returned
18441 in the result of the function, and should be written to files in the
18442 backup (and not in the data directory).
18446 The function also creates a backup history file in the transaction log
18447 archive area. The history file includes the label given to
18448 <function>pg_start_backup</>, the starting and ending transaction log locations for
18449 the backup, and the starting and ending times of the backup. The return
18450 value is the backup's ending transaction log location (which again
18451 can be ignored). After recording the ending location, the current
18452 transaction log insertion
18453 point is automatically advanced to the next transaction log file, so that the
18454 ending transaction log file can be archived immediately to complete the backup.
18458 <function>pg_switch_wal</> moves to the next transaction log file, allowing the
18459 current file to be archived (assuming you are using continuous archiving).
18460 The return value is the ending transaction log location + 1 within the just-completed transaction log file.
18461 If there has been no transaction log activity since the last transaction log switch,
18462 <function>pg_switch_wal</> does nothing and returns the start location
18463 of the transaction log file currently in use.
18467 <function>pg_create_restore_point</> creates a named transaction log
18468 record that can be used as recovery target, and returns the corresponding
18469 transaction log location. The given name can then be used with
18470 <xref linkend="recovery-target-name"> to specify the point up to which
18471 recovery will proceed. Avoid creating multiple restore points with the
18472 same name, since recovery will stop at the first one whose name matches
18473 the recovery target.
18477 <function>pg_current_wal_location</> displays the current transaction log write
18478 location in the same format used by the above functions. Similarly,
18479 <function>pg_current_wal_insert_location</> displays the current transaction log
18480 insertion point and <function>pg_current_wal_flush_location</> displays the
18481 current transaction log flush point. The insertion point is the <quote>logical</>
18482 end of the transaction log at any instant, while the write location is the end of
18483 what has actually been written out from the server's internal buffers and flush
18484 location is the location guaranteed to be written to durable storage. The write
18485 location is the end of what can be examined from outside the server, and is usually
18486 what you want if you are interested in archiving partially-complete transaction log
18487 files. The insertion and flush points are made available primarily for server
18488 debugging purposes. These are both read-only operations and do not
18489 require superuser permissions.
18493 You can use <function>pg_walfile_name_offset</> to extract the
18494 corresponding transaction log file name and byte offset from the results of any of the
18495 above functions. For example:
18497 postgres=# SELECT * FROM pg_walfile_name_offset(pg_stop_backup());
18498 file_name | file_offset
18499 --------------------------+-------------
18500 00000001000000000000000D | 4039624
18503 Similarly, <function>pg_walfile_name</> extracts just the transaction log file name.
18504 When the given transaction log location is exactly at a transaction log file boundary, both
18505 these functions return the name of the preceding transaction log file.
18506 This is usually the desired behavior for managing transaction log archiving
18507 behavior, since the preceding file is the last one that currently
18508 needs to be archived.
18512 <function>pg_wal_location_diff</> calculates the difference in bytes
18513 between two transaction log locations. It can be used with
18514 <structname>pg_stat_replication</structname> or some functions shown in
18515 <xref linkend="functions-admin-backup-table"> to get the replication lag.
18519 For details about proper usage of these functions, see
18520 <xref linkend="continuous-archiving">.
18525 <sect2 id="functions-recovery-control">
18526 <title>Recovery Control Functions</title>
18529 <primary>pg_is_in_recovery</primary>
18532 <primary>pg_last_wal_receive_location</primary>
18535 <primary>pg_last_wal_replay_location</primary>
18538 <primary>pg_last_xact_replay_timestamp</primary>
18542 The functions shown in <xref
18543 linkend="functions-recovery-info-table"> provide information
18544 about the current status of the standby.
18545 These functions may be executed both during recovery and in normal running.
18548 <table id="functions-recovery-info-table">
18549 <title>Recovery Information Functions</title>
18552 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18559 <literal><function>pg_is_in_recovery()</function></literal>
18561 <entry><type>bool</type></entry>
18562 <entry>True if recovery is still in progress.
18567 <literal><function>pg_last_wal_receive_location()</function></literal>
18569 <entry><type>pg_lsn</type></entry>
18570 <entry>Get last transaction log location received and synced to disk by
18571 streaming replication. While streaming replication is in progress
18572 this will increase monotonically. If recovery has completed this will
18574 the value of the last WAL record received and synced to disk during
18575 recovery. If streaming replication is disabled, or if it has not yet
18576 started, the function returns NULL.
18581 <literal><function>pg_last_wal_replay_location()</function></literal>
18583 <entry><type>pg_lsn</type></entry>
18584 <entry>Get last transaction log location replayed during recovery.
18585 If recovery is still in progress this will increase monotonically.
18586 If recovery has completed then this value will remain static at
18587 the value of the last WAL record applied during that recovery.
18588 When the server has been started normally without recovery
18589 the function returns NULL.
18594 <literal><function>pg_last_xact_replay_timestamp()</function></literal>
18596 <entry><type>timestamp with time zone</type></entry>
18597 <entry>Get time stamp of last transaction replayed during recovery.
18598 This is the time at which the commit or abort WAL record for that
18599 transaction was generated on the primary.
18600 If no transactions have been replayed during recovery, this function
18601 returns NULL. Otherwise, if recovery is still in progress this will
18602 increase monotonically. If recovery has completed then this value will
18603 remain static at the value of the last transaction applied during that
18604 recovery. When the server has been started normally without recovery
18605 the function returns NULL.
18613 <primary>pg_is_wal_replay_paused</primary>
18616 <primary>pg_wal_replay_pause</primary>
18619 <primary>pg_wal_replay_resume</primary>
18623 The functions shown in <xref
18624 linkend="functions-recovery-control-table"> control the progress of recovery.
18625 These functions may be executed only during recovery.
18628 <table id="functions-recovery-control-table">
18629 <title>Recovery Control Functions</title>
18632 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18639 <literal><function>pg_is_wal_replay_paused()</function></literal>
18641 <entry><type>bool</type></entry>
18642 <entry>True if recovery is paused.
18647 <literal><function>pg_wal_replay_pause()</function></literal>
18649 <entry><type>void</type></entry>
18650 <entry>Pauses recovery immediately (restricted to superusers by default, but other users can be granted EXECUTE to run the function).
18655 <literal><function>pg_wal_replay_resume()</function></literal>
18657 <entry><type>void</type></entry>
18658 <entry>Restarts recovery if it was paused (restricted to superusers by default, but other users can be granted EXECUTE to run the function).
18666 While recovery is paused no further database changes are applied.
18667 If in hot standby, all new queries will see the same consistent snapshot
18668 of the database, and no further query conflicts will be generated until
18669 recovery is resumed.
18673 If streaming replication is disabled, the paused state may continue
18674 indefinitely without problem. While streaming replication is in
18675 progress WAL records will continue to be received, which will
18676 eventually fill available disk space, depending upon the duration of
18677 the pause, the rate of WAL generation and available disk space.
18682 <sect2 id="functions-snapshot-synchronization">
18683 <title>Snapshot Synchronization Functions</title>
18686 <primary>pg_export_snapshot</primary>
18690 <productname>PostgreSQL</> allows database sessions to synchronize their
18691 snapshots. A <firstterm>snapshot</> determines which data is visible to the
18692 transaction that is using the snapshot. Synchronized snapshots are
18693 necessary when two or more sessions need to see identical content in the
18694 database. If two sessions just start their transactions independently,
18695 there is always a possibility that some third transaction commits
18696 between the executions of the two <command>START TRANSACTION</> commands,
18697 so that one session sees the effects of that transaction and the other
18702 To solve this problem, <productname>PostgreSQL</> allows a transaction to
18703 <firstterm>export</> the snapshot it is using. As long as the exporting
18704 transaction remains open, other transactions can <firstterm>import</> its
18705 snapshot, and thereby be guaranteed that they see exactly the same view
18706 of the database that the first transaction sees. But note that any
18707 database changes made by any one of these transactions remain invisible
18708 to the other transactions, as is usual for changes made by uncommitted
18709 transactions. So the transactions are synchronized with respect to
18710 pre-existing data, but act normally for changes they make themselves.
18714 Snapshots are exported with the <function>pg_export_snapshot</> function,
18715 shown in <xref linkend="functions-snapshot-synchronization-table">, and
18716 imported with the <xref linkend="sql-set-transaction"> command.
18719 <table id="functions-snapshot-synchronization-table">
18720 <title>Snapshot Synchronization Functions</title>
18723 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18730 <literal><function>pg_export_snapshot()</function></literal>
18732 <entry><type>text</type></entry>
18733 <entry>Save the current snapshot and return its identifier</entry>
18740 The function <function>pg_export_snapshot</> saves the current snapshot
18741 and returns a <type>text</> string identifying the snapshot. This string
18742 must be passed (outside the database) to clients that want to import the
18743 snapshot. The snapshot is available for import only until the end of the
18744 transaction that exported it. A transaction can export more than one
18745 snapshot, if needed. Note that doing so is only useful in <literal>READ
18746 COMMITTED</> transactions, since in <literal>REPEATABLE READ</> and
18747 higher isolation levels, transactions use the same snapshot throughout
18748 their lifetime. Once a transaction has exported any snapshots, it cannot
18749 be prepared with <xref linkend="sql-prepare-transaction">.
18753 See <xref linkend="sql-set-transaction"> for details of how to use an
18758 <sect2 id="functions-replication">
18759 <title>Replication Functions</title>
18762 The functions shown
18763 in <xref linkend="functions-replication-table"> are for
18764 controlling and interacting with replication features.
18765 See <xref linkend="streaming-replication">,
18766 <xref linkend="streaming-replication-slots">, and
18767 <xref linkend="replication-origins">
18768 for information about the underlying features. Use of these
18769 functions is restricted to superusers.
18773 Many of these functions have equivalent commands in the replication
18774 protocol; see <xref linkend="protocol-replication">.
18778 The functions described in
18779 <xref linkend="functions-admin-backup">,
18780 <xref linkend="functions-recovery-control">, and
18781 <xref linkend="functions-snapshot-synchronization">
18782 are also relevant for replication.
18785 <table id="functions-replication-table">
18786 <title>Replication <acronym>SQL</acronym> Functions</title>
18790 <entry>Function</entry>
18791 <entry>Return Type</entry>
18792 <entry>Description</entry>
18799 <primary>pg_create_physical_replication_slot</primary>
18801 <literal><function>pg_create_physical_replication_slot(<parameter>slot_name</parameter> <type>name</type> <optional>, <parameter>immediately_reserve</> <type>boolean</>, <parameter>temporary</> <type>boolean</></optional>)</function></literal>
18804 (<parameter>slot_name</parameter> <type>name</type>, <parameter>wal_position</parameter> <type>pg_lsn</type>)
18807 Creates a new physical replication slot named
18808 <parameter>slot_name</parameter>. The optional second parameter,
18809 when <literal>true</>, specifies that the <acronym>LSN</> for this
18810 replication slot be reserved immediately; otherwise
18811 the <acronym>LSN</> is reserved on first connection from a streaming
18812 replication client. Streaming changes from a physical slot is only
18813 possible with the streaming-replication protocol —
18814 see <xref linkend="protocol-replication">. The optional third
18815 parameter, <parameter>temporary</>, when set to true, specifies that
18816 the slot should not be permanently stored to disk and is only meant
18817 for use by current session. Temporary slots are also
18818 released upon any error. This function corresponds
18819 to the replication protocol command <literal>CREATE_REPLICATION_SLOT
18820 ... PHYSICAL</literal>.
18826 <primary>pg_drop_replication_slot</primary>
18828 <literal><function>pg_drop_replication_slot(<parameter>slot_name</parameter> <type>name</type>)</function></literal>
18834 Drops the physical or logical replication slot
18835 named <parameter>slot_name</parameter>. Same as replication protocol
18836 command <literal>DROP_REPLICATION_SLOT</>.
18843 <primary>pg_create_logical_replication_slot</primary>
18845 <literal><function>pg_create_logical_replication_slot(<parameter>slot_name</parameter> <type>name</type>, <parameter>plugin</parameter> <type>name</type> <optional>, <parameter>temporary</> <type>boolean</></optional>)</function></literal>
18848 (<parameter>slot_name</parameter> <type>name</type>, <parameter>wal_position</parameter> <type>pg_lsn</type>)
18851 Creates a new logical (decoding) replication slot named
18852 <parameter>slot_name</parameter> using the output plugin
18853 <parameter>plugin</parameter>. The optional third
18854 parameter, <parameter>temporary</>, when set to true, specifies that
18855 the slot should not be permanently stored to disk and is only meant
18856 for use by current session. Temporary slots are also
18857 released upon any error. A call to this function has the same
18858 effect as the replication protocol command
18859 <literal>CREATE_REPLICATION_SLOT ... LOGICAL</literal>.
18866 <primary>pg_logical_slot_get_changes</primary>
18868 <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>
18871 (<parameter>location</parameter> <type>pg_lsn</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>text</type>)
18874 Returns changes in the slot <parameter>slot_name</parameter>, starting
18875 from the point at which since changes have been consumed last. If
18876 <parameter>upto_lsn</> and <parameter>upto_nchanges</> are NULL,
18877 logical decoding will continue until end of WAL. If
18878 <parameter>upto_lsn</> is non-NULL, decoding will include only
18879 those transactions which commit prior to the specified LSN. If
18880 <parameter>upto_nchanges</parameter> is non-NULL, decoding will
18881 stop when the number of rows produced by decoding exceeds
18882 the specified value. Note, however, that the actual number of
18883 rows returned may be larger, since this limit is only checked after
18884 adding the rows produced when decoding each new transaction commit.
18891 <primary>pg_logical_slot_peek_changes</primary>
18893 <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>
18896 (<parameter>location</parameter> <type>text</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>text</type>)
18900 the <function>pg_logical_slot_get_changes()</function> function,
18901 except that changes are not consumed; that is, they will be returned
18902 again on future calls.
18909 <primary>pg_logical_slot_get_binary_changes</primary>
18911 <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>
18914 (<parameter>location</parameter> <type>pg_lsn</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>bytea</type>)
18918 the <function>pg_logical_slot_get_changes()</function> function,
18919 except that changes are returned as <type>bytea</type>.
18926 <primary>pg_logical_slot_peek_binary_changes</primary>
18928 <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>
18931 (<parameter>location</parameter> <type>pg_lsn</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>bytea</type>)
18935 the <function>pg_logical_slot_get_changes()</function> function,
18936 except that changes are returned as <type>bytea</type> and that
18937 changes are not consumed; that is, they will be returned again
18943 <entry id="pg-replication-origin-create">
18945 <primary>pg_replication_origin_create</primary>
18947 <literal><function>pg_replication_origin_create(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18953 Create a replication origin with the given external
18954 name, and return the internal id assigned to it.
18959 <entry id="pg-replication-origin-drop">
18961 <primary>pg_replication_origin_drop</primary>
18963 <literal><function>pg_replication_origin_drop(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18969 Delete a previously created replication origin, including any
18970 associated replay progress.
18977 <primary>pg_replication_origin_oid</primary>
18979 <literal><function>pg_replication_origin_oid(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18985 Lookup a replication origin by name and return the internal id. If no
18986 corresponding replication origin is found an error is thrown.
18991 <entry id="pg-replication-origin-session-setup">
18993 <primary>pg_replication_origin_session_setup</primary>
18995 <literal><function>pg_replication_origin_session_setup(<parameter>node_name</parameter> <type>text</type>)</function></literal>
19001 Mark the current session as replaying from the given
19002 origin, allowing replay progress to be tracked. Use
19003 <function>pg_replication_origin_session_reset</function> to revert.
19004 Can only be used if no previous origin is configured.
19011 <primary>pg_replication_origin_session_reset</primary>
19013 <literal><function>pg_replication_origin_session_reset()</function></literal>
19020 of <function>pg_replication_origin_session_setup()</function>.
19027 <primary>pg_replication_origin_session_is_setup</primary>
19029 <literal><function>pg_replication_origin_session_is_setup()</function></literal>
19035 Has a replication origin been configured in the current session?
19040 <entry id="pg-replication-origin-session-progress">
19042 <primary>pg_replication_origin_session_progress</primary>
19044 <literal><function>pg_replication_origin_session_progress(<parameter>flush</parameter> <type>bool</type>)</function></literal>
19047 <type>pg_lsn</type>
19050 Return the replay position for the replication origin configured in
19051 the current session. The parameter <parameter>flush</parameter>
19052 determines whether the corresponding local transaction will be
19053 guaranteed to have been flushed to disk or not.
19058 <entry id="pg-replication-origin-xact-setup">
19060 <primary>pg_replication_origin_xact_setup</primary>
19062 <literal><function>pg_replication_origin_xact_setup(<parameter>origin_lsn</parameter> <type>pg_lsn</type>, <parameter>origin_timestamp</parameter> <type>timestamptz</type>)</function></literal>
19068 Mark the current transaction as replaying a transaction that has
19069 committed at the given <acronym>LSN</acronym> and timestamp. Can
19070 only be called when a replication origin has previously been
19072 <function>pg_replication_origin_session_setup()</function>.
19077 <entry id="pg-replication-origin-xact-reset">
19079 <primary>pg_replication_origin_xact_reset</primary>
19081 <literal><function>pg_replication_origin_xact_reset()</function></literal>
19087 Cancel the effects of
19088 <function>pg_replication_origin_xact_setup()</function>.
19093 <entry id="pg-replication-origin-advance">
19095 <primary>pg_replication_origin_advance</primary>
19097 <literal>pg_replication_origin_advance<function>(<parameter>node_name</parameter> <type>text</type>, <parameter>pos</parameter> <type>pg_lsn</type>)</function></literal>
19103 Set replication progress for the given node to the given
19104 position. This primarily is useful for setting up the initial position
19105 or a new position after configuration changes and similar. Be aware
19106 that careless use of this function can lead to inconsistently
19112 <entry id="pg-replication-origin-progress">
19114 <primary>pg_replication_origin_progress</primary>
19116 <literal><function>pg_replication_origin_progress(<parameter>node_name</parameter> <type>text</type>, <parameter>flush</parameter> <type>bool</type>)</function></literal>
19119 <type>pg_lsn</type>
19122 Return the replay position for the given replication origin. The
19123 parameter <parameter>flush</parameter> determines whether the
19124 corresponding local transaction will be guaranteed to have been
19125 flushed to disk or not.
19130 <entry id="pg-logical-emit-message-text">
19132 <primary>pg_logical_emit_message</primary>
19134 <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>
19137 <type>pg_lsn</type>
19140 Emit text logical decoding message. This can be used to pass generic
19141 messages to logical decoding plugins through WAL. The parameter
19142 <parameter>transactional</parameter> specifies if the message should
19143 be part of current transaction or if it should be written immediately
19144 and decoded as soon as the logical decoding reads the record. The
19145 <parameter>prefix</parameter> is textual prefix used by the logical
19146 decoding plugins to easily recognize interesting messages for them.
19147 The <parameter>content</parameter> is the text of the message.
19152 <entry id="pg-logical-emit-message-bytea">
19153 <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>
19156 <type>pg_lsn</type>
19159 Emit binary logical decoding message. This can be used to pass generic
19160 messages to logical decoding plugins through WAL. The parameter
19161 <parameter>transactional</parameter> specifies if the message should
19162 be part of current transaction or if it should be written immediately
19163 and decoded as soon as the logical decoding reads the record. The
19164 <parameter>prefix</parameter> is textual prefix used by the logical
19165 decoding plugins to easily recognize interesting messages for them.
19166 The <parameter>content</parameter> is the binary content of the
19177 <sect2 id="functions-admin-dbobject">
19178 <title>Database Object Management Functions</title>
19181 The functions shown in <xref linkend="functions-admin-dbsize"> calculate
19182 the disk space usage of database objects.
19186 <primary>pg_column_size</primary>
19189 <primary>pg_database_size</primary>
19192 <primary>pg_indexes_size</primary>
19195 <primary>pg_relation_size</primary>
19198 <primary>pg_size_bytes</primary>
19201 <primary>pg_size_pretty</primary>
19204 <primary>pg_table_size</primary>
19207 <primary>pg_tablespace_size</primary>
19210 <primary>pg_total_relation_size</primary>
19213 <table id="functions-admin-dbsize">
19214 <title>Database Object Size Functions</title>
19217 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
19223 <entry><literal><function>pg_column_size(<type>any</type>)</function></literal></entry>
19224 <entry><type>int</type></entry>
19225 <entry>Number of bytes used to store a particular value (possibly compressed)</entry>
19229 <literal><function>pg_database_size(<type>oid</type>)</function></literal>
19231 <entry><type>bigint</type></entry>
19232 <entry>Disk space used by the database with the specified OID</entry>
19236 <literal><function>pg_database_size(<type>name</type>)</function></literal>
19238 <entry><type>bigint</type></entry>
19239 <entry>Disk space used by the database with the specified name</entry>
19243 <literal><function>pg_indexes_size(<type>regclass</type>)</function></literal>
19245 <entry><type>bigint</type></entry>
19247 Total disk space used by indexes attached to the specified table
19252 <literal><function>pg_relation_size(<parameter>relation</parameter> <type>regclass</type>, <parameter>fork</parameter> <type>text</type>)</function></literal>
19254 <entry><type>bigint</type></entry>
19256 Disk space used by the specified fork (<literal>'main'</literal>,
19257 <literal>'fsm'</literal>, <literal>'vm'</>, or <literal>'init'</>)
19258 of the specified table or index
19263 <literal><function>pg_relation_size(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
19265 <entry><type>bigint</type></entry>
19267 Shorthand for <literal>pg_relation_size(..., 'main')</literal>
19272 <literal><function>pg_size_bytes(<type>text</type>)</function></literal>
19274 <entry><type>bigint</type></entry>
19276 Converts a size in human-readable format with size units into bytes
19281 <literal><function>pg_size_pretty(<type>bigint</type>)</function></literal>
19283 <entry><type>text</type></entry>
19285 Converts a size in bytes expressed as a 64-bit integer into a
19286 human-readable format with size units
19291 <literal><function>pg_size_pretty(<type>numeric</type>)</function></literal>
19293 <entry><type>text</type></entry>
19295 Converts a size in bytes expressed as a numeric value into a
19296 human-readable format with size units
19301 <literal><function>pg_table_size(<type>regclass</type>)</function></literal>
19303 <entry><type>bigint</type></entry>
19305 Disk space used by the specified table, excluding indexes
19306 (but including TOAST, free space map, and visibility map)
19311 <literal><function>pg_tablespace_size(<type>oid</type>)</function></literal>
19313 <entry><type>bigint</type></entry>
19314 <entry>Disk space used by the tablespace with the specified OID</entry>
19318 <literal><function>pg_tablespace_size(<type>name</type>)</function></literal>
19320 <entry><type>bigint</type></entry>
19321 <entry>Disk space used by the tablespace with the specified name</entry>
19325 <literal><function>pg_total_relation_size(<type>regclass</type>)</function></literal>
19327 <entry><type>bigint</type></entry>
19329 Total disk space used by the specified table,
19330 including all indexes and <acronym>TOAST</> data
19338 <function>pg_column_size</> shows the space used to store any individual
19343 <function>pg_total_relation_size</> accepts the OID or name of a
19344 table or toast table, and returns the total on-disk space used for
19345 that table, including all associated indexes. This function is
19346 equivalent to <function>pg_table_size</function>
19347 <literal>+</> <function>pg_indexes_size</function>.
19351 <function>pg_table_size</> accepts the OID or name of a table and
19352 returns the disk space needed for that table, exclusive of indexes.
19353 (TOAST space, free space map, and visibility map are included.)
19357 <function>pg_indexes_size</> accepts the OID or name of a table and
19358 returns the total disk space used by all the indexes attached to that
19363 <function>pg_database_size</function> and <function>pg_tablespace_size</>
19364 accept the OID or name of a database or tablespace, and return the total
19365 disk space used therein. To use <function>pg_database_size</function>,
19366 you must have <literal>CONNECT</> permission on the specified database
19367 (which is granted by default). To use <function>pg_tablespace_size</>,
19368 you must have <literal>CREATE</> permission on the specified tablespace,
19369 unless it is the default tablespace for the current database.
19373 <function>pg_relation_size</> accepts the OID or name of a table, index
19374 or toast table, and returns the on-disk size in bytes of one fork of
19375 that relation. (Note that for most purposes it is more convenient to
19376 use the higher-level functions <function>pg_total_relation_size</>
19377 or <function>pg_table_size</>, which sum the sizes of all forks.)
19378 With one argument, it returns the size of the main data fork of the
19379 relation. The second argument can be provided to specify which fork
19381 <itemizedlist spacing="compact">
19384 <literal>'main'</literal> returns the size of the main
19385 data fork of the relation.
19390 <literal>'fsm'</literal> returns the size of the Free Space Map
19391 (see <xref linkend="storage-fsm">) associated with the relation.
19396 <literal>'vm'</literal> returns the size of the Visibility Map
19397 (see <xref linkend="storage-vm">) associated with the relation.
19402 <literal>'init'</literal> returns the size of the initialization
19403 fork, if any, associated with the relation.
19410 <function>pg_size_pretty</> can be used to format the result of one of
19411 the other functions in a human-readable way, using bytes, kB, MB, GB or TB
19416 <function>pg_size_bytes</> can be used to get the size in bytes from a
19417 string in human-readable format. The input may have units of bytes, kB,
19418 MB, GB or TB, and is parsed case-insensitively. If no units are specified,
19424 The units kB, MB, GB and TB used by the functions
19425 <function>pg_size_pretty</> and <function>pg_size_bytes</> are defined
19426 using powers of 2 rather than powers of 10, so 1kB is 1024 bytes, 1MB is
19427 1024<superscript>2</> = 1048576 bytes, and so on.
19432 The functions above that operate on tables or indexes accept a
19433 <type>regclass</> argument, which is simply the OID of the table or index
19434 in the <structname>pg_class</> system catalog. You do not have to look up
19435 the OID by hand, however, since the <type>regclass</> data type's input
19436 converter will do the work for you. Just write the table name enclosed in
19437 single quotes so that it looks like a literal constant. For compatibility
19438 with the handling of ordinary <acronym>SQL</acronym> names, the string
19439 will be converted to lower case unless it contains double quotes around
19444 If an OID that does not represent an existing object is passed as
19445 argument to one of the above functions, NULL is returned.
19449 The functions shown in <xref linkend="functions-admin-dblocation"> assist
19450 in identifying the specific disk files associated with database objects.
19454 <primary>pg_relation_filenode</primary>
19457 <primary>pg_relation_filepath</primary>
19460 <primary>pg_filenode_relation</primary>
19463 <table id="functions-admin-dblocation">
19464 <title>Database Object Location Functions</title>
19467 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
19474 <literal><function>pg_relation_filenode(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
19476 <entry><type>oid</type></entry>
19478 Filenode number of the specified relation
19483 <literal><function>pg_relation_filepath(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
19485 <entry><type>text</type></entry>
19487 File path name of the specified relation
19492 <literal><function>pg_filenode_relation(<parameter>tablespace</parameter> <type>oid</type>, <parameter>filenode</parameter> <type>oid</type>)</function></literal>
19494 <entry><type>regclass</type></entry>
19496 Find the relation associated with a given tablespace and filenode
19504 <function>pg_relation_filenode</> accepts the OID or name of a table,
19505 index, sequence, or toast table, and returns the <quote>filenode</> number
19506 currently assigned to it. The filenode is the base component of the file
19507 name(s) used for the relation (see <xref linkend="storage-file-layout">
19508 for more information). For most tables the result is the same as
19509 <structname>pg_class</>.<structfield>relfilenode</>, but for certain
19510 system catalogs <structfield>relfilenode</> is zero and this function must
19511 be used to get the correct value. The function returns NULL if passed
19512 a relation that does not have storage, such as a view.
19516 <function>pg_relation_filepath</> is similar to
19517 <function>pg_relation_filenode</>, but it returns the entire file path name
19518 (relative to the database cluster's data directory <varname>PGDATA</>) of
19523 <function>pg_filenode_relation</> is the reverse of
19524 <function>pg_relation_filenode</>. Given a <quote>tablespace</> OID and
19525 a <quote>filenode</>, it returns the associated relation's OID. For a table
19526 in the database's default tablespace, the tablespace can be specified as 0.
19530 <xref linkend="functions-admin-collation"> lists functions used to manage
19534 <table id="functions-admin-collation">
19535 <title>Collation Management Functions</title>
19538 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
19544 <indexterm><primary>pg_import_system_collations</primary></indexterm>
19545 <literal><function>pg_import_system_collations(<parameter>if_not_exists</> <type>boolean</>, <parameter>schema</> <type>regnamespace</>)</function></literal>
19547 <entry><type>void</type></entry>
19548 <entry>Import operating system collations</entry>
19555 <function>pg_import_system_collations</> populates the system
19556 catalog <literal>pg_collation</literal> with collations based on all the
19557 locales it finds on the operating system. This is
19558 what <command>initdb</command> uses;
19559 see <xref linkend="collation-managing"> for more details. If additional
19560 locales are installed into the operating system later on, this function
19561 can be run again to add collations for the new locales. In that case, the
19562 parameter <parameter>if_not_exists</parameter> should be set to true to
19563 skip over existing collations. The <parameter>schema</parameter>
19564 parameter would typically be <literal>pg_catalog</literal>, but that is
19565 not a requirement. (Collation objects based on locales that are no longer
19566 present on the operating system are never removed by this function.)
19571 <sect2 id="functions-admin-index">
19572 <title>Index Maintenance Functions</title>
19575 <primary>brin_summarize_new_values</primary>
19579 <primary>gin_clean_pending_list</primary>
19583 <xref linkend="functions-admin-index-table"> shows the functions
19584 available for index maintenance tasks.
19585 These functions cannot be executed during recovery.
19586 Use of these functions is restricted to superusers and the owner
19587 of the given index.
19590 <table id="functions-admin-index-table">
19591 <title>Index Maintenance Functions</title>
19594 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
19600 <literal><function>brin_summarize_new_values(<parameter>index</> <type>regclass</>)</function></literal>
19602 <entry><type>integer</type></entry>
19603 <entry>summarize page ranges not already summarized</entry>
19607 <literal><function>gin_clean_pending_list(<parameter>index</> <type>regclass</>)</function></literal>
19609 <entry><type>bigint</type></entry>
19610 <entry>move GIN pending list entries into main index structure</entry>
19617 <function>brin_summarize_new_values</> accepts the OID or name of a
19618 BRIN index and inspects the index to find page ranges in the base table
19619 that are not currently summarized by the index; for any such range
19620 it creates a new summary index tuple by scanning the table pages.
19621 It returns the number of new page range summaries that were inserted
19626 <function>gin_clean_pending_list</> accepts the OID or name of
19627 a GIN index and cleans up the pending list of the specified index
19628 by moving entries in it to the main GIN data structure in bulk.
19629 It returns the number of pages removed from the pending list.
19630 Note that if the argument is a GIN index built with
19631 the <literal>fastupdate</> option disabled, no cleanup happens and the
19632 return value is 0, because the index doesn't have a pending list.
19633 Please see <xref linkend="gin-fast-update"> and <xref linkend="gin-tips">
19634 for details of the pending list and <literal>fastupdate</> option.
19639 <sect2 id="functions-admin-genfile">
19640 <title>Generic File Access Functions</title>
19643 The functions shown in <xref
19644 linkend="functions-admin-genfile-table"> provide native access to
19645 files on the machine hosting the server. Only files within the
19646 database cluster directory and the <varname>log_directory</> can be
19647 accessed. Use a relative path for files in the cluster directory,
19648 and a path matching the <varname>log_directory</> configuration setting
19649 for log files. Use of these functions is restricted to superusers
19650 except where stated otherwise.
19653 <table id="functions-admin-genfile-table">
19654 <title>Generic File Access Functions</title>
19657 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
19664 <literal><function>pg_ls_dir(<parameter>dirname</> <type>text</> [, <parameter>missing_ok</> <type>boolean</>, <parameter>include_dot_dirs</> <type>boolean</>])</function></literal>
19666 <entry><type>setof text</type></entry>
19668 List the contents of a directory.
19673 <literal><function>pg_ls_logdir()</function></literal>
19675 <entry><type>setof record</type></entry>
19677 List the name, size, and last modification time of files in the log
19678 directory. Access may be granted to non-superuser roles.
19683 <literal><function>pg_ls_waldir()</function></literal>
19685 <entry><type>setof record</type></entry>
19687 List the name, size, and last modification time of files in the WAL
19688 directory. Access may be granted to non-superuser roles.
19693 <literal><function>pg_read_file(<parameter>filename</> <type>text</> [, <parameter>offset</> <type>bigint</>, <parameter>length</> <type>bigint</> [, <parameter>missing_ok</> <type>boolean</>] ])</function></literal>
19695 <entry><type>text</type></entry>
19697 Return the contents of a text file.
19702 <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>
19704 <entry><type>bytea</type></entry>
19706 Return the contents of a file.
19711 <literal><function>pg_stat_file(<parameter>filename</> <type>text</>[, <parameter>missing_ok</> <type>boolean</type>])</function></literal>
19713 <entry><type>record</type></entry>
19715 Return information about a file.
19723 Some of these functions take an optional <parameter>missing_ok</> parameter,
19724 which specifies the behavior when the file or directory does not exist.
19725 If <literal>true</literal>, the function returns NULL (except
19726 <function>pg_ls_dir</>, which returns an empty result set). If
19727 <literal>false</>, an error is raised. The default is <literal>false</>.
19731 <primary>pg_ls_dir</primary>
19734 <function>pg_ls_dir</> returns the names of all files (and directories
19735 and other special files) in the specified directory. The <parameter>
19736 include_dot_dirs</> indicates whether <quote>.</> and <quote>..</> are
19737 included in the result set. The default is to exclude them
19738 (<literal>false</>), but including them can be useful when
19739 <parameter>missing_ok</> is <literal>true</literal>, to distinguish an
19740 empty directory from an non-existent directory.
19744 <primary>pg_ls_logdir</primary>
19747 <function>pg_ls_logdir</> returns the name, size, and last modified time
19748 (mtime) of each file in the log directory. By default, only superusers
19749 can use this function, but access may be granted to others using
19750 <command>GRANT</command>.
19754 <primary>pg_ls_waldir</primary>
19757 <function>pg_ls_waldir</> returns the name, size, and last modified time
19758 (mtime) of each file in the write ahead log (WAL) directory. By
19759 default only superusers can use this function, but access may be granted
19760 to others using <command>GRANT</command>.
19764 <primary>pg_read_file</primary>
19767 <function>pg_read_file</> returns part of a text file, starting
19768 at the given <parameter>offset</>, returning at most <parameter>length</>
19769 bytes (less if the end of file is reached first). If <parameter>offset</>
19770 is negative, it is relative to the end of the file.
19771 If <parameter>offset</> and <parameter>length</> are omitted, the entire
19772 file is returned. The bytes read from the file are interpreted as a string
19773 in the server encoding; an error is thrown if they are not valid in that
19778 <primary>pg_read_binary_file</primary>
19781 <function>pg_read_binary_file</> is similar to
19782 <function>pg_read_file</>, except that the result is a <type>bytea</type> value;
19783 accordingly, no encoding checks are performed.
19784 In combination with the <function>convert_from</> function, this function
19785 can be used to read a file in a specified encoding:
19787 SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');
19792 <primary>pg_stat_file</primary>
19795 <function>pg_stat_file</> returns a record containing the file
19796 size, last accessed time stamp, last modified time stamp,
19797 last file status change time stamp (Unix platforms only),
19798 file creation time stamp (Windows only), and a <type>boolean</type>
19799 indicating if it is a directory. Typical usages include:
19801 SELECT * FROM pg_stat_file('filename');
19802 SELECT (pg_stat_file('filename')).modification;
19808 <sect2 id="functions-advisory-locks">
19809 <title>Advisory Lock Functions</title>
19812 The functions shown in <xref linkend="functions-advisory-locks-table">
19813 manage advisory locks. For details about proper use of these functions,
19814 see <xref linkend="advisory-locks">.
19817 <table id="functions-advisory-locks-table">
19818 <title>Advisory Lock Functions</title>
19821 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
19828 <literal><function>pg_advisory_lock(<parameter>key</> <type>bigint</>)</function></literal>
19830 <entry><type>void</type></entry>
19831 <entry>Obtain exclusive session level advisory lock</entry>
19835 <literal><function>pg_advisory_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19837 <entry><type>void</type></entry>
19838 <entry>Obtain exclusive session level advisory lock</entry>
19842 <literal><function>pg_advisory_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19844 <entry><type>void</type></entry>
19845 <entry>Obtain shared session level advisory lock</entry>
19849 <literal><function>pg_advisory_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19851 <entry><type>void</type></entry>
19852 <entry>Obtain shared session level advisory lock</entry>
19856 <literal><function>pg_advisory_unlock(<parameter>key</> <type>bigint</>)</function></literal>
19858 <entry><type>boolean</type></entry>
19859 <entry>Release an exclusive session level advisory lock</entry>
19863 <literal><function>pg_advisory_unlock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19865 <entry><type>boolean</type></entry>
19866 <entry>Release an exclusive session level advisory lock</entry>
19870 <literal><function>pg_advisory_unlock_all()</function></literal>
19872 <entry><type>void</type></entry>
19873 <entry>Release all session level advisory locks held by the current session</entry>
19877 <literal><function>pg_advisory_unlock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19879 <entry><type>boolean</type></entry>
19880 <entry>Release a shared session level advisory lock</entry>
19884 <literal><function>pg_advisory_unlock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19886 <entry><type>boolean</type></entry>
19887 <entry>Release a shared session level advisory lock</entry>
19891 <literal><function>pg_advisory_xact_lock(<parameter>key</> <type>bigint</>)</function></literal>
19893 <entry><type>void</type></entry>
19894 <entry>Obtain exclusive transaction level advisory lock</entry>
19898 <literal><function>pg_advisory_xact_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19900 <entry><type>void</type></entry>
19901 <entry>Obtain exclusive transaction level advisory lock</entry>
19905 <literal><function>pg_advisory_xact_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19907 <entry><type>void</type></entry>
19908 <entry>Obtain shared transaction level advisory lock</entry>
19912 <literal><function>pg_advisory_xact_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19914 <entry><type>void</type></entry>
19915 <entry>Obtain shared transaction level advisory lock</entry>
19919 <literal><function>pg_try_advisory_lock(<parameter>key</> <type>bigint</>)</function></literal>
19921 <entry><type>boolean</type></entry>
19922 <entry>Obtain exclusive session level advisory lock if available</entry>
19926 <literal><function>pg_try_advisory_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19928 <entry><type>boolean</type></entry>
19929 <entry>Obtain exclusive session level advisory lock if available</entry>
19933 <literal><function>pg_try_advisory_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19935 <entry><type>boolean</type></entry>
19936 <entry>Obtain shared session level advisory lock if available</entry>
19940 <literal><function>pg_try_advisory_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19942 <entry><type>boolean</type></entry>
19943 <entry>Obtain shared session level advisory lock if available</entry>
19947 <literal><function>pg_try_advisory_xact_lock(<parameter>key</> <type>bigint</>)</function></literal>
19949 <entry><type>boolean</type></entry>
19950 <entry>Obtain exclusive transaction level advisory lock if available</entry>
19954 <literal><function>pg_try_advisory_xact_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19956 <entry><type>boolean</type></entry>
19957 <entry>Obtain exclusive transaction level advisory lock if available</entry>
19961 <literal><function>pg_try_advisory_xact_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19963 <entry><type>boolean</type></entry>
19964 <entry>Obtain shared transaction level advisory lock if available</entry>
19968 <literal><function>pg_try_advisory_xact_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19970 <entry><type>boolean</type></entry>
19971 <entry>Obtain shared transaction level advisory lock if available</entry>
19978 <primary>pg_advisory_lock</primary>
19981 <function>pg_advisory_lock</> locks an application-defined resource,
19982 which can be identified either by a single 64-bit key value or two
19983 32-bit key values (note that these two key spaces do not overlap).
19984 If another session already holds a lock on the same resource identifier,
19985 this function will wait until the resource becomes available. The lock
19986 is exclusive. Multiple lock requests stack, so that if the same resource
19987 is locked three times it must then be unlocked three times to be
19988 released for other sessions' use.
19992 <primary>pg_advisory_lock_shared</primary>
19995 <function>pg_advisory_lock_shared</> works the same as
19996 <function>pg_advisory_lock</>,
19997 except the lock can be shared with other sessions requesting shared locks.
19998 Only would-be exclusive lockers are locked out.
20002 <primary>pg_try_advisory_lock</primary>
20005 <function>pg_try_advisory_lock</> is similar to
20006 <function>pg_advisory_lock</>, except the function will not wait for the
20007 lock to become available. It will either obtain the lock immediately and
20008 return <literal>true</>, or return <literal>false</> if the lock cannot be
20009 acquired immediately.
20013 <primary>pg_try_advisory_lock_shared</primary>
20016 <function>pg_try_advisory_lock_shared</> works the same as
20017 <function>pg_try_advisory_lock</>, except it attempts to acquire
20018 a shared rather than an exclusive lock.
20022 <primary>pg_advisory_unlock</primary>
20025 <function>pg_advisory_unlock</> will release a previously-acquired
20026 exclusive session level advisory lock. It
20027 returns <literal>true</> if the lock is successfully released.
20028 If the lock was not held, it will return <literal>false</>,
20029 and in addition, an SQL warning will be reported by the server.
20033 <primary>pg_advisory_unlock_shared</primary>
20036 <function>pg_advisory_unlock_shared</> works the same as
20037 <function>pg_advisory_unlock</>,
20038 except it releases a shared session level advisory lock.
20042 <primary>pg_advisory_unlock_all</primary>
20045 <function>pg_advisory_unlock_all</> will release all session level advisory
20046 locks held by the current session. (This function is implicitly invoked
20047 at session end, even if the client disconnects ungracefully.)
20051 <primary>pg_advisory_xact_lock</primary>
20054 <function>pg_advisory_xact_lock</> works the same as
20055 <function>pg_advisory_lock</>, except the lock is automatically released
20056 at the end of the current transaction and cannot be released explicitly.
20060 <primary>pg_advisory_xact_lock_shared</primary>
20063 <function>pg_advisory_xact_lock_shared</> works the same as
20064 <function>pg_advisory_lock_shared</>, except the lock is automatically released
20065 at the end of the current transaction and cannot be released explicitly.
20069 <primary>pg_try_advisory_xact_lock</primary>
20072 <function>pg_try_advisory_xact_lock</> works the same as
20073 <function>pg_try_advisory_lock</>, except the lock, if acquired,
20074 is automatically released at the end of the current transaction and
20075 cannot be released explicitly.
20079 <primary>pg_try_advisory_xact_lock_shared</primary>
20082 <function>pg_try_advisory_xact_lock_shared</> works the same as
20083 <function>pg_try_advisory_lock_shared</>, except the lock, if acquired,
20084 is automatically released at the end of the current transaction and
20085 cannot be released explicitly.
20092 <sect1 id="functions-trigger">
20093 <title>Trigger Functions</title>
20096 <primary>suppress_redundant_updates_trigger</primary>
20100 Currently <productname>PostgreSQL</> provides one built in trigger
20101 function, <function>suppress_redundant_updates_trigger</>,
20102 which will prevent any update
20103 that does not actually change the data in the row from taking place, in
20104 contrast to the normal behavior which always performs the update
20105 regardless of whether or not the data has changed. (This normal behavior
20106 makes updates run faster, since no checking is required, and is also
20107 useful in certain cases.)
20111 Ideally, you should normally avoid running updates that don't actually
20112 change the data in the record. Redundant updates can cost considerable
20113 unnecessary time, especially if there are lots of indexes to alter,
20114 and space in dead rows that will eventually have to be vacuumed.
20115 However, detecting such situations in client code is not
20116 always easy, or even possible, and writing expressions to detect
20117 them can be error-prone. An alternative is to use
20118 <function>suppress_redundant_updates_trigger</>, which will skip
20119 updates that don't change the data. You should use this with care,
20120 however. The trigger takes a small but non-trivial time for each record,
20121 so if most of the records affected by an update are actually changed,
20122 use of this trigger will actually make the update run slower.
20126 The <function>suppress_redundant_updates_trigger</> function can be
20127 added to a table like this:
20129 CREATE TRIGGER z_min_update
20130 BEFORE UPDATE ON tablename
20131 FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger();
20133 In most cases, you would want to fire this trigger last for each row.
20134 Bearing in mind that triggers fire in name order, you would then
20135 choose a trigger name that comes after the name of any other trigger
20136 you might have on the table.
20139 For more information about creating triggers, see
20140 <xref linkend="SQL-CREATETRIGGER">.
20144 <sect1 id="functions-event-triggers">
20145 <title>Event Trigger Functions</title>
20148 <productname>PostgreSQL</> provides these helper functions
20149 to retrieve information from event triggers.
20153 For more information about event triggers,
20154 see <xref linkend="event-triggers">.
20157 <sect2 id="pg-event-trigger-ddl-command-end-functions">
20158 <title>Capturing Changes at Command End</title>
20161 <primary>pg_event_trigger_ddl_commands</primary>
20165 <function>pg_event_trigger_ddl_commands</> returns a list of
20166 <acronym>DDL</acronym> commands executed by each user action,
20167 when invoked in a function attached to a
20168 <literal>ddl_command_end</> event trigger. If called in any other
20169 context, an error is raised.
20170 <function>pg_event_trigger_ddl_commands</> returns one row for each
20171 base command executed; some commands that are a single SQL sentence
20172 may return more than one row. This function returns the following
20179 <entry>Name</entry>
20180 <entry>Type</entry>
20181 <entry>Description</entry>
20187 <entry><literal>classid</literal></entry>
20188 <entry><type>Oid</type></entry>
20189 <entry>OID of catalog the object belongs in</entry>
20192 <entry><literal>objid</literal></entry>
20193 <entry><type>Oid</type></entry>
20194 <entry>OID of the object in the catalog</entry>
20197 <entry><literal>objsubid</literal></entry>
20198 <entry><type>integer</type></entry>
20199 <entry>Object sub-id (e.g. attribute number for columns)</entry>
20202 <entry><literal>command_tag</literal></entry>
20203 <entry><type>text</type></entry>
20204 <entry>command tag</entry>
20207 <entry><literal>object_type</literal></entry>
20208 <entry><type>text</type></entry>
20209 <entry>Type of the object</entry>
20212 <entry><literal>schema_name</literal></entry>
20213 <entry><type>text</type></entry>
20215 Name of the schema the object belongs in, if any; otherwise <literal>NULL</>.
20216 No quoting is applied.
20220 <entry><literal>object_identity</literal></entry>
20221 <entry><type>text</type></entry>
20223 Text rendering of the object identity, schema-qualified. Each and every
20224 identifier present in the identity is quoted if necessary.
20228 <entry><literal>in_extension</literal></entry>
20229 <entry><type>bool</type></entry>
20230 <entry>whether the command is part of an extension script</entry>
20233 <entry><literal>command</literal></entry>
20234 <entry><type>pg_ddl_command</type></entry>
20236 A complete representation of the command, in internal format.
20237 This cannot be output directly, but it can be passed to other
20238 functions to obtain different pieces of information about the
20248 <sect2 id="pg-event-trigger-sql-drop-functions">
20249 <title>Processing Objects Dropped by a DDL Command</title>
20252 <primary>pg_event_trigger_dropped_objects</primary>
20256 <function>pg_event_trigger_dropped_objects</> returns a list of all objects
20257 dropped by the command in whose <literal>sql_drop</> event it is called.
20258 If called in any other context,
20259 <function>pg_event_trigger_dropped_objects</> raises an error.
20260 <function>pg_event_trigger_dropped_objects</> returns the following columns:
20266 <entry>Name</entry>
20267 <entry>Type</entry>
20268 <entry>Description</entry>
20274 <entry><literal>classid</literal></entry>
20275 <entry><type>Oid</type></entry>
20276 <entry>OID of catalog the object belonged in</entry>
20279 <entry><literal>objid</literal></entry>
20280 <entry><type>Oid</type></entry>
20281 <entry>OID the object had within the catalog</entry>
20284 <entry><literal>objsubid</literal></entry>
20285 <entry><type>int32</type></entry>
20286 <entry>Object sub-id (e.g. attribute number for columns)</entry>
20289 <entry><literal>original</literal></entry>
20290 <entry><type>bool</type></entry>
20291 <entry>Flag used to identify the root object(s) of the deletion</entry>
20294 <entry><literal>normal</literal></entry>
20295 <entry><type>bool</type></entry>
20297 Flag indicating that there's a normal dependency relationship
20298 in the dependency graph leading to this object
20302 <entry><literal>is_temporary</literal></entry>
20303 <entry><type>bool</type></entry>
20305 Flag indicating that the object was a temporary object.
20309 <entry><literal>object_type</literal></entry>
20310 <entry><type>text</type></entry>
20311 <entry>Type of the object</entry>
20314 <entry><literal>schema_name</literal></entry>
20315 <entry><type>text</type></entry>
20317 Name of the schema the object belonged in, if any; otherwise <literal>NULL</>.
20318 No quoting is applied.
20322 <entry><literal>object_name</literal></entry>
20323 <entry><type>text</type></entry>
20325 Name of the object, if the combination of schema and name can be
20326 used as a unique identifier for the object; otherwise <literal>NULL</>.
20327 No quoting is applied, and name is never schema-qualified.
20331 <entry><literal>object_identity</literal></entry>
20332 <entry><type>text</type></entry>
20334 Text rendering of the object identity, schema-qualified. Each and every
20335 identifier present in the identity is quoted if necessary.
20339 <entry><literal>address_names</literal></entry>
20340 <entry><type>text[]</type></entry>
20342 An array that, together with <literal>object_type</literal> and
20343 <literal>address_args</literal>,
20344 can be used by the <function>pg_get_object_address()</function> to
20345 recreate the object address in a remote server containing an
20346 identically named object of the same kind.
20350 <entry><literal>address_args</literal></entry>
20351 <entry><type>text[]</type></entry>
20353 Complement for <literal>address_names</literal> above.
20362 The <function>pg_event_trigger_dropped_objects</> function can be used
20363 in an event trigger like this:
20365 CREATE FUNCTION test_event_trigger_for_drops()
20366 RETURNS event_trigger LANGUAGE plpgsql AS $$
20370 FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects()
20372 RAISE NOTICE '% dropped object: % %.% %',
20377 obj.object_identity;
20381 CREATE EVENT TRIGGER test_event_trigger_for_drops
20383 EXECUTE PROCEDURE test_event_trigger_for_drops();
20388 <sect2 id="pg-event-trigger-table-rewrite-functions">
20389 <title>Handling a Table Rewrite Event</title>
20392 The functions shown in
20393 <xref linkend="functions-event-trigger-table-rewrite">
20394 provide information about a table for which a
20395 <literal>table_rewrite</> event has just been called.
20396 If called in any other context, an error is raised.
20399 <table id="functions-event-trigger-table-rewrite">
20400 <title>Table Rewrite information</title>
20403 <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
20409 <indexterm><primary>pg_event_trigger_table_rewrite_oid</primary></indexterm>
20410 <literal><function>pg_event_trigger_table_rewrite_oid()</function></literal>
20412 <entry><type>Oid</type></entry>
20413 <entry>The OID of the table about to be rewritten.</entry>
20418 <indexterm><primary>pg_event_trigger_table_rewrite_reason</primary></indexterm>
20419 <literal><function>pg_event_trigger_table_rewrite_reason()</function></literal>
20421 <entry><type>int</type></entry>
20423 The reason code(s) explaining the reason for rewriting. The exact
20424 meaning of the codes is release dependent.
20432 The <function>pg_event_trigger_table_rewrite_oid</> function can be used
20433 in an event trigger like this:
20435 CREATE FUNCTION test_event_trigger_table_rewrite_oid()
20436 RETURNS event_trigger
20437 LANGUAGE plpgsql AS
20440 RAISE NOTICE 'rewriting table % for reason %',
20441 pg_event_trigger_table_rewrite_oid()::regclass,
20442 pg_event_trigger_table_rewrite_reason();
20446 CREATE EVENT TRIGGER test_table_rewrite_oid
20448 EXECUTE PROCEDURE test_event_trigger_table_rewrite_oid();