]> granicus.if.org Git - postgresql/blob - doc/src/sgml/func.sgml
Polish the documentation concerning phrase text search.
[postgresql] / doc / src / sgml / func.sgml
1 <!-- doc/src/sgml/func.sgml -->
2
3  <chapter id="functions">
4   <title>Functions and Operators</title>
5
6   <indexterm zone="functions">
7    <primary>function</primary>
8   </indexterm>
9
10   <indexterm zone="functions">
11    <primary>operator</primary>
12   </indexterm>
13
14   <para>
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.
22   </para>
23
24   <para>
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
34    the manual.
35   </para>
36
37
38   <sect1 id="functions-logical">
39    <title>Logical Operators</title>
40
41    <indexterm zone="functions-logical">
42     <primary>operator</primary>
43     <secondary>logical</secondary>
44    </indexterm>
45
46    <indexterm>
47     <primary>Boolean</primary>
48     <secondary>operators</secondary>
49     <see>operators, logical</see>
50    </indexterm>
51
52    <para>
53     The usual logical operators are available:
54
55     <indexterm>
56      <primary>AND (operator)</primary>
57     </indexterm>
58
59     <indexterm>
60      <primary>OR (operator)</primary>
61     </indexterm>
62
63     <indexterm>
64      <primary>NOT (operator)</primary>
65     </indexterm>
66
67     <indexterm>
68      <primary>conjunction</primary>
69     </indexterm>
70
71     <indexterm>
72      <primary>disjunction</primary>
73     </indexterm>
74
75     <indexterm>
76      <primary>negation</primary>
77     </indexterm>
78
79     <simplelist>
80      <member><literal>AND</></member>
81      <member><literal>OR</></member>
82      <member><literal>NOT</></member>
83     </simplelist>
84
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:
88
89     <informaltable>
90      <tgroup cols="4">
91       <thead>
92        <row>
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>
97        </row>
98       </thead>
99
100       <tbody>
101        <row>
102         <entry>TRUE</entry>
103         <entry>TRUE</entry>
104         <entry>TRUE</entry>
105         <entry>TRUE</entry>
106        </row>
107
108        <row>
109         <entry>TRUE</entry>
110         <entry>FALSE</entry>
111         <entry>FALSE</entry>
112         <entry>TRUE</entry>
113        </row>
114
115        <row>
116         <entry>TRUE</entry>
117         <entry>NULL</entry>
118         <entry>NULL</entry>
119         <entry>TRUE</entry>
120        </row>
121
122        <row>
123         <entry>FALSE</entry>
124         <entry>FALSE</entry>
125         <entry>FALSE</entry>
126         <entry>FALSE</entry>
127        </row>
128
129        <row>
130         <entry>FALSE</entry>
131         <entry>NULL</entry>
132         <entry>FALSE</entry>
133         <entry>NULL</entry>
134        </row>
135
136        <row>
137         <entry>NULL</entry>
138         <entry>NULL</entry>
139         <entry>NULL</entry>
140         <entry>NULL</entry>
141        </row>
142       </tbody>
143      </tgroup>
144     </informaltable>
145
146     <informaltable>
147      <tgroup cols="2">
148       <thead>
149        <row>
150         <entry><replaceable>a</replaceable></entry>
151         <entry>NOT <replaceable>a</replaceable></entry>
152        </row>
153       </thead>
154
155       <tbody>
156        <row>
157         <entry>TRUE</entry>
158         <entry>FALSE</entry>
159        </row>
160
161        <row>
162         <entry>FALSE</entry>
163         <entry>TRUE</entry>
164        </row>
165
166        <row>
167         <entry>NULL</entry>
168         <entry>NULL</entry>
169        </row>
170       </tbody>
171      </tgroup>
172     </informaltable>
173    </para>
174
175    <para>
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.
181    </para>
182   </sect1>
183
184   <sect1 id="functions-comparison">
185    <title>Comparison Functions and Operators</title>
186
187    <indexterm zone="functions-comparison">
188     <primary>comparison</primary>
189     <secondary>operators</secondary>
190    </indexterm>
191
192    <para>
193     The usual comparison operators are available, as shown in <xref
194     linkend="functions-comparison-op-table">.
195    </para>
196
197    <table id="functions-comparison-op-table">
198     <title>Comparison Operators</title>
199     <tgroup cols="2">
200      <thead>
201       <row>
202        <entry>Operator</entry>
203        <entry>Description</entry>
204       </row>
205      </thead>
206
207      <tbody>
208       <row>
209        <entry> <literal>&lt;</literal> </entry>
210        <entry>less than</entry>
211       </row>
212
213       <row>
214        <entry> <literal>&gt;</literal> </entry>
215        <entry>greater than</entry>
216       </row>
217
218       <row>
219        <entry> <literal>&lt;=</literal> </entry>
220        <entry>less than or equal to</entry>
221       </row>
222
223       <row>
224        <entry> <literal>&gt;=</literal> </entry>
225        <entry>greater than or equal to</entry>
226       </row>
227
228       <row>
229        <entry> <literal>=</literal> </entry>
230        <entry>equal</entry>
231       </row>
232
233       <row>
234        <entry> <literal>&lt;&gt;</literal> or <literal>!=</literal> </entry>
235        <entry>not equal</entry>
236       </row>
237      </tbody>
238     </tgroup>
239    </table>
240
241    <note>
242     <para>
243      The <literal>!=</literal> operator is converted to
244      <literal>&lt;&gt;</literal> in the parser stage.  It is not
245      possible to implement <literal>!=</literal> and
246      <literal>&lt;&gt;</literal> operators that do different things.
247     </para>
248    </note>
249
250    <para>
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 &lt; 2 &lt; 3</literal> are not valid (because there is
255     no <literal>&lt;</literal> operator to compare a Boolean value with
256     <literal>3</literal>).
257    </para>
258
259    <para>
260     <indexterm>
261      <primary>BETWEEN</primary>
262     </indexterm>
263     In addition to the comparison operators, the special
264     <token>BETWEEN</token> construct is available:
265 <synopsis>
266 <replaceable>a</replaceable> BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
267 </synopsis>
268     is equivalent to
269 <synopsis>
270 <replaceable>a</replaceable> &gt;= <replaceable>x</replaceable> AND <replaceable>a</replaceable> &lt;= <replaceable>y</replaceable>
271 </synopsis>
272     Notice that <token>BETWEEN</token> treats the endpoint values as included
273     in the range.
274     <literal>NOT BETWEEN</literal> does the opposite comparison:
275 <synopsis>
276 <replaceable>a</replaceable> NOT BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
277 </synopsis>
278     is equivalent to
279 <synopsis>
280 <replaceable>a</replaceable> &lt; <replaceable>x</replaceable> OR <replaceable>a</replaceable> &gt; <replaceable>y</replaceable>
281 </synopsis>
282     <indexterm>
283      <primary>BETWEEN SYMMETRIC</primary>
284     </indexterm>
285     <literal>BETWEEN SYMMETRIC</> is the same as <literal>BETWEEN</>
286     except there is no requirement that the argument to the left of
287     <literal>AND</> be less than or equal to the argument on the right.
288     If it is not, those two arguments are automatically swapped, so that
289     a nonempty range is always implied.
290    </para>
291
292    <para>
293     <indexterm>
294      <primary>IS NULL</primary>
295     </indexterm>
296     <indexterm>
297      <primary>IS NOT NULL</primary>
298     </indexterm>
299     <indexterm>
300      <primary>ISNULL</primary>
301     </indexterm>
302     <indexterm>
303      <primary>NOTNULL</primary>
304     </indexterm>
305     To check whether a value is or is not null, use the constructs:
306 <synopsis>
307 <replaceable>expression</replaceable> IS NULL
308 <replaceable>expression</replaceable> IS NOT NULL
309 </synopsis>
310     or the equivalent, but nonstandard, constructs:
311 <synopsis>
312 <replaceable>expression</replaceable> ISNULL
313 <replaceable>expression</replaceable> NOTNULL
314 </synopsis>
315     <indexterm><primary>null value</primary><secondary>comparing</secondary></indexterm>
316    </para>
317
318    <para>
319     Do <emphasis>not</emphasis> write
320     <literal><replaceable>expression</replaceable> = NULL</literal>
321     because <literal>NULL</> is not <quote>equal to</quote>
322     <literal>NULL</>.  (The null value represents an unknown value,
323     and it is not known whether two unknown values are equal.) This
324     behavior conforms to the SQL standard.
325    </para>
326
327   <tip>
328    <para>
329     Some applications might expect that
330     <literal><replaceable>expression</replaceable> = NULL</literal>
331     returns true if <replaceable>expression</replaceable> evaluates to
332     the null value.  It is highly recommended that these applications
333     be modified to comply with the SQL standard. However, if that
334     cannot be done the <xref linkend="guc-transform-null-equals">
335     configuration variable is available. If it is enabled,
336     <productname>PostgreSQL</productname> will convert <literal>x =
337     NULL</literal> clauses to <literal>x IS NULL</literal>.
338    </para>
339   </tip>
340
341   <note>
342    <para>
343     If the <replaceable>expression</replaceable> is row-valued, then
344     <literal>IS NULL</> is true when the row expression itself is null
345     or when all the row's fields are null, while
346     <literal>IS NOT NULL</> is true when the row expression itself is non-null
347     and all the row's fields are non-null.  Because of this behavior,
348     <literal>IS NULL</> and <literal>IS NOT NULL</> do not always return
349     inverse results for row-valued expressions, i.e., a row-valued
350     expression that contains both NULL and non-null values will return false
351     for both tests.
352     This definition conforms to the SQL standard, and is a change from the
353     inconsistent behavior exhibited by <productname>PostgreSQL</productname>
354     versions prior to 8.2.
355    </para>
356   </note>
357
358    <para>
359     <indexterm>
360      <primary>IS DISTINCT FROM</primary>
361     </indexterm>
362     <indexterm>
363      <primary>IS NOT DISTINCT FROM</primary>
364     </indexterm>
365     Ordinary comparison operators yield null (signifying <quote>unknown</>),
366     not true or false, when either input is null.  For example,
367     <literal>7 = NULL</> yields null, as does <literal>7 &lt;&gt; NULL</>.  When
368     this behavior is not suitable, use the
369     <literal>IS <optional> NOT </> DISTINCT FROM</literal> constructs:
370 <synopsis>
371 <replaceable>expression</replaceable> IS DISTINCT FROM <replaceable>expression</replaceable>
372 <replaceable>expression</replaceable> IS NOT DISTINCT FROM <replaceable>expression</replaceable>
373 </synopsis>
374     For non-null inputs, <literal>IS DISTINCT FROM</literal> is
375     the same as the <literal>&lt;&gt;</> operator.  However, if both
376     inputs are null it returns false, and if only one input is
377     null it returns true.  Similarly, <literal>IS NOT DISTINCT
378     FROM</literal> is identical to <literal>=</literal> for non-null
379     inputs, but it returns true when both inputs are null, and false when only
380     one input is null. Thus, these constructs effectively act as though null
381     were a normal data value, rather than <quote>unknown</>.
382    </para>
383
384    <para>
385     <indexterm>
386      <primary>IS TRUE</primary>
387     </indexterm>
388     <indexterm>
389      <primary>IS NOT TRUE</primary>
390     </indexterm>
391     <indexterm>
392      <primary>IS FALSE</primary>
393     </indexterm>
394     <indexterm>
395      <primary>IS NOT FALSE</primary>
396     </indexterm>
397     <indexterm>
398      <primary>IS UNKNOWN</primary>
399     </indexterm>
400     <indexterm>
401      <primary>IS NOT UNKNOWN</primary>
402     </indexterm>
403     Boolean values can also be tested using the constructs
404 <synopsis>
405 <replaceable>expression</replaceable> IS TRUE
406 <replaceable>expression</replaceable> IS NOT TRUE
407 <replaceable>expression</replaceable> IS FALSE
408 <replaceable>expression</replaceable> IS NOT FALSE
409 <replaceable>expression</replaceable> IS UNKNOWN
410 <replaceable>expression</replaceable> IS NOT UNKNOWN
411 </synopsis>
412     These will always return true or false, never a null value, even when the
413     operand is null.
414     A null input is treated as the logical value <quote>unknown</>.
415     Notice that <literal>IS UNKNOWN</> and <literal>IS NOT UNKNOWN</> are
416     effectively the same as <literal>IS NULL</literal> and
417     <literal>IS NOT NULL</literal>, respectively, except that the input
418     expression must be of Boolean type.
419    </para>
420
421 <!-- IS OF does not conform to the ISO SQL behavior, so it is undocumented here
422    <para>
423     <indexterm>
424      <primary>IS OF</primary>
425     </indexterm>
426     <indexterm>
427      <primary>IS NOT OF</primary>
428     </indexterm>
429     It is possible to check the data type of an expression using the
430     constructs
431 <synopsis>
432 <replaceable>expression</replaceable> IS OF (typename, ...)
433 <replaceable>expression</replaceable> IS NOT OF (typename, ...)
434 </synopsis>
435     They return a boolean value based on whether the expression's data
436     type is one of the listed data types.
437    </para>
438 -->
439
440    <para>
441     Some comparison-related functions are also available, as shown in <xref
442     linkend="functions-comparison-func-table">.
443    </para>
444
445   <table id="functions-comparison-func-table">
446     <title>Comparison Functions</title>
447     <tgroup cols="4">
448      <thead>
449       <row>
450        <entry>Function</entry>
451        <entry>Description</entry>
452        <entry>Example</entry>
453        <entry>Example Result</entry>
454       </row>
455      </thead>
456      <tbody>
457       <row>
458        <entry>
459          <indexterm>
460           <primary>num_nonnulls</primary>
461          </indexterm>
462          <literal>num_nonnulls(VARIADIC "any")</literal>
463        </entry>
464        <entry>returns the number of non-NULL arguments</entry>
465        <entry><literal>num_nonnulls(1, NULL, 2)</literal></entry>
466        <entry><literal>2</literal></entry>
467       </row>
468       <row>
469        <entry>
470          <indexterm>
471           <primary>num_nulls</primary>
472          </indexterm>
473          <literal>num_nulls(VARIADIC "any")</literal>
474        </entry>
475        <entry>returns the number of NULL arguments</entry>
476        <entry><literal>num_nulls(1, NULL, 2)</literal></entry>
477        <entry><literal>1</literal></entry>
478       </row>
479      </tbody>
480     </tgroup>
481    </table>
482
483   </sect1>
484
485   <sect1 id="functions-math">
486    <title>Mathematical Functions and Operators</title>
487
488    <para>
489     Mathematical operators are provided for many
490     <productname>PostgreSQL</productname> types. For types without
491     standard mathematical conventions
492     (e.g., date/time types) we
493     describe the actual behavior in subsequent sections.
494    </para>
495
496    <para>
497     <xref linkend="functions-math-op-table"> shows the available mathematical operators.
498    </para>
499
500    <table id="functions-math-op-table">
501     <title>Mathematical Operators</title>
502
503     <tgroup cols="4">
504      <thead>
505       <row>
506        <entry>Operator</entry>
507        <entry>Description</entry>
508        <entry>Example</entry>
509        <entry>Result</entry>
510       </row>
511      </thead>
512
513      <tbody>
514       <row>
515        <entry> <literal>+</literal> </entry>
516        <entry>addition</entry>
517        <entry><literal>2 + 3</literal></entry>
518        <entry><literal>5</literal></entry>
519       </row>
520
521       <row>
522        <entry> <literal>-</literal> </entry>
523        <entry>subtraction</entry>
524        <entry><literal>2 - 3</literal></entry>
525        <entry><literal>-1</literal></entry>
526       </row>
527
528       <row>
529        <entry> <literal>*</literal> </entry>
530        <entry>multiplication</entry>
531        <entry><literal>2 * 3</literal></entry>
532        <entry><literal>6</literal></entry>
533       </row>
534
535       <row>
536        <entry> <literal>/</literal> </entry>
537        <entry>division (integer division truncates the result)</entry>
538        <entry><literal>4 / 2</literal></entry>
539        <entry><literal>2</literal></entry>
540       </row>
541
542       <row>
543        <entry> <literal>%</literal> </entry>
544        <entry>modulo (remainder)</entry>
545        <entry><literal>5 % 4</literal></entry>
546        <entry><literal>1</literal></entry>
547       </row>
548
549       <row>
550        <entry> <literal>^</literal> </entry>
551        <entry>exponentiation (associates left to right)</entry>
552        <entry><literal>2.0 ^ 3.0</literal></entry>
553        <entry><literal>8</literal></entry>
554       </row>
555
556       <row>
557        <entry> <literal>|/</literal> </entry>
558        <entry>square root</entry>
559        <entry><literal>|/ 25.0</literal></entry>
560        <entry><literal>5</literal></entry>
561       </row>
562
563       <row>
564        <entry> <literal>||/</literal> </entry>
565        <entry>cube root</entry>
566        <entry><literal>||/ 27.0</literal></entry>
567        <entry><literal>3</literal></entry>
568       </row>
569
570       <row>
571        <entry> <literal>!</literal> </entry>
572        <entry>factorial</entry>
573        <entry><literal>5 !</literal></entry>
574        <entry><literal>120</literal></entry>
575       </row>
576
577       <row>
578        <entry> <literal>!!</literal> </entry>
579        <entry>factorial (prefix operator)</entry>
580        <entry><literal>!! 5</literal></entry>
581        <entry><literal>120</literal></entry>
582       </row>
583
584       <row>
585        <entry> <literal>@</literal> </entry>
586        <entry>absolute value</entry>
587        <entry><literal>@ -5.0</literal></entry>
588        <entry><literal>5</literal></entry>
589       </row>
590
591       <row>
592        <entry> <literal>&amp;</literal> </entry>
593        <entry>bitwise AND</entry>
594        <entry><literal>91 &amp; 15</literal></entry>
595        <entry><literal>11</literal></entry>
596       </row>
597
598       <row>
599        <entry> <literal>|</literal> </entry>
600        <entry>bitwise OR</entry>
601        <entry><literal>32 | 3</literal></entry>
602        <entry><literal>35</literal></entry>
603       </row>
604
605       <row>
606        <entry> <literal>#</literal> </entry>
607        <entry>bitwise XOR</entry>
608        <entry><literal>17 # 5</literal></entry>
609        <entry><literal>20</literal></entry>
610       </row>
611
612       <row>
613        <entry> <literal>~</literal> </entry>
614        <entry>bitwise NOT</entry>
615        <entry><literal>~1</literal></entry>
616        <entry><literal>-2</literal></entry>
617       </row>
618
619       <row>
620        <entry> <literal>&lt;&lt;</literal> </entry>
621        <entry>bitwise shift left</entry>
622        <entry><literal>1 &lt;&lt; 4</literal></entry>
623        <entry><literal>16</literal></entry>
624       </row>
625
626       <row>
627        <entry> <literal>&gt;&gt;</literal> </entry>
628        <entry>bitwise shift right</entry>
629        <entry><literal>8 &gt;&gt; 2</literal></entry>
630        <entry><literal>2</literal></entry>
631       </row>
632
633      </tbody>
634     </tgroup>
635    </table>
636
637    <para>
638     The bitwise operators work only on integral data types, whereas
639     the others are available for all numeric data types.  The bitwise
640     operators are also available for the bit
641     string types <type>bit</type> and <type>bit varying</type>, as
642     shown in <xref linkend="functions-bit-string-op-table">.
643    </para>
644
645   <para>
646    <xref linkend="functions-math-func-table"> shows the available
647    mathematical functions.  In the table, <literal>dp</literal>
648    indicates <type>double precision</type>.  Many of these functions
649    are provided in multiple forms with different argument types.
650    Except where noted, any given form of a function returns the same
651    data type as its argument.
652    The functions working with <type>double precision</type> data are mostly
653    implemented on top of the host system's C library; accuracy and behavior in
654    boundary cases can therefore vary depending on the host system.
655   </para>
656
657    <table id="functions-math-func-table">
658     <title>Mathematical Functions</title>
659     <tgroup cols="5">
660      <thead>
661       <row>
662        <entry>Function</entry>
663        <entry>Return Type</entry>
664        <entry>Description</entry>
665        <entry>Example</entry>
666        <entry>Result</entry>
667       </row>
668      </thead>
669
670      <tbody>
671       <row>
672        <entry>
673         <indexterm>
674          <primary>abs</primary>
675         </indexterm>
676         <literal><function>abs(<replaceable>x</replaceable>)</function></literal>
677        </entry>
678        <entry>(same as input)</entry>
679        <entry>absolute value</entry>
680        <entry><literal>abs(-17.4)</literal></entry>
681        <entry><literal>17.4</literal></entry>
682       </row>
683
684       <row>
685        <entry>
686         <indexterm>
687          <primary>cbrt</primary>
688         </indexterm>
689         <literal><function>cbrt(<type>dp</type>)</function></literal>
690        </entry>
691        <entry><type>dp</type></entry>
692        <entry>cube root</entry>
693        <entry><literal>cbrt(27.0)</literal></entry>
694        <entry><literal>3</literal></entry>
695       </row>
696
697       <row>
698        <entry>
699         <indexterm>
700          <primary>ceil</primary>
701         </indexterm>
702         <literal><function>ceil(<type>dp</type> or <type>numeric</type>)</function></literal>
703        </entry>
704        <entry>(same as input)</entry>
705        <entry>smallest integer not less than argument</entry>
706        <entry><literal>ceil(-42.8)</literal></entry>
707        <entry><literal>-42</literal></entry>
708       </row>
709
710       <row>
711        <entry>
712         <indexterm>
713          <primary>ceiling</primary>
714         </indexterm>
715         <literal><function>ceiling(<type>dp</type> or <type>numeric</type>)</function></literal>
716        </entry>
717        <entry>(same as input)</entry>
718        <entry>smallest integer not less than argument (alias for <function>ceil</function>)</entry>
719        <entry><literal>ceiling(-95.3)</literal></entry>
720        <entry><literal>-95</literal></entry>
721       </row>
722
723       <row>
724        <entry>
725         <indexterm>
726          <primary>degrees</primary>
727         </indexterm>
728         <literal><function>degrees(<type>dp</type>)</function></literal>
729        </entry>
730        <entry><type>dp</type></entry>
731        <entry>radians to degrees</entry>
732        <entry><literal>degrees(0.5)</literal></entry>
733        <entry><literal>28.6478897565412</literal></entry>
734       </row>
735
736       <row>
737        <entry>
738         <indexterm>
739          <primary>div</primary>
740         </indexterm>
741         <literal><function>div(<parameter>y</parameter> <type>numeric</>,
742          <parameter>x</parameter> <type>numeric</>)</function></literal>
743        </entry>
744        <entry><type>numeric</></entry>
745        <entry>integer quotient of <parameter>y</parameter>/<parameter>x</parameter></entry>
746        <entry><literal>div(9,4)</literal></entry>
747        <entry><literal>2</literal></entry>
748       </row>
749
750       <row>
751        <entry>
752         <indexterm>
753          <primary>exp</primary>
754         </indexterm>
755         <literal><function>exp(<type>dp</type> or <type>numeric</type>)</function></literal>
756        </entry>
757        <entry>(same as input)</entry>
758        <entry>exponential</entry>
759        <entry><literal>exp(1.0)</literal></entry>
760        <entry><literal>2.71828182845905</literal></entry>
761       </row>
762
763       <row>
764        <entry>
765         <indexterm>
766          <primary>floor</primary>
767         </indexterm>
768         <literal><function>floor(<type>dp</type> or <type>numeric</type>)</function></literal>
769        </entry>
770        <entry>(same as input)</entry>
771        <entry>largest integer not greater than argument</entry>
772        <entry><literal>floor(-42.8)</literal></entry>
773        <entry><literal>-43</literal></entry>
774       </row>
775
776       <row>
777        <entry>
778         <indexterm>
779          <primary>ln</primary>
780         </indexterm>
781         <literal><function>ln(<type>dp</type> or <type>numeric</type>)</function></literal>
782        </entry>
783        <entry>(same as input)</entry>
784        <entry>natural logarithm</entry>
785        <entry><literal>ln(2.0)</literal></entry>
786        <entry><literal>0.693147180559945</literal></entry>
787       </row>
788
789       <row>
790        <entry>
791         <indexterm>
792          <primary>log</primary>
793         </indexterm>
794         <literal><function>log(<type>dp</type> or <type>numeric</type>)</function></literal>
795        </entry>
796        <entry>(same as input)</entry>
797        <entry>base 10 logarithm</entry>
798        <entry><literal>log(100.0)</literal></entry>
799        <entry><literal>2</literal></entry>
800       </row>
801
802       <row>
803        <entry><literal><function>log(<parameter>b</parameter> <type>numeric</type>,
804         <parameter>x</parameter> <type>numeric</type>)</function></literal></entry>
805        <entry><type>numeric</type></entry>
806        <entry>logarithm to base <parameter>b</parameter></entry>
807        <entry><literal>log(2.0, 64.0)</literal></entry>
808        <entry><literal>6.0000000000</literal></entry>
809       </row>
810
811       <row>
812        <entry>
813         <indexterm>
814          <primary>mod</primary>
815         </indexterm>
816         <literal><function>mod(<parameter>y</parameter>,
817          <parameter>x</parameter>)</function></literal>
818        </entry>
819        <entry>(same as argument types)</entry>
820        <entry>remainder of <parameter>y</parameter>/<parameter>x</parameter></entry>
821        <entry><literal>mod(9,4)</literal></entry>
822        <entry><literal>1</literal></entry>
823       </row>
824
825       <row>
826        <entry>
827         <indexterm>
828          <primary>pi</primary>
829         </indexterm>
830         <literal><function>pi()</function></literal>
831        </entry>
832        <entry><type>dp</type></entry>
833        <entry><quote>&pi;</quote> constant</entry>
834        <entry><literal>pi()</literal></entry>
835        <entry><literal>3.14159265358979</literal></entry>
836       </row>
837
838       <row>
839        <entry>
840         <indexterm>
841          <primary>power</primary>
842         </indexterm>
843         <literal><function>power(<parameter>a</parameter> <type>dp</type>,
844         <parameter>b</parameter> <type>dp</type>)</function></literal>
845        </entry>
846        <entry><type>dp</type></entry>
847        <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
848        <entry><literal>power(9.0, 3.0)</literal></entry>
849        <entry><literal>729</literal></entry>
850       </row>
851
852       <row>
853        <entry><literal><function>power(<parameter>a</parameter> <type>numeric</type>,
854         <parameter>b</parameter> <type>numeric</type>)</function></literal></entry>
855        <entry><type>numeric</type></entry>
856        <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
857        <entry><literal>power(9.0, 3.0)</literal></entry>
858        <entry><literal>729</literal></entry>
859       </row>
860
861       <row>
862        <entry>
863         <indexterm>
864          <primary>radians</primary>
865         </indexterm>
866         <literal><function>radians(<type>dp</type>)</function></literal>
867        </entry>
868        <entry><type>dp</type></entry>
869        <entry>degrees to radians</entry>
870        <entry><literal>radians(45.0)</literal></entry>
871        <entry><literal>0.785398163397448</literal></entry>
872       </row>
873
874       <row>
875        <entry>
876         <indexterm>
877          <primary>round</primary>
878         </indexterm>
879         <literal><function>round(<type>dp</type> or <type>numeric</type>)</function></literal>
880        </entry>
881        <entry>(same as input)</entry>
882        <entry>round to nearest integer</entry>
883        <entry><literal>round(42.4)</literal></entry>
884        <entry><literal>42</literal></entry>
885       </row>
886
887       <row>
888        <entry><literal><function>round(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</function></literal></entry>
889        <entry><type>numeric</type></entry>
890        <entry>round to <parameter>s</parameter> decimal places</entry>
891        <entry><literal>round(42.4382, 2)</literal></entry>
892        <entry><literal>42.44</literal></entry>
893       </row>
894
895       <row>
896        <entry>
897         <indexterm>
898          <primary>scale</primary>
899         </indexterm>
900         <literal><function>scale(<type>numeric</type>)</function></literal>
901        </entry>
902        <entry><type>numeric</type></entry>
903        <entry>scale of the argument (the number of decimal digits in the fractional part)</entry>
904        <entry><literal>scale(8.41)</literal></entry>
905        <entry><literal>2</literal></entry>
906       </row>
907
908       <row>
909        <entry>
910         <indexterm>
911          <primary>sign</primary>
912         </indexterm>
913         <literal><function>sign(<type>dp</type> or <type>numeric</type>)</function></literal>
914        </entry>
915        <entry>(same as input)</entry>
916        <entry>sign of the argument (-1, 0, +1)</entry>
917        <entry><literal>sign(-8.4)</literal></entry>
918        <entry><literal>-1</literal></entry>
919       </row>
920
921       <row>
922        <entry>
923         <indexterm>
924          <primary>sqrt</primary>
925         </indexterm>
926         <literal><function>sqrt(<type>dp</type> or <type>numeric</type>)</function></literal>
927        </entry>
928        <entry>(same as input)</entry>
929        <entry>square root</entry>
930        <entry><literal>sqrt(2.0)</literal></entry>
931        <entry><literal>1.4142135623731</literal></entry>
932       </row>
933
934       <row>
935        <entry>
936         <indexterm>
937          <primary>trunc</primary>
938         </indexterm>
939         <literal><function>trunc(<type>dp</type> or <type>numeric</type>)</function></literal>
940        </entry>
941        <entry>(same as input)</entry>
942        <entry>truncate toward zero</entry>
943        <entry><literal>trunc(42.8)</literal></entry>
944        <entry><literal>42</literal></entry>
945       </row>
946
947       <row>
948        <entry><literal><function>trunc(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</function></literal></entry>
949        <entry><type>numeric</type></entry>
950        <entry>truncate to <parameter>s</parameter> decimal places</entry>
951        <entry><literal>trunc(42.4382, 2)</literal></entry>
952        <entry><literal>42.43</literal></entry>
953       </row>
954
955       <row>
956        <entry>
957         <indexterm>
958          <primary>width_bucket</primary>
959         </indexterm>
960         <literal><function>width_bucket(<parameter>operand</parameter> <type>dp</type>, <parameter>b1</parameter> <type>dp</type>, <parameter>b2</parameter> <type>dp</type>, <parameter>count</parameter> <type>int</type>)</function></literal></entry>
961        <entry><type>int</type></entry>
962        <entry>return the bucket number to which <parameter>operand</> would
963        be assigned in a histogram having <parameter>count</> equal-width
964        buckets spanning the range <parameter>b1</> to <parameter>b2</>;
965        returns <literal>0</> or <literal><parameter>count</>+1</literal> for
966        an input outside the range</entry>
967        <entry><literal>width_bucket(5.35, 0.024, 10.06, 5)</literal></entry>
968        <entry><literal>3</literal></entry>
969       </row>
970
971       <row>
972        <entry><literal><function>width_bucket(<parameter>operand</parameter> <type>numeric</type>, <parameter>b1</parameter> <type>numeric</type>, <parameter>b2</parameter> <type>numeric</type>, <parameter>count</parameter> <type>int</type>)</function></literal></entry>
973        <entry><type>int</type></entry>
974        <entry>return the bucket number to which <parameter>operand</> would
975        be assigned in a histogram having <parameter>count</> equal-width
976        buckets spanning the range <parameter>b1</> to <parameter>b2</>;
977        returns <literal>0</> or <literal><parameter>count</>+1</literal> for
978        an input outside the range</entry>
979        <entry><literal>width_bucket(5.35, 0.024, 10.06, 5)</literal></entry>
980        <entry><literal>3</literal></entry>
981       </row>
982
983       <row>
984        <entry><literal><function>width_bucket(<parameter>operand</parameter> <type>anyelement</type>, <parameter>thresholds</parameter> <type>anyarray</type>)</function></literal></entry>
985        <entry><type>int</type></entry>
986        <entry>return the bucket number to which <parameter>operand</> would
987        be assigned given an array listing the lower bounds of the buckets;
988        returns <literal>0</> for an input less than the first lower bound;
989        the <parameter>thresholds</> array <emphasis>must be sorted</>,
990        smallest first, or unexpected results will be obtained</entry>
991        <entry><literal>width_bucket(now(), array['yesterday', 'today', 'tomorrow']::timestamptz[])</literal></entry>
992        <entry><literal>2</literal></entry>
993       </row>
994      </tbody>
995     </tgroup>
996    </table>
997
998   <para>
999     <xref linkend="functions-math-random-table"> shows functions for
1000     generating random numbers.
1001   </para>
1002
1003    <table id="functions-math-random-table">
1004     <title>Random Functions</title>
1005
1006     <tgroup cols="3">
1007      <thead>
1008       <row>
1009        <entry>Function</entry>
1010        <entry>Return Type</entry>
1011        <entry>Description</entry>
1012       </row>
1013      </thead>
1014      <tbody>
1015       <row>
1016        <entry>
1017         <indexterm>
1018          <primary>random</primary>
1019         </indexterm>
1020         <literal><function>random()</function></literal>
1021        </entry>
1022        <entry><type>dp</type></entry>
1023        <entry>random value in the range 0.0 &lt;= x &lt; 1.0</entry>
1024       </row>
1025
1026       <row>
1027        <entry>
1028         <indexterm>
1029          <primary>setseed</primary>
1030         </indexterm>
1031         <literal><function>setseed(<type>dp</type>)</function></literal>
1032        </entry>
1033        <entry><type>void</type></entry>
1034        <entry>set seed for subsequent <literal>random()</literal> calls (value between -1.0 and
1035        1.0, inclusive)</entry>
1036       </row>
1037      </tbody>
1038     </tgroup>
1039    </table>
1040
1041   <para>
1042    The characteristics of the values returned by
1043    <literal><function>random()</function></literal> depend
1044    on the system implementation. It is not suitable for cryptographic
1045    applications; see <xref linkend="pgcrypto"> module for an alternative.
1046    </para>
1047
1048   <para>
1049    Finally, <xref linkend="functions-math-trig-table"> shows the
1050    available trigonometric functions.  All trigonometric functions
1051    take arguments and return values of type <type>double
1052    precision</type>.  Each of the trigonometric functions comes in
1053    two variants, one that measures angles in radians and one that
1054    measures angles in degrees.
1055   </para>
1056
1057    <table id="functions-math-trig-table">
1058     <title>Trigonometric Functions</title>
1059
1060     <tgroup cols="3">
1061      <thead>
1062       <row>
1063        <entry>Function (radians)</entry>
1064        <entry>Function (degrees)</entry>
1065        <entry>Description</entry>
1066       </row>
1067      </thead>
1068
1069      <tbody>
1070       <row>
1071        <entry>
1072         <indexterm>
1073          <primary>acos</primary>
1074         </indexterm><literal><function>acos(<replaceable>x</replaceable>)</function></literal>
1075        </entry>
1076        <entry>
1077         <indexterm>
1078          <primary>acosd</primary>
1079         </indexterm><literal><function>acosd(<replaceable>x</replaceable>)</function></literal>
1080        </entry>
1081        <entry>inverse cosine</entry>
1082       </row>
1083
1084       <row>
1085        <entry>
1086         <indexterm>
1087          <primary>asin</primary>
1088         </indexterm>
1089         <literal><function>asin(<replaceable>x</replaceable>)</function></literal>
1090        </entry>
1091        <entry>
1092         <indexterm>
1093          <primary>asind</primary>
1094         </indexterm>
1095         <literal><function>asind(<replaceable>x</replaceable>)</function></literal>
1096        </entry>
1097        <entry>inverse sine</entry>
1098       </row>
1099
1100       <row>
1101        <entry>
1102         <indexterm>
1103          <primary>atan</primary>
1104         </indexterm>
1105         <literal><function>atan(<replaceable>x</replaceable>)</function></literal>
1106        </entry>
1107        <entry>
1108         <indexterm>
1109          <primary>atand</primary>
1110         </indexterm>
1111         <literal><function>atand(<replaceable>x</replaceable>)</function></literal>
1112        </entry>
1113        <entry>inverse tangent</entry>
1114       </row>
1115
1116       <row>
1117        <entry>
1118         <indexterm>
1119          <primary>atan2</primary>
1120         </indexterm>
1121         <literal><function>atan2(<replaceable>y</replaceable>,
1122         <replaceable>x</replaceable>)</function></literal>
1123        </entry>
1124        <entry>
1125         <indexterm>
1126          <primary>atan2d</primary>
1127         </indexterm>
1128         <literal><function>atan2d(<replaceable>y</replaceable>,
1129         <replaceable>x</replaceable>)</function></literal>
1130        </entry>
1131        <entry>inverse tangent of
1132         <literal><replaceable>y</replaceable>/<replaceable>x</replaceable></literal></entry>
1133       </row>
1134
1135       <row>
1136        <entry>
1137         <indexterm>
1138          <primary>cos</primary>
1139         </indexterm>
1140         <literal><function>cos(<replaceable>x</replaceable>)</function></literal>
1141        </entry>
1142        <entry>
1143         <indexterm>
1144          <primary>cosd</primary>
1145         </indexterm>
1146         <literal><function>cosd(<replaceable>x</replaceable>)</function></literal>
1147        </entry>
1148        <entry>cosine</entry>
1149       </row>
1150
1151       <row>
1152        <entry>
1153         <indexterm>
1154          <primary>cot</primary>
1155         </indexterm>
1156         <literal><function>cot(<replaceable>x</replaceable>)</function></literal>
1157        </entry>
1158        <entry>
1159         <indexterm>
1160          <primary>cotd</primary>
1161         </indexterm>
1162         <literal><function>cotd(<replaceable>x</replaceable>)</function></literal>
1163        </entry>
1164        <entry>cotangent</entry>
1165       </row>
1166
1167       <row>
1168        <entry>
1169         <indexterm>
1170          <primary>sin</primary>
1171         </indexterm>
1172         <literal><function>sin(<replaceable>x</replaceable>)</function></literal>
1173        </entry>
1174        <entry>
1175         <indexterm>
1176          <primary>sind</primary>
1177         </indexterm>
1178         <literal><function>sind(<replaceable>x</replaceable>)</function></literal>
1179        </entry>
1180        <entry>sine</entry>
1181       </row>
1182
1183       <row>
1184        <entry>
1185         <indexterm>
1186          <primary>tan</primary>
1187         </indexterm>
1188         <literal><function>tan(<replaceable>x</replaceable>)</function></literal>
1189        </entry>
1190        <entry>
1191         <indexterm>
1192          <primary>tand</primary>
1193         </indexterm>
1194         <literal><function>tand(<replaceable>x</replaceable>)</function></literal>
1195        </entry>
1196        <entry>tangent</entry>
1197       </row>
1198      </tbody>
1199     </tgroup>
1200    </table>
1201
1202   <note>
1203    <para>
1204     Another way to work with angles measured in degrees is to use the unit
1205     transformation functions <literal><function>radians()</function></literal>
1206     and <literal><function>degrees()</function></literal> shown earlier.
1207     However, using the degree-based trigonometric functions is preferred,
1208     as that way avoids roundoff error for special cases such
1209     as <literal>sind(30)</>.
1210    </para>
1211   </note>
1212
1213   </sect1>
1214
1215
1216   <sect1 id="functions-string">
1217    <title>String Functions and Operators</title>
1218
1219    <para>
1220     This section describes functions and operators for examining and
1221     manipulating string values.  Strings in this context include values
1222     of the types <type>character</type>, <type>character varying</type>,
1223     and <type>text</type>.  Unless otherwise noted, all
1224     of the functions listed below work on all of these types, but be
1225     wary of potential effects of automatic space-padding when using the
1226     <type>character</type> type.  Some functions also exist
1227     natively for the bit-string types.
1228    </para>
1229
1230    <para>
1231     <acronym>SQL</acronym> defines some string functions that use
1232     key words, rather than commas, to separate
1233     arguments.  Details are in
1234     <xref linkend="functions-string-sql">.
1235     <productname>PostgreSQL</> also provides versions of these functions
1236     that use the regular function invocation syntax
1237     (see <xref linkend="functions-string-other">).
1238    </para>
1239
1240    <note>
1241     <para>
1242      Before <productname>PostgreSQL</productname> 8.3, these functions would
1243      silently accept values of several non-string data types as well, due to
1244      the presence of implicit coercions from those data types to
1245      <type>text</>.  Those coercions have been removed because they frequently
1246      caused surprising behaviors.  However, the string concatenation operator
1247      (<literal>||</>) still accepts non-string input, so long as at least one
1248      input is of a string type, as shown in <xref
1249      linkend="functions-string-sql">.  For other cases, insert an explicit
1250      coercion to <type>text</> if you need to duplicate the previous behavior.
1251     </para>
1252    </note>
1253
1254    <table id="functions-string-sql">
1255     <title><acronym>SQL</acronym> String Functions and Operators</title>
1256     <tgroup cols="5">
1257      <thead>
1258       <row>
1259        <entry>Function</entry>
1260        <entry>Return Type</entry>
1261        <entry>Description</entry>
1262        <entry>Example</entry>
1263        <entry>Result</entry>
1264       </row>
1265      </thead>
1266
1267      <tbody>
1268       <row>
1269        <entry><literal><parameter>string</parameter> <literal>||</literal>
1270         <parameter>string</parameter></literal></entry>
1271        <entry> <type>text</type> </entry>
1272        <entry>
1273         String concatenation
1274         <indexterm>
1275          <primary>character string</primary>
1276          <secondary>concatenation</secondary>
1277         </indexterm>
1278        </entry>
1279        <entry><literal>'Post' || 'greSQL'</literal></entry>
1280        <entry><literal>PostgreSQL</literal></entry>
1281       </row>
1282
1283       <row>
1284        <entry>
1285         <literal><parameter>string</parameter> <literal>||</literal>
1286         <parameter>non-string</parameter></literal>
1287         or
1288         <literal><parameter>non-string</parameter> <literal>||</literal>
1289         <parameter>string</parameter></literal>
1290        </entry>
1291        <entry> <type>text</type> </entry>
1292        <entry>
1293         String concatenation with one non-string input
1294        </entry>
1295        <entry><literal>'Value: ' || 42</literal></entry>
1296        <entry><literal>Value: 42</literal></entry>
1297       </row>
1298
1299       <row>
1300        <entry>
1301         <indexterm>
1302          <primary>bit_length</primary>
1303         </indexterm>
1304         <literal><function>bit_length(<parameter>string</parameter>)</function></literal>
1305        </entry>
1306        <entry><type>int</type></entry>
1307        <entry>Number of bits in string</entry>
1308        <entry><literal>bit_length('jose')</literal></entry>
1309        <entry><literal>32</literal></entry>
1310       </row>
1311
1312       <row>
1313        <entry>
1314         <indexterm>
1315          <primary>char_length</primary>
1316         </indexterm>
1317         <literal><function>char_length(<parameter>string</parameter>)</function></literal> or <literal><function>character_length(<parameter>string</parameter>)</function></literal>
1318        </entry>
1319        <entry><type>int</type></entry>
1320        <entry>
1321         Number of characters in string
1322         <indexterm>
1323          <primary>character string</primary>
1324          <secondary>length</secondary>
1325         </indexterm>
1326         <indexterm>
1327          <primary>length</primary>
1328          <secondary sortas="character string">of a character string</secondary>
1329          <see>character string, length</see>
1330         </indexterm>
1331        </entry>
1332        <entry><literal>char_length('jose')</literal></entry>
1333        <entry><literal>4</literal></entry>
1334       </row>
1335
1336       <row>
1337        <entry>
1338         <indexterm>
1339          <primary>lower</primary>
1340         </indexterm>
1341         <literal><function>lower(<parameter>string</parameter>)</function></literal>
1342        </entry>
1343        <entry><type>text</type></entry>
1344        <entry>Convert string to lower case</entry>
1345        <entry><literal>lower('TOM')</literal></entry>
1346        <entry><literal>tom</literal></entry>
1347       </row>
1348
1349       <row>
1350        <entry>
1351         <indexterm>
1352          <primary>octet_length</primary>
1353         </indexterm>
1354         <literal><function>octet_length(<parameter>string</parameter>)</function></literal>
1355        </entry>
1356        <entry><type>int</type></entry>
1357        <entry>Number of bytes in string</entry>
1358        <entry><literal>octet_length('jose')</literal></entry>
1359        <entry><literal>4</literal></entry>
1360       </row>
1361
1362       <row>
1363        <entry>
1364         <indexterm>
1365          <primary>overlay</primary>
1366         </indexterm>
1367         <literal><function>overlay(<parameter>string</parameter> placing <parameter>string</parameter> from <type>int</type> <optional>for <type>int</type></optional>)</function></literal>
1368        </entry>
1369        <entry><type>text</type></entry>
1370        <entry>
1371         Replace substring
1372        </entry>
1373        <entry><literal>overlay('Txxxxas' placing 'hom' from 2 for 4)</literal></entry>
1374        <entry><literal>Thomas</literal></entry>
1375       </row>
1376
1377       <row>
1378        <entry>
1379         <indexterm>
1380          <primary>position</primary>
1381         </indexterm>
1382         <literal><function>position(<parameter>substring</parameter> in <parameter>string</parameter>)</function></literal>
1383        </entry>
1384        <entry><type>int</type></entry>
1385        <entry>Location of specified substring</entry>
1386        <entry><literal>position('om' in 'Thomas')</literal></entry>
1387        <entry><literal>3</literal></entry>
1388       </row>
1389
1390       <row>
1391        <entry>
1392         <indexterm>
1393          <primary>substring</primary>
1394         </indexterm>
1395         <literal><function>substring(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</function></literal>
1396        </entry>
1397        <entry><type>text</type></entry>
1398        <entry>
1399         Extract substring
1400        </entry>
1401        <entry><literal>substring('Thomas' from 2 for 3)</literal></entry>
1402        <entry><literal>hom</literal></entry>
1403       </row>
1404
1405       <row>
1406        <entry><literal><function>substring(<parameter>string</parameter> from <replaceable>pattern</replaceable>)</function></literal></entry>
1407        <entry><type>text</type></entry>
1408        <entry>
1409         Extract substring matching POSIX regular expression. See
1410         <xref linkend="functions-matching"> for more information on pattern
1411         matching.
1412        </entry>
1413        <entry><literal>substring('Thomas' from '...$')</literal></entry>
1414        <entry><literal>mas</literal></entry>
1415       </row>
1416
1417       <row>
1418        <entry><literal><function>substring(<parameter>string</parameter> from <replaceable>pattern</replaceable> for <replaceable>escape</replaceable>)</function></literal></entry>
1419        <entry><type>text</type></entry>
1420        <entry>
1421         Extract substring matching <acronym>SQL</acronym> regular expression.
1422         See <xref linkend="functions-matching"> for more information on
1423         pattern matching.
1424        </entry>
1425        <entry><literal>substring('Thomas' from '%#"o_a#"_' for '#')</literal></entry>
1426        <entry><literal>oma</literal></entry>
1427       </row>
1428
1429       <row>
1430        <entry>
1431         <indexterm>
1432          <primary>trim</primary>
1433         </indexterm>
1434         <literal><function>trim(<optional>leading | trailing | both</optional>
1435         <optional><parameter>characters</parameter></optional> from
1436         <parameter>string</parameter>)</function></literal>
1437        </entry>
1438        <entry><type>text</type></entry>
1439        <entry>
1440         Remove the longest string containing only the
1441         <parameter>characters</parameter> (a space by default) from the
1442         start/end/both ends of the <parameter>string</parameter>
1443        </entry>
1444        <entry><literal>trim(both 'x' from 'xTomxx')</literal></entry>
1445        <entry><literal>Tom</literal></entry>
1446       </row>
1447
1448       <row>
1449        <entry>
1450         <literal><function>trim(<optional>leading | trailing
1451         | both</optional> <optional>from</optional>
1452         <parameter>string</parameter>
1453         <optional><parameter>, characters</parameter></optional>
1454         )</function></literal>
1455        </entry>
1456        <entry><type>text</type></entry>
1457        <entry>
1458         Non-standard version of <function>trim()</>
1459        </entry>
1460        <entry><literal>trim(both from 'xTomxx', 'x')</literal></entry>
1461        <entry><literal>Tom</literal></entry>
1462       </row>
1463
1464       <row>
1465        <entry>
1466         <indexterm>
1467          <primary>upper</primary>
1468         </indexterm>
1469         <literal><function>upper(<parameter>string</parameter>)</function></literal>
1470        </entry>
1471        <entry><type>text</type></entry>
1472        <entry>Convert string to upper case</entry>
1473        <entry><literal>upper('tom')</literal></entry>
1474        <entry><literal>TOM</literal></entry>
1475       </row>
1476      </tbody>
1477     </tgroup>
1478    </table>
1479
1480    <para>
1481     Additional string manipulation functions are available and are
1482     listed in <xref linkend="functions-string-other">.  Some of them are used internally to implement the
1483     <acronym>SQL</acronym>-standard string functions listed in <xref linkend="functions-string-sql">.
1484    </para>
1485
1486    <table id="functions-string-other">
1487     <title>Other String Functions</title>
1488     <tgroup cols="5">
1489      <thead>
1490       <row>
1491        <entry>Function</entry>
1492        <entry>Return Type</entry>
1493        <entry>Description</entry>
1494        <entry>Example</entry>
1495        <entry>Result</entry>
1496       </row>
1497      </thead>
1498
1499      <tbody>
1500       <row>
1501        <entry>
1502         <indexterm>
1503          <primary>ascii</primary>
1504         </indexterm>
1505         <literal><function>ascii(<parameter>string</parameter>)</function></literal>
1506        </entry>
1507        <entry><type>int</type></entry>
1508        <entry>
1509         <acronym>ASCII</acronym> code of the first character of the
1510         argument.  For <acronym>UTF8</acronym> returns the Unicode code
1511         point of the character.  For other multibyte encodings, the
1512         argument must be an <acronym>ASCII</acronym> character.
1513        </entry>
1514        <entry><literal>ascii('x')</literal></entry>
1515        <entry><literal>120</literal></entry>
1516       </row>
1517
1518       <row>
1519        <entry>
1520         <indexterm>
1521          <primary>btrim</primary>
1522         </indexterm>
1523         <literal><function>btrim(<parameter>string</parameter> <type>text</type>
1524         <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
1525        </entry>
1526        <entry><type>text</type></entry>
1527        <entry>
1528         Remove the longest string consisting only of characters
1529         in <parameter>characters</parameter> (a space by default)
1530         from the start and end of <parameter>string</parameter>
1531        </entry>
1532        <entry><literal>btrim('xyxtrimyyx', 'xy')</literal></entry>
1533        <entry><literal>trim</literal></entry>
1534       </row>
1535
1536       <row>
1537        <entry>
1538         <indexterm>
1539          <primary>chr</primary>
1540         </indexterm>
1541         <literal><function>chr(<type>int</type>)</function></literal>
1542        </entry>
1543        <entry><type>text</type></entry>
1544        <entry>
1545         Character with the given code. For <acronym>UTF8</acronym> the
1546         argument is treated as a Unicode code point. For other multibyte
1547         encodings the argument must designate an
1548         <acronym>ASCII</acronym> character.  The NULL (0) character is not
1549         allowed because text data types cannot store such bytes.
1550        </entry>
1551        <entry><literal>chr(65)</literal></entry>
1552        <entry><literal>A</literal></entry>
1553       </row>
1554
1555       <row>
1556        <entry>
1557         <indexterm>
1558          <primary>concat</primary>
1559         </indexterm>
1560         <literal><function>concat(<parameter>str</parameter> <type>"any"</type>
1561          [, <parameter>str</parameter> <type>"any"</type> [, ...] ])</function></literal>
1562        </entry>
1563        <entry><type>text</type></entry>
1564        <entry>
1565         Concatenate the text representations of all the arguments.
1566         NULL arguments are ignored.
1567        </entry>
1568        <entry><literal>concat('abcde', 2, NULL, 22)</literal></entry>
1569        <entry><literal>abcde222</literal></entry>
1570       </row>
1571
1572       <row>
1573        <entry>
1574         <indexterm>
1575          <primary>concat_ws</primary>
1576         </indexterm>
1577         <literal><function>concat_ws(<parameter>sep</parameter> <type>text</type>,
1578         <parameter>str</parameter> <type>"any"</type>
1579         [, <parameter>str</parameter> <type>"any"</type> [, ...] ])</function></literal>
1580        </entry>
1581        <entry><type>text</type></entry>
1582        <entry>
1583         Concatenate all but the first argument with separators. The first
1584         argument is used as the separator string. NULL arguments are ignored.
1585        </entry>
1586        <entry><literal>concat_ws(',', 'abcde', 2, NULL, 22)</literal></entry>
1587        <entry><literal>abcde,2,22</literal></entry>
1588       </row>
1589
1590       <row>
1591        <entry>
1592         <indexterm>
1593          <primary>convert</primary>
1594         </indexterm>
1595         <literal><function>convert(<parameter>string</parameter> <type>bytea</type>,
1596         <parameter>src_encoding</parameter> <type>name</type>,
1597         <parameter>dest_encoding</parameter> <type>name</type>)</function></literal>
1598        </entry>
1599        <entry><type>bytea</type></entry>
1600        <entry>
1601         Convert string to <parameter>dest_encoding</parameter>.  The
1602         original encoding is specified by
1603         <parameter>src_encoding</parameter>. The
1604         <parameter>string</parameter> must be valid in this encoding.
1605         Conversions can be defined by <command>CREATE CONVERSION</command>.
1606         Also there are some predefined conversions. See <xref
1607         linkend="conversion-names"> for available conversions.
1608        </entry>
1609        <entry><literal>convert('text_in_utf8', 'UTF8', 'LATIN1')</literal></entry>
1610        <entry><literal>text_in_utf8</literal> represented in Latin-1
1611        encoding (ISO 8859-1)</entry>
1612       </row>
1613
1614       <row>
1615        <entry>
1616         <indexterm>
1617          <primary>convert_from</primary>
1618         </indexterm>
1619         <literal><function>convert_from(<parameter>string</parameter> <type>bytea</type>,
1620         <parameter>src_encoding</parameter> <type>name</type>)</function></literal>
1621        </entry>
1622        <entry><type>text</type></entry>
1623        <entry>
1624         Convert string to the database encoding.  The original encoding
1625         is specified by <parameter>src_encoding</parameter>. The
1626         <parameter>string</parameter> must be valid in this encoding.
1627        </entry>
1628        <entry><literal>convert_from('text_in_utf8', 'UTF8')</literal></entry>
1629        <entry><literal>text_in_utf8</literal> represented in the current database encoding</entry>
1630       </row>
1631
1632       <row>
1633        <entry>
1634         <indexterm>
1635          <primary>convert_to</primary>
1636         </indexterm>
1637         <literal><function>convert_to(<parameter>string</parameter> <type>text</type>,
1638         <parameter>dest_encoding</parameter> <type>name</type>)</function></literal>
1639        </entry>
1640        <entry><type>bytea</type></entry>
1641        <entry>
1642         Convert string to <parameter>dest_encoding</parameter>.
1643        </entry>
1644        <entry><literal>convert_to('some text', 'UTF8')</literal></entry>
1645        <entry><literal>some text</literal> represented in the UTF8 encoding</entry>
1646       </row>
1647
1648       <row>
1649        <entry>
1650         <indexterm>
1651          <primary>decode</primary>
1652         </indexterm>
1653         <literal><function>decode(<parameter>string</parameter> <type>text</type>,
1654         <parameter>format</parameter> <type>text</type>)</function></literal>
1655        </entry>
1656        <entry><type>bytea</type></entry>
1657        <entry>
1658         Decode binary data from textual representation in <parameter>string</>.
1659         Options for <parameter>format</> are same as in <function>encode</>.
1660        </entry>
1661        <entry><literal>decode('MTIzAAE=', 'base64')</literal></entry>
1662        <entry><literal>\x3132330001</literal></entry>
1663       </row>
1664
1665       <row>
1666        <entry>
1667         <indexterm>
1668          <primary>encode</primary>
1669         </indexterm>
1670         <literal><function>encode(<parameter>data</parameter> <type>bytea</type>,
1671         <parameter>format</parameter> <type>text</type>)</function></literal>
1672        </entry>
1673        <entry><type>text</type></entry>
1674        <entry>
1675         Encode binary data into a textual representation.  Supported
1676         formats are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
1677         <literal>escape</> converts zero bytes and high-bit-set bytes to
1678         octal sequences (<literal>\</><replaceable>nnn</>) and
1679         doubles backslashes.
1680        </entry>
1681        <entry><literal>encode(E'123\\000\\001', 'base64')</literal></entry>
1682        <entry><literal>MTIzAAE=</literal></entry>
1683       </row>
1684
1685       <row>
1686        <entry id="format">
1687         <indexterm>
1688          <primary>format</primary>
1689         </indexterm>
1690         <literal><function>format</function>(<parameter>formatstr</parameter> <type>text</type>
1691         [, <parameter>formatarg</parameter> <type>"any"</type> [, ...] ])</literal>
1692        </entry>
1693        <entry><type>text</type></entry>
1694        <entry>
1695          Format arguments according to a format string.
1696          This function is similar to the C function <function>sprintf</>.
1697          See <xref linkend="functions-string-format">.
1698        </entry>
1699        <entry><literal>format('Hello %s, %1$s', 'World')</literal></entry>
1700        <entry><literal>Hello World, World</literal></entry>
1701       </row>
1702
1703       <row>
1704        <entry>
1705         <indexterm>
1706          <primary>initcap</primary>
1707         </indexterm>
1708         <literal><function>initcap(<parameter>string</parameter>)</function></literal>
1709        </entry>
1710        <entry><type>text</type></entry>
1711        <entry>
1712         Convert the first letter of each word to upper case and the
1713         rest to lower case. Words are sequences of alphanumeric
1714         characters separated by non-alphanumeric characters.
1715        </entry>
1716        <entry><literal>initcap('hi THOMAS')</literal></entry>
1717        <entry><literal>Hi Thomas</literal></entry>
1718       </row>
1719
1720       <row>
1721        <entry>
1722         <indexterm>
1723          <primary>left</primary>
1724         </indexterm>
1725         <literal><function>left(<parameter>str</parameter> <type>text</type>,
1726         <parameter>n</parameter> <type>int</type>)</function></literal>
1727        </entry>
1728        <entry><type>text</type></entry>
1729        <entry>
1730         Return first <replaceable>n</> characters in the string. When <replaceable>n</>
1731         is negative, return all but last |<replaceable>n</>| characters.
1732         </entry>
1733        <entry><literal>left('abcde', 2)</literal></entry>
1734        <entry><literal>ab</literal></entry>
1735       </row>
1736
1737       <row>
1738        <entry>
1739         <indexterm>
1740          <primary>length</primary>
1741         </indexterm>
1742         <literal><function>length(<parameter>string</parameter>)</function></literal>
1743        </entry>
1744        <entry><type>int</type></entry>
1745        <entry>
1746         Number of characters in <parameter>string</parameter>
1747        </entry>
1748        <entry><literal>length('jose')</literal></entry>
1749        <entry><literal>4</literal></entry>
1750       </row>
1751
1752       <row>
1753        <entry><literal><function>length(<parameter>string</parameter> <type>bytea</type>,
1754         <parameter>encoding</parameter> <type>name</type> )</function></literal></entry>
1755        <entry><type>int</type></entry>
1756        <entry>
1757         Number of characters in <parameter>string</parameter> in the given
1758         <parameter>encoding</parameter>. The <parameter>string</parameter>
1759         must be valid in this encoding.
1760        </entry>
1761        <entry><literal>length('jose', 'UTF8')</literal></entry>
1762        <entry><literal>4</literal></entry>
1763       </row>
1764
1765       <row>
1766        <entry>
1767         <indexterm>
1768          <primary>lpad</primary>
1769         </indexterm>
1770         <literal><function>lpad(<parameter>string</parameter> <type>text</type>,
1771         <parameter>length</parameter> <type>int</type>
1772         <optional>, <parameter>fill</parameter> <type>text</type></optional>)</function></literal>
1773        </entry>
1774        <entry><type>text</type></entry>
1775        <entry>
1776         Fill up the <parameter>string</parameter> to length
1777         <parameter>length</parameter> by prepending the characters
1778         <parameter>fill</parameter> (a space by default).  If the
1779         <parameter>string</parameter> is already longer than
1780         <parameter>length</parameter> then it is truncated (on the
1781         right).
1782        </entry>
1783        <entry><literal>lpad('hi', 5, 'xy')</literal></entry>
1784        <entry><literal>xyxhi</literal></entry>
1785       </row>
1786
1787       <row>
1788        <entry>
1789         <indexterm>
1790          <primary>ltrim</primary>
1791         </indexterm>
1792         <literal><function>ltrim(<parameter>string</parameter> <type>text</type>
1793         <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
1794        </entry>
1795        <entry><type>text</type></entry>
1796        <entry>
1797         Remove the longest string containing only characters from
1798         <parameter>characters</parameter> (a space by default) from the start of
1799         <parameter>string</parameter>
1800        </entry>
1801        <entry><literal>ltrim('zzzytrim', 'xyz')</literal></entry>
1802        <entry><literal>trim</literal></entry>
1803       </row>
1804
1805       <row>
1806        <entry>
1807         <indexterm>
1808          <primary>md5</primary>
1809         </indexterm>
1810         <literal><function>md5(<parameter>string</parameter>)</function></literal>
1811        </entry>
1812        <entry><type>text</type></entry>
1813        <entry>
1814         Calculates the MD5 hash of <parameter>string</parameter>,
1815         returning the result in hexadecimal
1816        </entry>
1817        <entry><literal>md5('abc')</literal></entry>
1818        <entry><literal>900150983cd24fb0 d6963f7d28e17f72</literal></entry>
1819       </row>
1820
1821       <row>
1822        <entry>
1823         <indexterm>
1824          <primary>parse_ident</primary>
1825         </indexterm>
1826         <literal><function>parse_ident(<parameter>qualified_identifier</parameter> <type>text</type>
1827            [, <parameter>strictmode</parameter> <type>boolean</type> DEFAULT true ] )</function></literal>
1828        </entry>
1829        <entry><type>text[]</type></entry>
1830        <entry>
1831         Split <parameter>qualified_identifier</parameter> into an array of
1832         identifiers, removing any quoting of individual identifiers.  By
1833         default, extra characters after the last identifier are considered an
1834         error; but if the second parameter is <literal>false</>, then such
1835         extra characters are ignored. (This behavior is useful for parsing
1836         names for objects like functions.) Note that this function does not
1837         truncate over-length identifiers. If you want truncation you can cast
1838         the result to <type>name[]</>.
1839        </entry>
1840        <entry><literal>parse_ident('"SomeSchema".someTable')</literal></entry>
1841        <entry><literal>{SomeSchema,sometable}</literal></entry>
1842       </row>
1843
1844       <row>
1845        <entry>
1846         <indexterm>
1847          <primary>pg_client_encoding</primary>
1848         </indexterm>
1849         <literal><function>pg_client_encoding()</function></literal>
1850        </entry>
1851        <entry><type>name</type></entry>
1852        <entry>
1853         Current client encoding name
1854        </entry>
1855        <entry><literal>pg_client_encoding()</literal></entry>
1856        <entry><literal>SQL_ASCII</literal></entry>
1857       </row>
1858
1859       <row>
1860        <entry>
1861         <indexterm>
1862          <primary>quote_ident</primary>
1863         </indexterm>
1864         <literal><function>quote_ident(<parameter>string</parameter> <type>text</type>)</function></literal>
1865        </entry>
1866        <entry><type>text</type></entry>
1867        <entry>
1868         Return the given string suitably quoted to be used as an identifier
1869         in an <acronym>SQL</acronym> statement string.
1870         Quotes are added only if necessary (i.e., if the string contains
1871         non-identifier characters or would be case-folded).
1872         Embedded quotes are properly doubled.
1873         See also <xref linkend="plpgsql-quote-literal-example">.
1874        </entry>
1875        <entry><literal>quote_ident('Foo bar')</literal></entry>
1876        <entry><literal>"Foo bar"</literal></entry>
1877       </row>
1878
1879       <row>
1880        <entry>
1881         <indexterm>
1882          <primary>quote_literal</primary>
1883         </indexterm>
1884         <literal><function>quote_literal(<parameter>string</parameter> <type>text</type>)</function></literal>
1885        </entry>
1886        <entry><type>text</type></entry>
1887        <entry>
1888         Return the given string suitably quoted to be used as a string literal
1889         in an <acronym>SQL</acronym> statement string.
1890         Embedded single-quotes and backslashes are properly doubled.
1891         Note that <function>quote_literal</function> returns null on null
1892         input; if the argument might be null,
1893         <function>quote_nullable</function> is often more suitable.
1894         See also <xref linkend="plpgsql-quote-literal-example">.
1895        </entry>
1896        <entry><literal>quote_literal(E'O\'Reilly')</literal></entry>
1897        <entry><literal>'O''Reilly'</literal></entry>
1898       </row>
1899
1900       <row>
1901        <entry><literal><function>quote_literal(<parameter>value</parameter> <type>anyelement</type>)</function></literal></entry>
1902        <entry><type>text</type></entry>
1903        <entry>
1904         Coerce the given value to text and then quote it as a literal.
1905         Embedded single-quotes and backslashes are properly doubled.
1906        </entry>
1907        <entry><literal>quote_literal(42.5)</literal></entry>
1908        <entry><literal>'42.5'</literal></entry>
1909       </row>
1910
1911       <row>
1912        <entry>
1913         <indexterm>
1914          <primary>quote_nullable</primary>
1915         </indexterm>
1916         <literal><function>quote_nullable(<parameter>string</parameter> <type>text</type>)</function></literal>
1917        </entry>
1918        <entry><type>text</type></entry>
1919        <entry>
1920         Return the given string suitably quoted to be used as a string literal
1921         in an <acronym>SQL</acronym> statement string; or, if the argument
1922         is null, return <literal>NULL</>.
1923         Embedded single-quotes and backslashes are properly doubled.
1924         See also <xref linkend="plpgsql-quote-literal-example">.
1925        </entry>
1926        <entry><literal>quote_nullable(NULL)</literal></entry>
1927        <entry><literal>NULL</literal></entry>
1928       </row>
1929
1930       <row>
1931        <entry><literal><function>quote_nullable(<parameter>value</parameter> <type>anyelement</type>)</function></literal></entry>
1932        <entry><type>text</type></entry>
1933        <entry>
1934         Coerce the given value to text and then quote it as a literal;
1935         or, if the argument is null, return <literal>NULL</>.
1936         Embedded single-quotes and backslashes are properly doubled.
1937        </entry>
1938        <entry><literal>quote_nullable(42.5)</literal></entry>
1939        <entry><literal>'42.5'</literal></entry>
1940       </row>
1941
1942       <row>
1943        <entry>
1944         <indexterm>
1945          <primary>regexp_matches</primary>
1946         </indexterm>
1947         <literal><function>regexp_matches(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
1948        </entry>
1949        <entry><type>setof text[]</type></entry>
1950        <entry>
1951         Return all captured substrings resulting from matching a POSIX regular
1952         expression against the <parameter>string</parameter>. See
1953         <xref linkend="functions-posix-regexp"> for more information.
1954        </entry>
1955        <entry><literal>regexp_matches('foobarbequebaz', '(bar)(beque)')</literal></entry>
1956        <entry><literal>{bar,beque}</literal></entry>
1957       </row>
1958
1959       <row>
1960        <entry>
1961         <indexterm>
1962          <primary>regexp_replace</primary>
1963         </indexterm>
1964         <literal><function>regexp_replace(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type>, <parameter>replacement</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
1965        </entry>
1966        <entry><type>text</type></entry>
1967        <entry>
1968         Replace substring(s) matching a POSIX regular expression. See
1969         <xref linkend="functions-posix-regexp"> for more information.
1970        </entry>
1971        <entry><literal>regexp_replace('Thomas', '.[mN]a.', 'M')</literal></entry>
1972        <entry><literal>ThM</literal></entry>
1973       </row>
1974
1975       <row>
1976        <entry>
1977         <indexterm>
1978          <primary>regexp_split_to_array</primary>
1979         </indexterm>
1980         <literal><function>regexp_split_to_array(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type> ])</function></literal>
1981        </entry>
1982        <entry><type>text[]</type></entry>
1983        <entry>
1984         Split <parameter>string</parameter> using a POSIX regular expression as
1985         the delimiter.  See <xref linkend="functions-posix-regexp"> for more
1986         information.
1987        </entry>
1988        <entry><literal>regexp_split_to_array('hello world', E'\\s+')</literal></entry>
1989        <entry><literal>{hello,world}</literal></entry>
1990       </row>
1991
1992       <row>
1993        <entry>
1994         <indexterm>
1995          <primary>regexp_split_to_table</primary>
1996         </indexterm>
1997         <literal><function>regexp_split_to_table(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
1998        </entry>
1999        <entry><type>setof text</type></entry>
2000        <entry>
2001         Split <parameter>string</parameter> using a POSIX regular expression as
2002         the delimiter.  See <xref linkend="functions-posix-regexp"> for more
2003         information.
2004        </entry>
2005        <entry><literal>regexp_split_to_table('hello world', E'\\s+')</literal></entry>
2006        <entry><literal>hello</literal><para><literal>world</literal></para> (2 rows)</entry>
2007       </row>
2008
2009       <row>
2010        <entry>
2011         <indexterm>
2012          <primary>repeat</primary>
2013         </indexterm>
2014         <literal><function>repeat(<parameter>string</parameter> <type>text</type>, <parameter>number</parameter> <type>int</type>)</function></literal>
2015        </entry>
2016        <entry><type>text</type></entry>
2017        <entry>Repeat <parameter>string</parameter> the specified
2018        <parameter>number</parameter> of times</entry>
2019        <entry><literal>repeat('Pg', 4)</literal></entry>
2020        <entry><literal>PgPgPgPg</literal></entry>
2021       </row>
2022
2023       <row>
2024        <entry>
2025         <indexterm>
2026          <primary>replace</primary>
2027         </indexterm>
2028         <literal><function>replace(<parameter>string</parameter> <type>text</type>,
2029         <parameter>from</parameter> <type>text</type>,
2030         <parameter>to</parameter> <type>text</type>)</function></literal>
2031        </entry>
2032        <entry><type>text</type></entry>
2033        <entry>Replace all occurrences in <parameter>string</parameter> of substring
2034         <parameter>from</parameter> with substring <parameter>to</parameter>
2035        </entry>
2036        <entry><literal>replace('abcdefabcdef', 'cd', 'XX')</literal></entry>
2037        <entry><literal>abXXefabXXef</literal></entry>
2038       </row>
2039
2040       <row>
2041        <entry>
2042         <indexterm>
2043          <primary>reverse</primary>
2044         </indexterm>
2045         <literal><function>reverse(<parameter>str</parameter>)</function></literal>
2046        </entry>
2047        <entry><type>text</type></entry>
2048        <entry>
2049         Return reversed string.
2050        </entry>
2051        <entry><literal>reverse('abcde')</literal></entry>
2052        <entry><literal>edcba</literal></entry>
2053       </row>
2054
2055       <row>
2056        <entry>
2057         <indexterm>
2058          <primary>right</primary>
2059         </indexterm>
2060         <literal><function>right(<parameter>str</parameter> <type>text</type>,
2061          <parameter>n</parameter> <type>int</type>)</function></literal>
2062        </entry>
2063        <entry><type>text</type></entry>
2064        <entry>
2065         Return last <replaceable>n</> characters in the string. When <replaceable>n</>
2066         is negative, return all but first |<replaceable>n</>| characters.
2067        </entry>
2068        <entry><literal>right('abcde', 2)</literal></entry>
2069        <entry><literal>de</literal></entry>
2070       </row>
2071
2072       <row>
2073        <entry>
2074         <indexterm>
2075          <primary>rpad</primary>
2076         </indexterm>
2077         <literal><function>rpad(<parameter>string</parameter> <type>text</type>,
2078         <parameter>length</parameter> <type>int</type>
2079         <optional>, <parameter>fill</parameter> <type>text</type></optional>)</function></literal>
2080        </entry>
2081        <entry><type>text</type></entry>
2082        <entry>
2083         Fill up the <parameter>string</parameter> to length
2084         <parameter>length</parameter> by appending the characters
2085         <parameter>fill</parameter> (a space by default).  If the
2086         <parameter>string</parameter> is already longer than
2087         <parameter>length</parameter> then it is truncated.
2088        </entry>
2089        <entry><literal>rpad('hi', 5, 'xy')</literal></entry>
2090        <entry><literal>hixyx</literal></entry>
2091       </row>
2092
2093       <row>
2094        <entry>
2095         <indexterm>
2096          <primary>rtrim</primary>
2097         </indexterm>
2098         <literal><function>rtrim(<parameter>string</parameter> <type>text</type>
2099          <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
2100        </entry>
2101        <entry><type>text</type></entry>
2102        <entry>
2103         Remove the longest string containing only characters from
2104         <parameter>characters</parameter> (a space by default) from the end of
2105         <parameter>string</parameter>
2106        </entry>
2107        <entry><literal>rtrim('trimxxxx', 'x')</literal></entry>
2108        <entry><literal>trim</literal></entry>
2109       </row>
2110
2111       <row>
2112        <entry>
2113         <indexterm>
2114          <primary>split_part</primary>
2115         </indexterm>
2116         <literal><function>split_part(<parameter>string</parameter> <type>text</type>,
2117         <parameter>delimiter</parameter> <type>text</type>,
2118         <parameter>field</parameter> <type>int</type>)</function></literal>
2119        </entry>
2120        <entry><type>text</type></entry>
2121        <entry>Split <parameter>string</parameter> on <parameter>delimiter</parameter>
2122         and return the given field (counting from one)
2123        </entry>
2124        <entry><literal>split_part('abc~@~def~@~ghi', '~@~', 2)</literal></entry>
2125        <entry><literal>def</literal></entry>
2126       </row>
2127
2128       <row>
2129        <entry>
2130         <indexterm>
2131          <primary>strpos</primary>
2132         </indexterm>
2133         <literal><function>strpos(<parameter>string</parameter>, <parameter>substring</parameter>)</function></literal>
2134        </entry>
2135        <entry><type>int</type></entry>
2136        <entry>
2137         Location of specified substring (same as
2138         <literal>position(<parameter>substring</parameter> in
2139          <parameter>string</parameter>)</literal>, but note the reversed
2140         argument order)
2141        </entry>
2142        <entry><literal>strpos('high', 'ig')</literal></entry>
2143        <entry><literal>2</literal></entry>
2144       </row>
2145
2146       <row>
2147        <entry>
2148         <indexterm>
2149          <primary>substr</primary>
2150         </indexterm>
2151         <literal><function>substr(<parameter>string</parameter>, <parameter>from</parameter> <optional>, <parameter>count</parameter></optional>)</function></literal>
2152        </entry>
2153        <entry><type>text</type></entry>
2154        <entry>
2155         Extract substring (same as
2156         <literal>substring(<parameter>string</parameter> from <parameter>from</parameter> for <parameter>count</parameter>)</literal>)
2157        </entry>
2158        <entry><literal>substr('alphabet', 3, 2)</literal></entry>
2159        <entry><literal>ph</literal></entry>
2160       </row>
2161
2162       <row>
2163        <entry>
2164         <indexterm>
2165          <primary>to_ascii</primary>
2166         </indexterm>
2167         <literal><function>to_ascii(<parameter>string</parameter> <type>text</type>
2168         <optional>, <parameter>encoding</parameter> <type>text</type></optional>)</function></literal>
2169        </entry>
2170        <entry><type>text</type></entry>
2171        <entry>
2172        Convert <parameter>string</parameter> to <acronym>ASCII</acronym> from another encoding
2173        (only supports conversion from  <literal>LATIN1</>, <literal>LATIN2</>, <literal>LATIN9</>,
2174        and <literal>WIN1250</> encodings)
2175        </entry>
2176        <entry><literal>to_ascii('Karel')</literal></entry>
2177        <entry><literal>Karel</literal></entry>
2178       </row>
2179
2180       <row>
2181        <entry>
2182         <indexterm>
2183          <primary>to_hex</primary>
2184         </indexterm>
2185         <literal><function>to_hex(<parameter>number</parameter> <type>int</type>
2186         or <type>bigint</type>)</function></literal>
2187        </entry>
2188        <entry><type>text</type></entry>
2189        <entry>Convert <parameter>number</parameter> to its equivalent hexadecimal
2190         representation
2191        </entry>
2192        <entry><literal>to_hex(2147483647)</literal></entry>
2193        <entry><literal>7fffffff</literal></entry>
2194       </row>
2195
2196       <row>
2197        <entry>
2198         <indexterm>
2199          <primary>translate</primary>
2200         </indexterm>
2201         <literal><function>translate(<parameter>string</parameter> <type>text</type>,
2202         <parameter>from</parameter> <type>text</type>,
2203         <parameter>to</parameter> <type>text</type>)</function></literal>
2204        </entry>
2205        <entry><type>text</type></entry>
2206        <entry>
2207         Any character in <parameter>string</parameter> that matches a
2208         character in the <parameter>from</parameter> set is replaced by
2209         the corresponding character in the <parameter>to</parameter>
2210         set. If <parameter>from</parameter> is longer than
2211         <parameter>to</parameter>, occurrences of the extra characters in
2212         <parameter>from</parameter> are removed.
2213        </entry>
2214        <entry><literal>translate('12345', '143', 'ax')</literal></entry>
2215        <entry><literal>a2x5</literal></entry>
2216       </row>
2217
2218      </tbody>
2219     </tgroup>
2220    </table>
2221
2222    <para>
2223     The <function>concat</function>, <function>concat_ws</function> and
2224     <function>format</function> functions are variadic, so it is possible to
2225     pass the values to be concatenated or formatted as an array marked with
2226     the <literal>VARIADIC</literal> keyword (see <xref
2227     linkend="xfunc-sql-variadic-functions">).  The array's elements are
2228     treated as if they were separate ordinary arguments to the function.
2229     If the variadic array argument is NULL, <function>concat</function>
2230     and <function>concat_ws</function> return NULL, but
2231     <function>format</function> treats a NULL as a zero-element array.
2232    </para>
2233
2234    <para>
2235    See also the aggregate function <function>string_agg</function> in
2236    <xref linkend="functions-aggregate">.
2237    </para>
2238
2239    <table id="conversion-names">
2240     <title>Built-in Conversions</title>
2241     <tgroup cols="3">
2242      <thead>
2243       <row>
2244        <entry>Conversion Name
2245         <footnote>
2246          <para>
2247           The conversion names follow a standard naming scheme: The
2248           official name of the source encoding with all
2249           non-alphanumeric characters replaced by underscores, followed
2250           by <literal>_to_</literal>, followed by the similarly processed
2251           destination encoding name. Therefore, the names might deviate
2252           from the customary encoding names.
2253          </para>
2254         </footnote>
2255        </entry>
2256        <entry>Source Encoding</entry>
2257        <entry>Destination Encoding</entry>
2258       </row>
2259      </thead>
2260
2261      <tbody>
2262       <row>
2263        <entry><literal>ascii_to_mic</literal></entry>
2264        <entry><literal>SQL_ASCII</literal></entry>
2265        <entry><literal>MULE_INTERNAL</literal></entry>
2266       </row>
2267
2268       <row>
2269        <entry><literal>ascii_to_utf8</literal></entry>
2270        <entry><literal>SQL_ASCII</literal></entry>
2271        <entry><literal>UTF8</literal></entry>
2272       </row>
2273
2274       <row>
2275        <entry><literal>big5_to_euc_tw</literal></entry>
2276        <entry><literal>BIG5</literal></entry>
2277        <entry><literal>EUC_TW</literal></entry>
2278       </row>
2279
2280       <row>
2281        <entry><literal>big5_to_mic</literal></entry>
2282        <entry><literal>BIG5</literal></entry>
2283        <entry><literal>MULE_INTERNAL</literal></entry>
2284       </row>
2285
2286       <row>
2287        <entry><literal>big5_to_utf8</literal></entry>
2288        <entry><literal>BIG5</literal></entry>
2289        <entry><literal>UTF8</literal></entry>
2290       </row>
2291
2292       <row>
2293        <entry><literal>euc_cn_to_mic</literal></entry>
2294        <entry><literal>EUC_CN</literal></entry>
2295        <entry><literal>MULE_INTERNAL</literal></entry>
2296       </row>
2297
2298       <row>
2299        <entry><literal>euc_cn_to_utf8</literal></entry>
2300        <entry><literal>EUC_CN</literal></entry>
2301        <entry><literal>UTF8</literal></entry>
2302       </row>
2303
2304       <row>
2305        <entry><literal>euc_jp_to_mic</literal></entry>
2306        <entry><literal>EUC_JP</literal></entry>
2307        <entry><literal>MULE_INTERNAL</literal></entry>
2308       </row>
2309
2310       <row>
2311        <entry><literal>euc_jp_to_sjis</literal></entry>
2312        <entry><literal>EUC_JP</literal></entry>
2313        <entry><literal>SJIS</literal></entry>
2314       </row>
2315
2316       <row>
2317        <entry><literal>euc_jp_to_utf8</literal></entry>
2318        <entry><literal>EUC_JP</literal></entry>
2319        <entry><literal>UTF8</literal></entry>
2320       </row>
2321
2322       <row>
2323        <entry><literal>euc_kr_to_mic</literal></entry>
2324        <entry><literal>EUC_KR</literal></entry>
2325        <entry><literal>MULE_INTERNAL</literal></entry>
2326       </row>
2327
2328       <row>
2329        <entry><literal>euc_kr_to_utf8</literal></entry>
2330        <entry><literal>EUC_KR</literal></entry>
2331        <entry><literal>UTF8</literal></entry>
2332       </row>
2333
2334       <row>
2335        <entry><literal>euc_tw_to_big5</literal></entry>
2336        <entry><literal>EUC_TW</literal></entry>
2337        <entry><literal>BIG5</literal></entry>
2338       </row>
2339
2340       <row>
2341        <entry><literal>euc_tw_to_mic</literal></entry>
2342        <entry><literal>EUC_TW</literal></entry>
2343        <entry><literal>MULE_INTERNAL</literal></entry>
2344       </row>
2345
2346       <row>
2347        <entry><literal>euc_tw_to_utf8</literal></entry>
2348        <entry><literal>EUC_TW</literal></entry>
2349        <entry><literal>UTF8</literal></entry>
2350       </row>
2351
2352       <row>
2353        <entry><literal>gb18030_to_utf8</literal></entry>
2354        <entry><literal>GB18030</literal></entry>
2355        <entry><literal>UTF8</literal></entry>
2356       </row>
2357
2358       <row>
2359        <entry><literal>gbk_to_utf8</literal></entry>
2360        <entry><literal>GBK</literal></entry>
2361        <entry><literal>UTF8</literal></entry>
2362       </row>
2363
2364       <row>
2365        <entry><literal>iso_8859_10_to_utf8</literal></entry>
2366        <entry><literal>LATIN6</literal></entry>
2367        <entry><literal>UTF8</literal></entry>
2368       </row>
2369
2370       <row>
2371        <entry><literal>iso_8859_13_to_utf8</literal></entry>
2372        <entry><literal>LATIN7</literal></entry>
2373        <entry><literal>UTF8</literal></entry>
2374       </row>
2375
2376       <row>
2377        <entry><literal>iso_8859_14_to_utf8</literal></entry>
2378        <entry><literal>LATIN8</literal></entry>
2379        <entry><literal>UTF8</literal></entry>
2380       </row>
2381
2382       <row>
2383        <entry><literal>iso_8859_15_to_utf8</literal></entry>
2384        <entry><literal>LATIN9</literal></entry>
2385        <entry><literal>UTF8</literal></entry>
2386       </row>
2387
2388       <row>
2389        <entry><literal>iso_8859_16_to_utf8</literal></entry>
2390        <entry><literal>LATIN10</literal></entry>
2391        <entry><literal>UTF8</literal></entry>
2392       </row>
2393
2394       <row>
2395        <entry><literal>iso_8859_1_to_mic</literal></entry>
2396        <entry><literal>LATIN1</literal></entry>
2397        <entry><literal>MULE_INTERNAL</literal></entry>
2398       </row>
2399
2400       <row>
2401        <entry><literal>iso_8859_1_to_utf8</literal></entry>
2402        <entry><literal>LATIN1</literal></entry>
2403        <entry><literal>UTF8</literal></entry>
2404       </row>
2405
2406       <row>
2407        <entry><literal>iso_8859_2_to_mic</literal></entry>
2408        <entry><literal>LATIN2</literal></entry>
2409        <entry><literal>MULE_INTERNAL</literal></entry>
2410       </row>
2411
2412       <row>
2413        <entry><literal>iso_8859_2_to_utf8</literal></entry>
2414        <entry><literal>LATIN2</literal></entry>
2415        <entry><literal>UTF8</literal></entry>
2416       </row>
2417
2418       <row>
2419        <entry><literal>iso_8859_2_to_windows_1250</literal></entry>
2420        <entry><literal>LATIN2</literal></entry>
2421        <entry><literal>WIN1250</literal></entry>
2422       </row>
2423
2424       <row>
2425        <entry><literal>iso_8859_3_to_mic</literal></entry>
2426        <entry><literal>LATIN3</literal></entry>
2427        <entry><literal>MULE_INTERNAL</literal></entry>
2428       </row>
2429
2430       <row>
2431        <entry><literal>iso_8859_3_to_utf8</literal></entry>
2432        <entry><literal>LATIN3</literal></entry>
2433        <entry><literal>UTF8</literal></entry>
2434       </row>
2435
2436       <row>
2437        <entry><literal>iso_8859_4_to_mic</literal></entry>
2438        <entry><literal>LATIN4</literal></entry>
2439        <entry><literal>MULE_INTERNAL</literal></entry>
2440       </row>
2441
2442       <row>
2443        <entry><literal>iso_8859_4_to_utf8</literal></entry>
2444        <entry><literal>LATIN4</literal></entry>
2445        <entry><literal>UTF8</literal></entry>
2446       </row>
2447
2448       <row>
2449        <entry><literal>iso_8859_5_to_koi8_r</literal></entry>
2450        <entry><literal>ISO_8859_5</literal></entry>
2451        <entry><literal>KOI8R</literal></entry>
2452       </row>
2453
2454       <row>
2455        <entry><literal>iso_8859_5_to_mic</literal></entry>
2456        <entry><literal>ISO_8859_5</literal></entry>
2457        <entry><literal>MULE_INTERNAL</literal></entry>
2458       </row>
2459
2460       <row>
2461        <entry><literal>iso_8859_5_to_utf8</literal></entry>
2462        <entry><literal>ISO_8859_5</literal></entry>
2463        <entry><literal>UTF8</literal></entry>
2464       </row>
2465
2466       <row>
2467        <entry><literal>iso_8859_5_to_windows_1251</literal></entry>
2468        <entry><literal>ISO_8859_5</literal></entry>
2469        <entry><literal>WIN1251</literal></entry>
2470       </row>
2471
2472       <row>
2473        <entry><literal>iso_8859_5_to_windows_866</literal></entry>
2474        <entry><literal>ISO_8859_5</literal></entry>
2475        <entry><literal>WIN866</literal></entry>
2476       </row>
2477
2478       <row>
2479        <entry><literal>iso_8859_6_to_utf8</literal></entry>
2480        <entry><literal>ISO_8859_6</literal></entry>
2481        <entry><literal>UTF8</literal></entry>
2482       </row>
2483
2484       <row>
2485        <entry><literal>iso_8859_7_to_utf8</literal></entry>
2486        <entry><literal>ISO_8859_7</literal></entry>
2487        <entry><literal>UTF8</literal></entry>
2488       </row>
2489
2490       <row>
2491        <entry><literal>iso_8859_8_to_utf8</literal></entry>
2492        <entry><literal>ISO_8859_8</literal></entry>
2493        <entry><literal>UTF8</literal></entry>
2494       </row>
2495
2496       <row>
2497        <entry><literal>iso_8859_9_to_utf8</literal></entry>
2498        <entry><literal>LATIN5</literal></entry>
2499        <entry><literal>UTF8</literal></entry>
2500       </row>
2501
2502       <row>
2503        <entry><literal>johab_to_utf8</literal></entry>
2504        <entry><literal>JOHAB</literal></entry>
2505        <entry><literal>UTF8</literal></entry>
2506       </row>
2507
2508       <row>
2509        <entry><literal>koi8_r_to_iso_8859_5</literal></entry>
2510        <entry><literal>KOI8R</literal></entry>
2511        <entry><literal>ISO_8859_5</literal></entry>
2512       </row>
2513
2514       <row>
2515        <entry><literal>koi8_r_to_mic</literal></entry>
2516        <entry><literal>KOI8R</literal></entry>
2517        <entry><literal>MULE_INTERNAL</literal></entry>
2518       </row>
2519
2520       <row>
2521        <entry><literal>koi8_r_to_utf8</literal></entry>
2522        <entry><literal>KOI8R</literal></entry>
2523        <entry><literal>UTF8</literal></entry>
2524       </row>
2525
2526       <row>
2527        <entry><literal>koi8_r_to_windows_1251</literal></entry>
2528        <entry><literal>KOI8R</literal></entry>
2529        <entry><literal>WIN1251</literal></entry>
2530       </row>
2531
2532       <row>
2533        <entry><literal>koi8_r_to_windows_866</literal></entry>
2534        <entry><literal>KOI8R</literal></entry>
2535        <entry><literal>WIN866</literal></entry>
2536       </row>
2537
2538       <row>
2539        <entry><literal>koi8_u_to_utf8</literal></entry>
2540        <entry><literal>KOI8U</literal></entry>
2541        <entry><literal>UTF8</literal></entry>
2542       </row>
2543
2544       <row>
2545        <entry><literal>mic_to_ascii</literal></entry>
2546        <entry><literal>MULE_INTERNAL</literal></entry>
2547        <entry><literal>SQL_ASCII</literal></entry>
2548       </row>
2549
2550       <row>
2551        <entry><literal>mic_to_big5</literal></entry>
2552        <entry><literal>MULE_INTERNAL</literal></entry>
2553        <entry><literal>BIG5</literal></entry>
2554       </row>
2555
2556       <row>
2557        <entry><literal>mic_to_euc_cn</literal></entry>
2558        <entry><literal>MULE_INTERNAL</literal></entry>
2559        <entry><literal>EUC_CN</literal></entry>
2560       </row>
2561
2562       <row>
2563        <entry><literal>mic_to_euc_jp</literal></entry>
2564        <entry><literal>MULE_INTERNAL</literal></entry>
2565        <entry><literal>EUC_JP</literal></entry>
2566       </row>
2567
2568       <row>
2569        <entry><literal>mic_to_euc_kr</literal></entry>
2570        <entry><literal>MULE_INTERNAL</literal></entry>
2571        <entry><literal>EUC_KR</literal></entry>
2572       </row>
2573
2574       <row>
2575        <entry><literal>mic_to_euc_tw</literal></entry>
2576        <entry><literal>MULE_INTERNAL</literal></entry>
2577        <entry><literal>EUC_TW</literal></entry>
2578       </row>
2579
2580       <row>
2581        <entry><literal>mic_to_iso_8859_1</literal></entry>
2582        <entry><literal>MULE_INTERNAL</literal></entry>
2583        <entry><literal>LATIN1</literal></entry>
2584       </row>
2585
2586       <row>
2587        <entry><literal>mic_to_iso_8859_2</literal></entry>
2588        <entry><literal>MULE_INTERNAL</literal></entry>
2589        <entry><literal>LATIN2</literal></entry>
2590       </row>
2591
2592       <row>
2593        <entry><literal>mic_to_iso_8859_3</literal></entry>
2594        <entry><literal>MULE_INTERNAL</literal></entry>
2595        <entry><literal>LATIN3</literal></entry>
2596       </row>
2597
2598       <row>
2599        <entry><literal>mic_to_iso_8859_4</literal></entry>
2600        <entry><literal>MULE_INTERNAL</literal></entry>
2601        <entry><literal>LATIN4</literal></entry>
2602       </row>
2603
2604       <row>
2605        <entry><literal>mic_to_iso_8859_5</literal></entry>
2606        <entry><literal>MULE_INTERNAL</literal></entry>
2607        <entry><literal>ISO_8859_5</literal></entry>
2608       </row>
2609
2610       <row>
2611        <entry><literal>mic_to_koi8_r</literal></entry>
2612        <entry><literal>MULE_INTERNAL</literal></entry>
2613        <entry><literal>KOI8R</literal></entry>
2614       </row>
2615
2616       <row>
2617        <entry><literal>mic_to_sjis</literal></entry>
2618        <entry><literal>MULE_INTERNAL</literal></entry>
2619        <entry><literal>SJIS</literal></entry>
2620       </row>
2621
2622       <row>
2623        <entry><literal>mic_to_windows_1250</literal></entry>
2624        <entry><literal>MULE_INTERNAL</literal></entry>
2625        <entry><literal>WIN1250</literal></entry>
2626       </row>
2627
2628       <row>
2629        <entry><literal>mic_to_windows_1251</literal></entry>
2630        <entry><literal>MULE_INTERNAL</literal></entry>
2631        <entry><literal>WIN1251</literal></entry>
2632       </row>
2633
2634       <row>
2635        <entry><literal>mic_to_windows_866</literal></entry>
2636        <entry><literal>MULE_INTERNAL</literal></entry>
2637        <entry><literal>WIN866</literal></entry>
2638       </row>
2639
2640       <row>
2641        <entry><literal>sjis_to_euc_jp</literal></entry>
2642        <entry><literal>SJIS</literal></entry>
2643        <entry><literal>EUC_JP</literal></entry>
2644       </row>
2645
2646       <row>
2647        <entry><literal>sjis_to_mic</literal></entry>
2648        <entry><literal>SJIS</literal></entry>
2649        <entry><literal>MULE_INTERNAL</literal></entry>
2650       </row>
2651
2652       <row>
2653        <entry><literal>sjis_to_utf8</literal></entry>
2654        <entry><literal>SJIS</literal></entry>
2655        <entry><literal>UTF8</literal></entry>
2656       </row>
2657
2658       <row>
2659        <entry><literal>tcvn_to_utf8</literal></entry>
2660        <entry><literal>WIN1258</literal></entry>
2661        <entry><literal>UTF8</literal></entry>
2662       </row>
2663
2664       <row>
2665        <entry><literal>uhc_to_utf8</literal></entry>
2666        <entry><literal>UHC</literal></entry>
2667        <entry><literal>UTF8</literal></entry>
2668       </row>
2669
2670       <row>
2671        <entry><literal>utf8_to_ascii</literal></entry>
2672        <entry><literal>UTF8</literal></entry>
2673        <entry><literal>SQL_ASCII</literal></entry>
2674       </row>
2675
2676       <row>
2677        <entry><literal>utf8_to_big5</literal></entry>
2678        <entry><literal>UTF8</literal></entry>
2679        <entry><literal>BIG5</literal></entry>
2680       </row>
2681
2682       <row>
2683        <entry><literal>utf8_to_euc_cn</literal></entry>
2684        <entry><literal>UTF8</literal></entry>
2685        <entry><literal>EUC_CN</literal></entry>
2686       </row>
2687
2688       <row>
2689        <entry><literal>utf8_to_euc_jp</literal></entry>
2690        <entry><literal>UTF8</literal></entry>
2691        <entry><literal>EUC_JP</literal></entry>
2692       </row>
2693
2694       <row>
2695        <entry><literal>utf8_to_euc_kr</literal></entry>
2696        <entry><literal>UTF8</literal></entry>
2697        <entry><literal>EUC_KR</literal></entry>
2698       </row>
2699
2700       <row>
2701        <entry><literal>utf8_to_euc_tw</literal></entry>
2702        <entry><literal>UTF8</literal></entry>
2703        <entry><literal>EUC_TW</literal></entry>
2704       </row>
2705
2706       <row>
2707        <entry><literal>utf8_to_gb18030</literal></entry>
2708        <entry><literal>UTF8</literal></entry>
2709        <entry><literal>GB18030</literal></entry>
2710       </row>
2711
2712       <row>
2713        <entry><literal>utf8_to_gbk</literal></entry>
2714        <entry><literal>UTF8</literal></entry>
2715        <entry><literal>GBK</literal></entry>
2716       </row>
2717
2718       <row>
2719        <entry><literal>utf8_to_iso_8859_1</literal></entry>
2720        <entry><literal>UTF8</literal></entry>
2721        <entry><literal>LATIN1</literal></entry>
2722       </row>
2723
2724       <row>
2725        <entry><literal>utf8_to_iso_8859_10</literal></entry>
2726        <entry><literal>UTF8</literal></entry>
2727        <entry><literal>LATIN6</literal></entry>
2728       </row>
2729
2730       <row>
2731        <entry><literal>utf8_to_iso_8859_13</literal></entry>
2732        <entry><literal>UTF8</literal></entry>
2733        <entry><literal>LATIN7</literal></entry>
2734       </row>
2735
2736       <row>
2737        <entry><literal>utf8_to_iso_8859_14</literal></entry>
2738        <entry><literal>UTF8</literal></entry>
2739        <entry><literal>LATIN8</literal></entry>
2740       </row>
2741
2742       <row>
2743        <entry><literal>utf8_to_iso_8859_15</literal></entry>
2744        <entry><literal>UTF8</literal></entry>
2745        <entry><literal>LATIN9</literal></entry>
2746       </row>
2747
2748       <row>
2749        <entry><literal>utf8_to_iso_8859_16</literal></entry>
2750        <entry><literal>UTF8</literal></entry>
2751        <entry><literal>LATIN10</literal></entry>
2752       </row>
2753
2754       <row>
2755        <entry><literal>utf8_to_iso_8859_2</literal></entry>
2756        <entry><literal>UTF8</literal></entry>
2757        <entry><literal>LATIN2</literal></entry>
2758       </row>
2759
2760       <row>
2761        <entry><literal>utf8_to_iso_8859_3</literal></entry>
2762        <entry><literal>UTF8</literal></entry>
2763        <entry><literal>LATIN3</literal></entry>
2764       </row>
2765
2766       <row>
2767        <entry><literal>utf8_to_iso_8859_4</literal></entry>
2768        <entry><literal>UTF8</literal></entry>
2769        <entry><literal>LATIN4</literal></entry>
2770       </row>
2771
2772       <row>
2773        <entry><literal>utf8_to_iso_8859_5</literal></entry>
2774        <entry><literal>UTF8</literal></entry>
2775        <entry><literal>ISO_8859_5</literal></entry>
2776       </row>
2777
2778       <row>
2779        <entry><literal>utf8_to_iso_8859_6</literal></entry>
2780        <entry><literal>UTF8</literal></entry>
2781        <entry><literal>ISO_8859_6</literal></entry>
2782       </row>
2783
2784       <row>
2785        <entry><literal>utf8_to_iso_8859_7</literal></entry>
2786        <entry><literal>UTF8</literal></entry>
2787        <entry><literal>ISO_8859_7</literal></entry>
2788       </row>
2789
2790       <row>
2791        <entry><literal>utf8_to_iso_8859_8</literal></entry>
2792        <entry><literal>UTF8</literal></entry>
2793        <entry><literal>ISO_8859_8</literal></entry>
2794       </row>
2795
2796       <row>
2797        <entry><literal>utf8_to_iso_8859_9</literal></entry>
2798        <entry><literal>UTF8</literal></entry>
2799        <entry><literal>LATIN5</literal></entry>
2800       </row>
2801
2802       <row>
2803        <entry><literal>utf8_to_johab</literal></entry>
2804        <entry><literal>UTF8</literal></entry>
2805        <entry><literal>JOHAB</literal></entry>
2806       </row>
2807
2808       <row>
2809        <entry><literal>utf8_to_koi8_r</literal></entry>
2810        <entry><literal>UTF8</literal></entry>
2811        <entry><literal>KOI8R</literal></entry>
2812       </row>
2813
2814       <row>
2815        <entry><literal>utf8_to_koi8_u</literal></entry>
2816        <entry><literal>UTF8</literal></entry>
2817        <entry><literal>KOI8U</literal></entry>
2818       </row>
2819
2820       <row>
2821        <entry><literal>utf8_to_sjis</literal></entry>
2822        <entry><literal>UTF8</literal></entry>
2823        <entry><literal>SJIS</literal></entry>
2824       </row>
2825
2826       <row>
2827        <entry><literal>utf8_to_tcvn</literal></entry>
2828        <entry><literal>UTF8</literal></entry>
2829        <entry><literal>WIN1258</literal></entry>
2830       </row>
2831
2832       <row>
2833        <entry><literal>utf8_to_uhc</literal></entry>
2834        <entry><literal>UTF8</literal></entry>
2835        <entry><literal>UHC</literal></entry>
2836       </row>
2837
2838       <row>
2839        <entry><literal>utf8_to_windows_1250</literal></entry>
2840        <entry><literal>UTF8</literal></entry>
2841        <entry><literal>WIN1250</literal></entry>
2842       </row>
2843
2844       <row>
2845        <entry><literal>utf8_to_windows_1251</literal></entry>
2846        <entry><literal>UTF8</literal></entry>
2847        <entry><literal>WIN1251</literal></entry>
2848       </row>
2849
2850       <row>
2851        <entry><literal>utf8_to_windows_1252</literal></entry>
2852        <entry><literal>UTF8</literal></entry>
2853        <entry><literal>WIN1252</literal></entry>
2854       </row>
2855
2856       <row>
2857        <entry><literal>utf8_to_windows_1253</literal></entry>
2858        <entry><literal>UTF8</literal></entry>
2859        <entry><literal>WIN1253</literal></entry>
2860       </row>
2861
2862       <row>
2863        <entry><literal>utf8_to_windows_1254</literal></entry>
2864        <entry><literal>UTF8</literal></entry>
2865        <entry><literal>WIN1254</literal></entry>
2866       </row>
2867
2868       <row>
2869        <entry><literal>utf8_to_windows_1255</literal></entry>
2870        <entry><literal>UTF8</literal></entry>
2871        <entry><literal>WIN1255</literal></entry>
2872       </row>
2873
2874       <row>
2875        <entry><literal>utf8_to_windows_1256</literal></entry>
2876        <entry><literal>UTF8</literal></entry>
2877        <entry><literal>WIN1256</literal></entry>
2878       </row>
2879
2880       <row>
2881        <entry><literal>utf8_to_windows_1257</literal></entry>
2882        <entry><literal>UTF8</literal></entry>
2883        <entry><literal>WIN1257</literal></entry>
2884       </row>
2885
2886       <row>
2887        <entry><literal>utf8_to_windows_866</literal></entry>
2888        <entry><literal>UTF8</literal></entry>
2889        <entry><literal>WIN866</literal></entry>
2890       </row>
2891
2892       <row>
2893        <entry><literal>utf8_to_windows_874</literal></entry>
2894        <entry><literal>UTF8</literal></entry>
2895        <entry><literal>WIN874</literal></entry>
2896       </row>
2897
2898       <row>
2899        <entry><literal>windows_1250_to_iso_8859_2</literal></entry>
2900        <entry><literal>WIN1250</literal></entry>
2901        <entry><literal>LATIN2</literal></entry>
2902       </row>
2903
2904       <row>
2905        <entry><literal>windows_1250_to_mic</literal></entry>
2906        <entry><literal>WIN1250</literal></entry>
2907        <entry><literal>MULE_INTERNAL</literal></entry>
2908       </row>
2909
2910       <row>
2911        <entry><literal>windows_1250_to_utf8</literal></entry>
2912        <entry><literal>WIN1250</literal></entry>
2913        <entry><literal>UTF8</literal></entry>
2914       </row>
2915
2916       <row>
2917        <entry><literal>windows_1251_to_iso_8859_5</literal></entry>
2918        <entry><literal>WIN1251</literal></entry>
2919        <entry><literal>ISO_8859_5</literal></entry>
2920       </row>
2921
2922       <row>
2923        <entry><literal>windows_1251_to_koi8_r</literal></entry>
2924        <entry><literal>WIN1251</literal></entry>
2925        <entry><literal>KOI8R</literal></entry>
2926       </row>
2927
2928       <row>
2929        <entry><literal>windows_1251_to_mic</literal></entry>
2930        <entry><literal>WIN1251</literal></entry>
2931        <entry><literal>MULE_INTERNAL</literal></entry>
2932       </row>
2933
2934       <row>
2935        <entry><literal>windows_1251_to_utf8</literal></entry>
2936        <entry><literal>WIN1251</literal></entry>
2937        <entry><literal>UTF8</literal></entry>
2938       </row>
2939
2940       <row>
2941        <entry><literal>windows_1251_to_windows_866</literal></entry>
2942        <entry><literal>WIN1251</literal></entry>
2943        <entry><literal>WIN866</literal></entry>
2944       </row>
2945
2946       <row>
2947        <entry><literal>windows_1252_to_utf8</literal></entry>
2948        <entry><literal>WIN1252</literal></entry>
2949        <entry><literal>UTF8</literal></entry>
2950       </row>
2951
2952       <row>
2953        <entry><literal>windows_1256_to_utf8</literal></entry>
2954        <entry><literal>WIN1256</literal></entry>
2955        <entry><literal>UTF8</literal></entry>
2956       </row>
2957
2958       <row>
2959        <entry><literal>windows_866_to_iso_8859_5</literal></entry>
2960        <entry><literal>WIN866</literal></entry>
2961        <entry><literal>ISO_8859_5</literal></entry>
2962       </row>
2963
2964       <row>
2965        <entry><literal>windows_866_to_koi8_r</literal></entry>
2966        <entry><literal>WIN866</literal></entry>
2967        <entry><literal>KOI8R</literal></entry>
2968       </row>
2969
2970       <row>
2971        <entry><literal>windows_866_to_mic</literal></entry>
2972        <entry><literal>WIN866</literal></entry>
2973        <entry><literal>MULE_INTERNAL</literal></entry>
2974       </row>
2975
2976       <row>
2977        <entry><literal>windows_866_to_utf8</literal></entry>
2978        <entry><literal>WIN866</literal></entry>
2979        <entry><literal>UTF8</literal></entry>
2980       </row>
2981
2982       <row>
2983        <entry><literal>windows_866_to_windows_1251</literal></entry>
2984        <entry><literal>WIN866</literal></entry>
2985        <entry><literal>WIN</literal></entry>
2986       </row>
2987
2988       <row>
2989        <entry><literal>windows_874_to_utf8</literal></entry>
2990        <entry><literal>WIN874</literal></entry>
2991        <entry><literal>UTF8</literal></entry>
2992       </row>
2993
2994       <row>
2995        <entry><literal>euc_jis_2004_to_utf8</literal></entry>
2996        <entry><literal>EUC_JIS_2004</literal></entry>
2997        <entry><literal>UTF8</literal></entry>
2998       </row>
2999
3000       <row>
3001        <entry><literal>utf8_to_euc_jis_2004</literal></entry>
3002        <entry><literal>UTF8</literal></entry>
3003        <entry><literal>EUC_JIS_2004</literal></entry>
3004       </row>
3005
3006       <row>
3007        <entry><literal>shift_jis_2004_to_utf8</literal></entry>
3008        <entry><literal>SHIFT_JIS_2004</literal></entry>
3009        <entry><literal>UTF8</literal></entry>
3010       </row>
3011
3012       <row>
3013        <entry><literal>utf8_to_shift_jis_2004</literal></entry>
3014        <entry><literal>UTF8</literal></entry>
3015        <entry><literal>SHIFT_JIS_2004</literal></entry>
3016       </row>
3017
3018       <row>
3019        <entry><literal>euc_jis_2004_to_shift_jis_2004</literal></entry>
3020        <entry><literal>EUC_JIS_2004</literal></entry>
3021        <entry><literal>SHIFT_JIS_2004</literal></entry>
3022       </row>
3023
3024       <row>
3025        <entry><literal>shift_jis_2004_to_euc_jis_2004</literal></entry>
3026        <entry><literal>SHIFT_JIS_2004</literal></entry>
3027        <entry><literal>EUC_JIS_2004</literal></entry>
3028       </row>
3029
3030      </tbody>
3031     </tgroup>
3032    </table>
3033
3034    <sect2 id="functions-string-format">
3035     <title><function>format</function></title>
3036
3037     <indexterm>
3038      <primary>format</primary>
3039     </indexterm>
3040
3041     <para>
3042      The function <function>format</> produces output formatted according to
3043      a format string, in a style similar to the C function
3044      <function>sprintf</>.
3045     </para>
3046
3047     <para>
3048 <synopsis>
3049 <function>format</>(<parameter>formatstr</> <type>text</> [, <parameter>formatarg</> <type>"any"</> [, ...] ])
3050 </synopsis>
3051      <replaceable>formatstr</> is a format string that specifies how the
3052      result should be formatted.  Text in the format string is copied
3053      directly to the result, except where <firstterm>format specifiers</> are
3054      used.  Format specifiers act as placeholders in the string, defining how
3055      subsequent function arguments should be formatted and inserted into the
3056      result.  Each <replaceable>formatarg</> argument is converted to text
3057      according to the usual output rules for its data type, and then formatted
3058      and inserted into the result string according to the format specifier(s).
3059     </para>
3060
3061     <para>
3062      Format specifiers are introduced by a <literal>%</> character and have
3063      the form
3064 <synopsis>
3065 %[<replaceable>position</>][<replaceable>flags</>][<replaceable>width</>]<replaceable>type</>
3066 </synopsis>
3067      where the component fields are:
3068
3069      <variablelist>
3070       <varlistentry>
3071        <term><replaceable>position</replaceable> (optional)</term>
3072        <listitem>
3073         <para>
3074          A string of the form <literal><replaceable>n</>$</> where
3075          <replaceable>n</> is the index of the argument to print.
3076          Index 1 means the first argument after
3077          <replaceable>formatstr</>.  If the <replaceable>position</> is
3078          omitted, the default is to use the next argument in sequence.
3079         </para>
3080        </listitem>
3081       </varlistentry>
3082
3083       <varlistentry>
3084        <term><replaceable>flags</replaceable> (optional)</term>
3085        <listitem>
3086         <para>
3087          Additional options controlling how the format specifier's output is
3088          formatted.  Currently the only supported flag is a minus sign
3089          (<literal>-</>) which will cause the format specifier's output to be
3090          left-justified.  This has no effect unless the <replaceable>width</>
3091          field is also specified.
3092         </para>
3093        </listitem>
3094       </varlistentry>
3095
3096       <varlistentry>
3097        <term><replaceable>width</replaceable> (optional)</term>
3098        <listitem>
3099         <para>
3100          Specifies the <emphasis>minimum</> number of characters to use to
3101          display the format specifier's output.  The output is padded on the
3102          left or right (depending on the <literal>-</> flag) with spaces as
3103          needed to fill the width.  A too-small width does not cause
3104          truncation of the output, but is simply ignored.  The width may be
3105          specified using any of the following: a positive integer; an
3106          asterisk (<literal>*</>) to use the next function argument as the
3107          width; or a string of the form <literal>*<replaceable>n</>$</> to
3108          use the <replaceable>n</>th function argument as the width.
3109         </para>
3110
3111         <para>
3112          If the width comes from a function argument, that argument is
3113          consumed before the argument that is used for the format specifier's
3114          value.  If the width argument is negative, the result is left
3115          aligned (as if the <literal>-</> flag had been specified) within a
3116          field of length <function>abs</>(<replaceable>width</replaceable>).
3117         </para>
3118        </listitem>
3119       </varlistentry>
3120
3121       <varlistentry>
3122        <term><replaceable>type</replaceable> (required)</term>
3123        <listitem>
3124         <para>
3125          The type of format conversion to use to produce the format
3126          specifier's output.  The following types are supported:
3127          <itemizedlist>
3128           <listitem>
3129            <para>
3130             <literal>s</literal> formats the argument value as a simple
3131             string.  A null value is treated as an empty string.
3132            </para>
3133           </listitem>
3134           <listitem>
3135            <para>
3136             <literal>I</literal> treats the argument value as an SQL
3137             identifier, double-quoting it if necessary.
3138             It is an error for the value to be null (equivalent to
3139             <function>quote_ident</>).
3140            </para>
3141           </listitem>
3142           <listitem>
3143            <para>
3144             <literal>L</literal> quotes the argument value as an SQL literal.
3145             A null value is displayed as the string <literal>NULL</>, without
3146             quotes (equivalent to <function>quote_nullable</function>).
3147            </para>
3148           </listitem>
3149          </itemizedlist>
3150         </para>
3151        </listitem>
3152       </varlistentry>
3153      </variablelist>
3154     </para>
3155
3156     <para>
3157      In addition to the format specifiers described above, the special sequence
3158      <literal>%%</> may be used to output a literal <literal>%</> character.
3159     </para>
3160
3161     <para>
3162      Here are some examples of the basic format conversions:
3163
3164 <screen>
3165 SELECT format('Hello %s', 'World');
3166 <lineannotation>Result: </lineannotation><computeroutput>Hello World</computeroutput>
3167
3168 SELECT format('Testing %s, %s, %s, %%', 'one', 'two', 'three');
3169 <lineannotation>Result: </><computeroutput>Testing one, two, three, %</>
3170
3171 SELECT format('INSERT INTO %I VALUES(%L)', 'Foo bar', E'O\'Reilly');
3172 <lineannotation>Result: </lineannotation><computeroutput>INSERT INTO "Foo bar" VALUES('O''Reilly')</computeroutput>
3173
3174 SELECT format('INSERT INTO %I VALUES(%L)', 'locations', E'C:\\Program Files');
3175 <lineannotation>Result: </lineannotation><computeroutput>INSERT INTO locations VALUES(E'C:\\Program Files')</computeroutput>
3176 </screen>
3177     </para>
3178
3179     <para>
3180      Here are examples using <replaceable>width</replaceable> fields
3181      and the <literal>-</> flag:
3182
3183 <screen>
3184 SELECT format('|%10s|', 'foo');
3185 <lineannotation>Result: </><computeroutput>|       foo|</>
3186
3187 SELECT format('|%-10s|', 'foo');
3188 <lineannotation>Result: </><computeroutput>|foo       |</>
3189
3190 SELECT format('|%*s|', 10, 'foo');
3191 <lineannotation>Result: </><computeroutput>|       foo|</>
3192
3193 SELECT format('|%*s|', -10, 'foo');
3194 <lineannotation>Result: </><computeroutput>|foo       |</>
3195
3196 SELECT format('|%-*s|', 10, 'foo');
3197 <lineannotation>Result: </><computeroutput>|foo       |</>
3198
3199 SELECT format('|%-*s|', -10, 'foo');
3200 <lineannotation>Result: </><computeroutput>|foo       |</>
3201 </screen>
3202     </para>
3203
3204     <para>
3205      These examples show use of <replaceable>position</> fields:
3206
3207 <screen>
3208 SELECT format('Testing %3$s, %2$s, %1$s', 'one', 'two', 'three');
3209 <lineannotation>Result: </><computeroutput>Testing three, two, one</>
3210
3211 SELECT format('|%*2$s|', 'foo', 10, 'bar');
3212 <lineannotation>Result: </><computeroutput>|       bar|</>
3213
3214 SELECT format('|%1$*2$s|', 'foo', 10, 'bar');
3215 <lineannotation>Result: </><computeroutput>|       foo|</>
3216 </screen>
3217     </para>
3218
3219     <para>
3220      Unlike the standard C function <function>sprintf</>,
3221      <productname>PostgreSQL</>'s <function>format</> function allows format
3222      specifiers with and without <replaceable>position</> fields to be mixed
3223      in the same format string.  A format specifier without a
3224      <replaceable>position</> field always uses the next argument after the
3225      last argument consumed.
3226      In addition, the <function>format</> function does not require all
3227      function arguments to be used in the format string.
3228      For example:
3229
3230 <screen>
3231 SELECT format('Testing %3$s, %2$s, %s', 'one', 'two', 'three');
3232 <lineannotation>Result: </><computeroutput>Testing three, two, three</>
3233 </screen>
3234     </para>
3235
3236     <para>
3237      The <literal>%I</> and <literal>%L</> format specifiers are particularly
3238      useful for safely constructing dynamic SQL statements.  See
3239      <xref linkend="plpgsql-quote-literal-example">.
3240     </para>
3241    </sect2>
3242
3243   </sect1>
3244
3245
3246   <sect1 id="functions-binarystring">
3247    <title>Binary String Functions and Operators</title>
3248
3249    <indexterm zone="functions-binarystring">
3250     <primary>binary data</primary>
3251     <secondary>functions</secondary>
3252    </indexterm>
3253
3254    <para>
3255     This section describes functions and operators for examining and
3256     manipulating values of type <type>bytea</type>.
3257    </para>
3258
3259    <para>
3260     <acronym>SQL</acronym> defines some string functions that use
3261     key words, rather than commas, to separate
3262     arguments.  Details are in
3263     <xref linkend="functions-binarystring-sql">.
3264     <productname>PostgreSQL</> also provides versions of these functions
3265     that use the regular function invocation syntax
3266     (see <xref linkend="functions-binarystring-other">).
3267    </para>
3268
3269    <note>
3270     <para>
3271      The sample results shown on this page assume that the server parameter
3272      <link linkend="guc-bytea-output"><varname>bytea_output</></link> is set
3273      to <literal>escape</literal> (the traditional PostgreSQL format).
3274     </para>
3275    </note>
3276
3277    <table id="functions-binarystring-sql">
3278     <title><acronym>SQL</acronym> Binary String Functions and Operators</title>
3279     <tgroup cols="5">
3280      <thead>
3281       <row>
3282        <entry>Function</entry>
3283        <entry>Return Type</entry>
3284        <entry>Description</entry>
3285        <entry>Example</entry>
3286        <entry>Result</entry>
3287       </row>
3288      </thead>
3289
3290      <tbody>
3291       <row>
3292        <entry><literal><parameter>string</parameter> <literal>||</literal>
3293         <parameter>string</parameter></literal></entry>
3294        <entry> <type>bytea</type> </entry>
3295        <entry>
3296         String concatenation
3297         <indexterm>
3298          <primary>binary string</primary>
3299          <secondary>concatenation</secondary>
3300         </indexterm>
3301        </entry>
3302        <entry><literal>E'\\\\Post'::bytea || E'\\047gres\\000'::bytea</literal></entry>
3303        <entry><literal>\\Post'gres\000</literal></entry>
3304       </row>
3305
3306       <row>
3307        <entry>
3308         <indexterm>
3309          <primary>octet_length</primary>
3310         </indexterm>
3311         <literal><function>octet_length(<parameter>string</parameter>)</function></literal>
3312        </entry>
3313        <entry><type>int</type></entry>
3314        <entry>Number of bytes in binary string</entry>
3315        <entry><literal>octet_length(E'jo\\000se'::bytea)</literal></entry>
3316        <entry><literal>5</literal></entry>
3317       </row>
3318
3319       <row>
3320        <entry>
3321         <indexterm>
3322          <primary>overlay</primary>
3323         </indexterm>
3324         <literal><function>overlay(<parameter>string</parameter> placing <parameter>string</parameter> from <type>int</type> <optional>for <type>int</type></optional>)</function></literal>
3325        </entry>
3326        <entry><type>bytea</type></entry>
3327        <entry>
3328         Replace substring
3329        </entry>
3330        <entry><literal>overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 2 for 3)</literal></entry>
3331        <entry><literal>T\\002\\003mas</literal></entry>
3332       </row>
3333
3334       <row>
3335        <entry>
3336         <indexterm>
3337          <primary>position</primary>
3338         </indexterm>
3339         <literal><function>position(<parameter>substring</parameter> in <parameter>string</parameter>)</function></literal>
3340        </entry>
3341        <entry><type>int</type></entry>
3342        <entry>Location of specified substring</entry>
3343       <entry><literal>position(E'\\000om'::bytea in E'Th\\000omas'::bytea)</literal></entry>
3344        <entry><literal>3</literal></entry>
3345       </row>
3346
3347       <row>
3348        <entry>
3349         <indexterm>
3350          <primary>substring</primary>
3351         </indexterm>
3352         <literal><function>substring(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</function></literal>
3353        </entry>
3354        <entry><type>bytea</type></entry>
3355        <entry>
3356         Extract substring
3357        </entry>
3358        <entry><literal>substring(E'Th\\000omas'::bytea from 2 for 3)</literal></entry>
3359        <entry><literal>h\000o</literal></entry>
3360       </row>
3361
3362       <row>
3363        <entry>
3364         <indexterm>
3365          <primary>trim</primary>
3366         </indexterm>
3367         <literal><function>trim(<optional>both</optional>
3368         <parameter>bytes</parameter> from
3369         <parameter>string</parameter>)</function></literal>
3370        </entry>
3371        <entry><type>bytea</type></entry>
3372        <entry>
3373         Remove the longest string containing only the bytes in
3374         <parameter>bytes</parameter> from the start
3375         and end of <parameter>string</parameter>
3376        </entry>
3377        <entry><literal>trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea)</literal></entry>
3378        <entry><literal>Tom</literal></entry>
3379       </row>
3380      </tbody>
3381     </tgroup>
3382    </table>
3383
3384    <para>
3385     Additional binary string manipulation functions are available and
3386     are listed in <xref linkend="functions-binarystring-other">.  Some
3387     of them are used internally to implement the
3388     <acronym>SQL</acronym>-standard string functions listed in <xref
3389     linkend="functions-binarystring-sql">.
3390    </para>
3391
3392    <table id="functions-binarystring-other">
3393     <title>Other Binary String Functions</title>
3394     <tgroup cols="5">
3395      <thead>
3396       <row>
3397        <entry>Function</entry>
3398        <entry>Return Type</entry>
3399        <entry>Description</entry>
3400        <entry>Example</entry>
3401        <entry>Result</entry>
3402       </row>
3403      </thead>
3404
3405      <tbody>
3406       <row>
3407        <entry>
3408         <indexterm>
3409          <primary>btrim</primary>
3410         </indexterm>
3411         <literal><function>btrim(<parameter>string</parameter>
3412         <type>bytea</type>, <parameter>bytes</parameter> <type>bytea</type>)</function></literal>
3413        </entry>
3414        <entry><type>bytea</type></entry>
3415        <entry>
3416         Remove the longest string consisting only of bytes
3417         in <parameter>bytes</parameter> from the start and end of
3418         <parameter>string</parameter>
3419       </entry>
3420       <entry><literal>btrim(E'\\000trim\\000'::bytea, E'\\000'::bytea)</literal></entry>
3421       <entry><literal>trim</literal></entry>
3422      </row>
3423
3424      <row>
3425       <entry>
3426         <indexterm>
3427          <primary>decode</primary>
3428         </indexterm>
3429        <literal><function>decode(<parameter>string</parameter> <type>text</type>,
3430        <parameter>format</parameter> <type>text</type>)</function></literal>
3431       </entry>
3432       <entry><type>bytea</type></entry>
3433       <entry>
3434        Decode binary data from textual representation in <parameter>string</>.
3435        Options for <parameter>format</> are same as in <function>encode</>.
3436       </entry>
3437       <entry><literal>decode(E'123\\000456', 'escape')</literal></entry>
3438       <entry><literal>123\000456</literal></entry>
3439      </row>
3440
3441      <row>
3442       <entry>
3443         <indexterm>
3444          <primary>encode</primary>
3445         </indexterm>
3446        <literal><function>encode(<parameter>data</parameter> <type>bytea</type>,
3447        <parameter>format</parameter> <type>text</type>)</function></literal>
3448       </entry>
3449       <entry><type>text</type></entry>
3450       <entry>
3451        Encode binary data into a textual representation.  Supported
3452        formats are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
3453        <literal>escape</> converts zero bytes and high-bit-set bytes to
3454        octal sequences (<literal>\</><replaceable>nnn</>) and
3455        doubles backslashes.
3456       </entry>
3457       <entry><literal>encode(E'123\\000456'::bytea, 'escape')</literal></entry>
3458       <entry><literal>123\000456</literal></entry>
3459      </row>
3460
3461       <row>
3462        <entry>
3463         <indexterm>
3464          <primary>get_bit</primary>
3465         </indexterm>
3466         <literal><function>get_bit(<parameter>string</parameter>, <parameter>offset</parameter>)</function></literal>
3467        </entry>
3468        <entry><type>int</type></entry>
3469        <entry>
3470         Extract bit from string
3471        </entry>
3472        <entry><literal>get_bit(E'Th\\000omas'::bytea, 45)</literal></entry>
3473        <entry><literal>1</literal></entry>
3474       </row>
3475
3476       <row>
3477        <entry>
3478         <indexterm>
3479          <primary>get_byte</primary>
3480         </indexterm>
3481         <literal><function>get_byte(<parameter>string</parameter>, <parameter>offset</parameter>)</function></literal>
3482        </entry>
3483        <entry><type>int</type></entry>
3484        <entry>
3485         Extract byte from string
3486        </entry>
3487        <entry><literal>get_byte(E'Th\\000omas'::bytea, 4)</literal></entry>
3488        <entry><literal>109</literal></entry>
3489       </row>
3490
3491      <row>
3492       <entry>
3493        <indexterm>
3494         <primary>length</primary>
3495        </indexterm>
3496        <literal><function>length(<parameter>string</parameter>)</function></literal>
3497       </entry>
3498       <entry><type>int</type></entry>
3499       <entry>
3500        Length of binary string
3501        <indexterm>
3502         <primary>binary string</primary>
3503         <secondary>length</secondary>
3504        </indexterm>
3505        <indexterm>
3506         <primary>length</primary>
3507         <secondary sortas="binary string">of a binary string</secondary>
3508         <see>binary strings, length</see>
3509        </indexterm>
3510       </entry>
3511       <entry><literal>length(E'jo\\000se'::bytea)</literal></entry>
3512       <entry><literal>5</literal></entry>
3513      </row>
3514
3515      <row>
3516       <entry>
3517        <indexterm>
3518         <primary>md5</primary>
3519        </indexterm>
3520        <literal><function>md5(<parameter>string</parameter>)</function></literal>
3521       </entry>
3522       <entry><type>text</type></entry>
3523       <entry>
3524        Calculates the MD5 hash of <parameter>string</parameter>,
3525        returning the result in hexadecimal
3526       </entry>
3527       <entry><literal>md5(E'Th\\000omas'::bytea)</literal></entry>
3528       <entry><literal>8ab2d3c9689aaf18 b4958c334c82d8b1</literal></entry>
3529      </row>
3530
3531       <row>
3532        <entry>
3533         <indexterm>
3534          <primary>set_bit</primary>
3535         </indexterm>
3536         <literal><function>set_bit(<parameter>string</parameter>,
3537         <parameter>offset</parameter>, <parameter>newvalue</>)</function></literal>
3538        </entry>
3539        <entry><type>bytea</type></entry>
3540        <entry>
3541         Set bit in string
3542        </entry>
3543        <entry><literal>set_bit(E'Th\\000omas'::bytea, 45, 0)</literal></entry>
3544        <entry><literal>Th\000omAs</literal></entry>
3545       </row>
3546
3547       <row>
3548        <entry>
3549         <indexterm>
3550          <primary>set_byte</primary>
3551         </indexterm>
3552         <literal><function>set_byte(<parameter>string</parameter>,
3553         <parameter>offset</parameter>, <parameter>newvalue</>)</function></literal>
3554        </entry>
3555        <entry><type>bytea</type></entry>
3556        <entry>
3557         Set byte in string
3558        </entry>
3559        <entry><literal>set_byte(E'Th\\000omas'::bytea, 4, 64)</literal></entry>
3560        <entry><literal>Th\000o@as</literal></entry>
3561       </row>
3562     </tbody>
3563    </tgroup>
3564   </table>
3565
3566   <para>
3567    <function>get_byte</> and <function>set_byte</> number the first byte
3568    of a binary string as byte 0.
3569    <function>get_bit</> and <function>set_bit</> number bits from the
3570    right within each byte; for example bit 0 is the least significant bit of
3571    the first byte, and bit 15 is the most significant bit of the second byte.
3572   </para>
3573
3574   <para>
3575    See also the aggregate function <function>string_agg</function> in
3576    <xref linkend="functions-aggregate"> and the large object functions
3577    in <xref linkend="lo-funcs">.
3578   </para>
3579  </sect1>
3580
3581
3582   <sect1 id="functions-bitstring">
3583    <title>Bit String Functions and Operators</title>
3584
3585    <indexterm zone="functions-bitstring">
3586     <primary>bit strings</primary>
3587     <secondary>functions</secondary>
3588    </indexterm>
3589
3590    <para>
3591     This section describes functions and operators for examining and
3592     manipulating bit strings, that is values of the types
3593     <type>bit</type> and <type>bit varying</type>.  Aside from the
3594     usual comparison operators, the operators
3595     shown in <xref linkend="functions-bit-string-op-table"> can be used.
3596     Bit string operands of <literal>&amp;</literal>, <literal>|</literal>,
3597     and <literal>#</literal> must be of equal length.  When bit
3598     shifting, the original length of the string is preserved, as shown
3599     in the examples.
3600    </para>
3601
3602    <table id="functions-bit-string-op-table">
3603     <title>Bit String Operators</title>
3604
3605     <tgroup cols="4">
3606      <thead>
3607       <row>
3608        <entry>Operator</entry>
3609        <entry>Description</entry>
3610        <entry>Example</entry>
3611        <entry>Result</entry>
3612       </row>
3613      </thead>
3614
3615      <tbody>
3616       <row>
3617        <entry> <literal>||</literal> </entry>
3618        <entry>concatenation</entry>
3619        <entry><literal>B'10001' || B'011'</literal></entry>
3620        <entry><literal>10001011</literal></entry>
3621       </row>
3622
3623       <row>
3624        <entry> <literal>&amp;</literal> </entry>
3625        <entry>bitwise AND</entry>
3626        <entry><literal>B'10001' &amp; B'01101'</literal></entry>
3627        <entry><literal>00001</literal></entry>
3628       </row>
3629
3630       <row>
3631        <entry> <literal>|</literal> </entry>
3632        <entry>bitwise OR</entry>
3633        <entry><literal>B'10001' | B'01101'</literal></entry>
3634        <entry><literal>11101</literal></entry>
3635       </row>
3636
3637       <row>
3638        <entry> <literal>#</literal> </entry>
3639        <entry>bitwise XOR</entry>
3640        <entry><literal>B'10001' # B'01101'</literal></entry>
3641        <entry><literal>11100</literal></entry>
3642       </row>
3643
3644       <row>
3645        <entry> <literal>~</literal> </entry>
3646        <entry>bitwise NOT</entry>
3647        <entry><literal>~ B'10001'</literal></entry>
3648        <entry><literal>01110</literal></entry>
3649       </row>
3650
3651       <row>
3652        <entry> <literal>&lt;&lt;</literal> </entry>
3653        <entry>bitwise shift left</entry>
3654        <entry><literal>B'10001' &lt;&lt; 3</literal></entry>
3655        <entry><literal>01000</literal></entry>
3656       </row>
3657
3658       <row>
3659        <entry> <literal>&gt;&gt;</literal> </entry>
3660        <entry>bitwise shift right</entry>
3661        <entry><literal>B'10001' &gt;&gt; 2</literal></entry>
3662        <entry><literal>00100</literal></entry>
3663       </row>
3664      </tbody>
3665     </tgroup>
3666    </table>
3667
3668    <para>
3669     The following <acronym>SQL</acronym>-standard functions work on bit
3670     strings as well as character strings:
3671     <literal><function>length</function></literal>,
3672     <literal><function>bit_length</function></literal>,
3673     <literal><function>octet_length</function></literal>,
3674     <literal><function>position</function></literal>,
3675     <literal><function>substring</function></literal>,
3676     <literal><function>overlay</function></literal>.
3677    </para>
3678
3679    <para>
3680     The following functions work on bit strings as well as binary
3681     strings:
3682     <literal><function>get_bit</function></literal>,
3683     <literal><function>set_bit</function></literal>.
3684     When working with a bit string, these functions number the first
3685     (leftmost) bit of the string as bit 0.
3686    </para>
3687
3688    <para>
3689     In addition, it is possible to cast integral values to and from type
3690     <type>bit</>.
3691     Some examples:
3692 <programlisting>
3693 44::bit(10)                    <lineannotation>0000101100</lineannotation>
3694 44::bit(3)                     <lineannotation>100</lineannotation>
3695 cast(-44 as bit(12))           <lineannotation>111111010100</lineannotation>
3696 '1110'::bit(4)::integer        <lineannotation>14</lineannotation>
3697 </programlisting>
3698     Note that casting to just <quote>bit</> means casting to
3699     <literal>bit(1)</>, and so will deliver only the least significant
3700     bit of the integer.
3701    </para>
3702
3703     <note>
3704      <para>
3705       Casting an integer to <type>bit(n)</> copies the rightmost
3706       <literal>n</> bits.  Casting an integer to a bit string width wider
3707       than the integer itself will sign-extend on the left.
3708      </para>
3709     </note>
3710
3711   </sect1>
3712
3713
3714  <sect1 id="functions-matching">
3715   <title>Pattern Matching</title>
3716
3717   <indexterm zone="functions-matching">
3718    <primary>pattern matching</primary>
3719   </indexterm>
3720
3721    <para>
3722     There are three separate approaches to pattern matching provided
3723     by <productname>PostgreSQL</productname>: the traditional
3724     <acronym>SQL</acronym> <function>LIKE</function> operator, the
3725     more recent <function>SIMILAR TO</function> operator (added in
3726     SQL:1999), and <acronym>POSIX</acronym>-style regular
3727     expressions.  Aside from the basic <quote>does this string match
3728     this pattern?</> operators, functions are available to extract
3729     or replace matching substrings and to split a string at matching
3730     locations.
3731    </para>
3732
3733    <tip>
3734     <para>
3735      If you have pattern matching needs that go beyond this,
3736      consider writing a user-defined function in Perl or Tcl.
3737     </para>
3738    </tip>
3739
3740    <caution>
3741     <para>
3742      While most regular-expression searches can be executed very quickly,
3743      regular expressions can be contrived that take arbitrary amounts of
3744      time and memory to process.  Be wary of accepting regular-expression
3745      search patterns from hostile sources.  If you must do so, it is
3746      advisable to impose a statement timeout.
3747     </para>
3748
3749     <para>
3750      Searches using <function>SIMILAR TO</function> patterns have the same
3751      security hazards, since <function>SIMILAR TO</function> provides many
3752      of the same capabilities as <acronym>POSIX</acronym>-style regular
3753      expressions.
3754     </para>
3755
3756     <para>
3757      <function>LIKE</function> searches, being much simpler than the other
3758      two options, are safer to use with possibly-hostile pattern sources.
3759     </para>
3760    </caution>
3761
3762   <sect2 id="functions-like">
3763    <title><function>LIKE</function></title>
3764
3765    <indexterm>
3766     <primary>LIKE</primary>
3767    </indexterm>
3768
3769 <synopsis>
3770 <replaceable>string</replaceable> LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3771 <replaceable>string</replaceable> NOT LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3772 </synopsis>
3773
3774     <para>
3775      The <function>LIKE</function> expression returns true if the
3776      <replaceable>string</replaceable> matches the supplied
3777      <replaceable>pattern</replaceable>.  (As
3778      expected, the <function>NOT LIKE</function> expression returns
3779      false if <function>LIKE</function> returns true, and vice versa.
3780      An equivalent expression is
3781      <literal>NOT (<replaceable>string</replaceable> LIKE
3782       <replaceable>pattern</replaceable>)</literal>.)
3783     </para>
3784
3785     <para>
3786      If <replaceable>pattern</replaceable> does not contain percent
3787      signs or underscores, then the pattern only represents the string
3788      itself; in that case <function>LIKE</function> acts like the
3789      equals operator.  An underscore (<literal>_</literal>) in
3790      <replaceable>pattern</replaceable> stands for (matches) any single
3791      character; a percent sign (<literal>%</literal>) matches any sequence
3792      of zero or more characters.
3793     </para>
3794
3795    <para>
3796     Some examples:
3797 <programlisting>
3798 'abc' LIKE 'abc'    <lineannotation>true</lineannotation>
3799 'abc' LIKE 'a%'     <lineannotation>true</lineannotation>
3800 'abc' LIKE '_b_'    <lineannotation>true</lineannotation>
3801 'abc' LIKE 'c'      <lineannotation>false</lineannotation>
3802 </programlisting>
3803    </para>
3804
3805    <para>
3806     <function>LIKE</function> pattern matching always covers the entire
3807     string.  Therefore, if it's desired to match a sequence anywhere within
3808     a string, the pattern must start and end with a percent sign.
3809    </para>
3810
3811    <para>
3812     To match a literal underscore or percent sign without matching
3813     other characters, the respective character in
3814     <replaceable>pattern</replaceable> must be
3815     preceded by the escape character.  The default escape
3816     character is the backslash but a different one can be selected by
3817     using the <literal>ESCAPE</literal> clause.  To match the escape
3818     character itself, write two escape characters.
3819    </para>
3820
3821    <note>
3822     <para>
3823      If you have <xref linkend="guc-standard-conforming-strings"> turned off,
3824      any backslashes you write in literal string constants will need to be
3825      doubled.  See <xref linkend="sql-syntax-strings"> for more information.
3826     </para>
3827    </note>
3828
3829    <para>
3830     It's also possible to select no escape character by writing
3831     <literal>ESCAPE ''</literal>.  This effectively disables the
3832     escape mechanism, which makes it impossible to turn off the
3833     special meaning of underscore and percent signs in the pattern.
3834    </para>
3835
3836    <para>
3837     The key word <token>ILIKE</token> can be used instead of
3838     <token>LIKE</token> to make the match case-insensitive according
3839     to the active locale.  This is not in the <acronym>SQL</acronym> standard but is a
3840     <productname>PostgreSQL</productname> extension.
3841    </para>
3842
3843    <para>
3844     The operator <literal>~~</literal> is equivalent to
3845     <function>LIKE</function>, and <literal>~~*</literal> corresponds to
3846     <function>ILIKE</function>.  There are also
3847     <literal>!~~</literal> and <literal>!~~*</literal> operators that
3848     represent <function>NOT LIKE</function> and <function>NOT
3849     ILIKE</function>, respectively.  All of these operators are
3850     <productname>PostgreSQL</productname>-specific.
3851    </para>
3852   </sect2>
3853
3854
3855   <sect2 id="functions-similarto-regexp">
3856    <title><function>SIMILAR TO</function> Regular Expressions</title>
3857
3858    <indexterm>
3859     <primary>regular expression</primary>
3860     <!-- <seealso>pattern matching</seealso> breaks index build -->
3861    </indexterm>
3862
3863    <indexterm>
3864     <primary>SIMILAR TO</primary>
3865    </indexterm>
3866    <indexterm>
3867     <primary>substring</primary>
3868    </indexterm>
3869
3870 <synopsis>
3871 <replaceable>string</replaceable> SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3872 <replaceable>string</replaceable> NOT SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3873 </synopsis>
3874
3875    <para>
3876     The <function>SIMILAR TO</function> operator returns true or
3877     false depending on whether its pattern matches the given string.
3878     It is similar to <function>LIKE</function>, except that it
3879     interprets the pattern using the SQL standard's definition of a
3880     regular expression.  SQL regular expressions are a curious cross
3881     between <function>LIKE</function> notation and common regular
3882     expression notation.
3883    </para>
3884
3885    <para>
3886     Like <function>LIKE</function>, the <function>SIMILAR TO</function>
3887     operator succeeds only if its pattern matches the entire string;
3888     this is unlike common regular expression behavior where the pattern
3889     can match any part of the string.
3890     Also like
3891     <function>LIKE</function>, <function>SIMILAR TO</function> uses
3892     <literal>_</> and <literal>%</> as wildcard characters denoting
3893     any single character and any string, respectively (these are
3894     comparable to <literal>.</> and <literal>.*</> in POSIX regular
3895     expressions).
3896    </para>
3897
3898    <para>
3899     In addition to these facilities borrowed from <function>LIKE</function>,
3900     <function>SIMILAR TO</function> supports these pattern-matching
3901     metacharacters borrowed from POSIX regular expressions:
3902
3903    <itemizedlist>
3904     <listitem>
3905      <para>
3906       <literal>|</literal> denotes alternation (either of two alternatives).
3907      </para>
3908     </listitem>
3909     <listitem>
3910      <para>
3911       <literal>*</literal> denotes repetition of the previous item zero
3912       or more times.
3913      </para>
3914     </listitem>
3915     <listitem>
3916      <para>
3917       <literal>+</literal> denotes repetition of the previous item one
3918       or more times.
3919      </para>
3920     </listitem>
3921     <listitem>
3922      <para>
3923       <literal>?</literal> denotes repetition of the previous item zero
3924       or one time.
3925      </para>
3926     </listitem>
3927     <listitem>
3928      <para>
3929       <literal>{</><replaceable>m</><literal>}</literal> denotes repetition
3930       of the previous item exactly <replaceable>m</> times.
3931      </para>
3932     </listitem>
3933     <listitem>
3934      <para>
3935       <literal>{</><replaceable>m</><literal>,}</literal> denotes repetition
3936       of the previous item <replaceable>m</> or more times.
3937      </para>
3938     </listitem>
3939     <listitem>
3940      <para>
3941       <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</>
3942       denotes repetition of the previous item at least <replaceable>m</> and
3943       not more than <replaceable>n</> times.
3944      </para>
3945     </listitem>
3946     <listitem>
3947      <para>
3948       Parentheses <literal>()</literal> can be used to group items into
3949       a single logical item.
3950      </para>
3951     </listitem>
3952     <listitem>
3953      <para>
3954       A bracket expression <literal>[...]</literal> specifies a character
3955       class, just as in POSIX regular expressions.
3956      </para>
3957     </listitem>
3958    </itemizedlist>
3959
3960     Notice that the period (<literal>.</>) is not a metacharacter
3961     for <function>SIMILAR TO</>.
3962    </para>
3963
3964    <para>
3965     As with <function>LIKE</>, a backslash disables the special meaning
3966     of any of these metacharacters; or a different escape character can
3967     be specified with <literal>ESCAPE</>.
3968    </para>
3969
3970    <para>
3971     Some examples:
3972 <programlisting>
3973 'abc' SIMILAR TO 'abc'      <lineannotation>true</lineannotation>
3974 'abc' SIMILAR TO 'a'        <lineannotation>false</lineannotation>
3975 'abc' SIMILAR TO '%(b|d)%'  <lineannotation>true</lineannotation>
3976 'abc' SIMILAR TO '(b|c)%'   <lineannotation>false</lineannotation>
3977 </programlisting>
3978    </para>
3979
3980    <para>
3981     The <function>substring</> function with three parameters,
3982     <function>substring(<replaceable>string</replaceable> from
3983     <replaceable>pattern</replaceable> for
3984     <replaceable>escape-character</replaceable>)</function>, provides
3985     extraction of a substring that matches an SQL
3986     regular expression pattern.  As with <literal>SIMILAR TO</>, the
3987     specified pattern must match the entire data string, or else the
3988     function fails and returns null.  To indicate the part of the
3989     pattern that should be returned on success, the pattern must contain
3990     two occurrences of the escape character followed by a double quote
3991     (<literal>"</>). <!-- " font-lock sanity -->
3992     The text matching the portion of the pattern
3993     between these markers is returned.
3994    </para>
3995
3996    <para>
3997     Some examples, with <literal>#&quot;</> delimiting the return string:
3998 <programlisting>
3999 substring('foobar' from '%#"o_b#"%' for '#')   <lineannotation>oob</lineannotation>
4000 substring('foobar' from '#"o_b#"%' for '#')    <lineannotation>NULL</lineannotation>
4001 </programlisting>
4002    </para>
4003   </sect2>
4004
4005   <sect2 id="functions-posix-regexp">
4006    <title><acronym>POSIX</acronym> Regular Expressions</title>
4007
4008    <indexterm zone="functions-posix-regexp">
4009     <primary>regular expression</primary>
4010     <seealso>pattern matching</seealso>
4011    </indexterm>
4012    <indexterm>
4013     <primary>substring</primary>
4014    </indexterm>
4015    <indexterm>
4016     <primary>regexp_replace</primary>
4017    </indexterm>
4018    <indexterm>
4019     <primary>regexp_matches</primary>
4020    </indexterm>
4021    <indexterm>
4022     <primary>regexp_split_to_table</primary>
4023    </indexterm>
4024    <indexterm>
4025     <primary>regexp_split_to_array</primary>
4026    </indexterm>
4027
4028    <para>
4029     <xref linkend="functions-posix-table"> lists the available
4030     operators for pattern matching using POSIX regular expressions.
4031    </para>
4032
4033    <table id="functions-posix-table">
4034     <title>Regular Expression Match Operators</title>
4035
4036     <tgroup cols="3">
4037      <thead>
4038       <row>
4039        <entry>Operator</entry>
4040        <entry>Description</entry>
4041        <entry>Example</entry>
4042       </row>
4043      </thead>
4044
4045       <tbody>
4046        <row>
4047         <entry> <literal>~</literal> </entry>
4048         <entry>Matches regular expression, case sensitive</entry>
4049         <entry><literal>'thomas' ~ '.*thomas.*'</literal></entry>
4050        </row>
4051
4052        <row>
4053         <entry> <literal>~*</literal> </entry>
4054         <entry>Matches regular expression, case insensitive</entry>
4055         <entry><literal>'thomas' ~* '.*Thomas.*'</literal></entry>
4056        </row>
4057
4058        <row>
4059         <entry> <literal>!~</literal> </entry>
4060         <entry>Does not match regular expression, case sensitive</entry>
4061         <entry><literal>'thomas' !~ '.*Thomas.*'</literal></entry>
4062        </row>
4063
4064        <row>
4065         <entry> <literal>!~*</literal> </entry>
4066         <entry>Does not match regular expression, case insensitive</entry>
4067         <entry><literal>'thomas' !~* '.*vadim.*'</literal></entry>
4068        </row>
4069       </tbody>
4070      </tgroup>
4071     </table>
4072
4073     <para>
4074      <acronym>POSIX</acronym> regular expressions provide a more
4075      powerful means for pattern matching than the <function>LIKE</function> and
4076      <function>SIMILAR TO</> operators.
4077      Many Unix tools such as <command>egrep</command>,
4078      <command>sed</command>, or <command>awk</command> use a pattern
4079      matching language that is similar to the one described here.
4080     </para>
4081
4082     <para>
4083      A regular expression is a character sequence that is an
4084      abbreviated definition of a set of strings (a <firstterm>regular
4085      set</firstterm>).  A string is said to match a regular expression
4086      if it is a member of the regular set described by the regular
4087      expression.  As with <function>LIKE</function>, pattern characters
4088      match string characters exactly unless they are special characters
4089      in the regular expression language &mdash; but regular expressions use
4090      different special characters than <function>LIKE</function> does.
4091      Unlike <function>LIKE</function> patterns, a
4092      regular expression is allowed to match anywhere within a string, unless
4093      the regular expression is explicitly anchored to the beginning or
4094      end of the string.
4095     </para>
4096
4097     <para>
4098      Some examples:
4099 <programlisting>
4100 'abc' ~ 'abc'    <lineannotation>true</lineannotation>
4101 'abc' ~ '^a'     <lineannotation>true</lineannotation>
4102 'abc' ~ '(b|d)'  <lineannotation>true</lineannotation>
4103 'abc' ~ '^(b|c)' <lineannotation>false</lineannotation>
4104 </programlisting>
4105     </para>
4106
4107     <para>
4108      The <acronym>POSIX</acronym> pattern language is described in much
4109      greater detail below.
4110     </para>
4111
4112     <para>
4113      The <function>substring</> function with two parameters,
4114      <function>substring(<replaceable>string</replaceable> from
4115      <replaceable>pattern</replaceable>)</function>, provides extraction of a
4116      substring
4117      that matches a POSIX regular expression pattern.  It returns null if
4118      there is no match, otherwise the portion of the text that matched the
4119      pattern.  But if the pattern contains any parentheses, the portion
4120      of the text that matched the first parenthesized subexpression (the
4121      one whose left parenthesis comes first) is
4122      returned.  You can put parentheses around the whole expression
4123      if you want to use parentheses within it without triggering this
4124      exception.  If you need parentheses in the pattern before the
4125      subexpression you want to extract, see the non-capturing parentheses
4126      described below.
4127     </para>
4128
4129    <para>
4130     Some examples:
4131 <programlisting>
4132 substring('foobar' from 'o.b')     <lineannotation>oob</lineannotation>
4133 substring('foobar' from 'o(.)b')   <lineannotation>o</lineannotation>
4134 </programlisting>
4135    </para>
4136
4137     <para>
4138      The <function>regexp_replace</> function provides substitution of
4139      new text for substrings that match POSIX regular expression patterns.
4140      It has the syntax
4141      <function>regexp_replace</function>(<replaceable>source</>,
4142      <replaceable>pattern</>, <replaceable>replacement</>
4143      <optional>, <replaceable>flags</> </optional>).
4144      The <replaceable>source</> string is returned unchanged if
4145      there is no match to the <replaceable>pattern</>.  If there is a
4146      match, the <replaceable>source</> string is returned with the
4147      <replaceable>replacement</> string substituted for the matching
4148      substring.  The <replaceable>replacement</> string can contain
4149      <literal>\</><replaceable>n</>, where <replaceable>n</> is 1
4150      through 9, to indicate that the source substring matching the
4151      <replaceable>n</>'th parenthesized subexpression of the pattern should be
4152      inserted, and it can contain <literal>\&amp;</> to indicate that the
4153      substring matching the entire pattern should be inserted.  Write
4154      <literal>\\</> if you need to put a literal backslash in the replacement
4155      text.
4156      The <replaceable>flags</> parameter is an optional text
4157      string containing zero or more single-letter flags that change the
4158      function's behavior.  Flag <literal>i</> specifies case-insensitive
4159      matching, while flag <literal>g</> specifies replacement of each matching
4160      substring rather than only the first one.  Supported flags (though
4161      not <literal>g</>) are
4162      described in <xref linkend="posix-embedded-options-table">.
4163     </para>
4164
4165    <para>
4166     Some examples:
4167 <programlisting>
4168 regexp_replace('foobarbaz', 'b..', 'X')
4169                                    <lineannotation>fooXbaz</lineannotation>
4170 regexp_replace('foobarbaz', 'b..', 'X', 'g')
4171                                    <lineannotation>fooXX</lineannotation>
4172 regexp_replace('foobarbaz', 'b(..)', E'X\\1Y', 'g')
4173                                    <lineannotation>fooXarYXazY</lineannotation>
4174 </programlisting>
4175    </para>
4176
4177     <para>
4178      The <function>regexp_matches</> function returns a text array of
4179      all of the captured substrings resulting from matching a POSIX
4180      regular expression pattern.  It has the syntax
4181      <function>regexp_matches</function>(<replaceable>string</>, <replaceable>pattern</>
4182      <optional>, <replaceable>flags</> </optional>).
4183      The function can return no rows, one row, or multiple rows (see
4184      the <literal>g</> flag below).  If the <replaceable>pattern</>
4185      does not match, the function returns no rows.  If the pattern
4186      contains no parenthesized subexpressions, then each row
4187      returned is a single-element text array containing the substring
4188      matching the whole pattern.  If the pattern contains parenthesized
4189      subexpressions, the function returns a text array whose
4190      <replaceable>n</>'th element is the substring matching the
4191      <replaceable>n</>'th parenthesized subexpression of the pattern
4192      (not counting <quote>non-capturing</> parentheses; see below for
4193      details).
4194      The <replaceable>flags</> parameter is an optional text
4195      string containing zero or more single-letter flags that change the
4196      function's behavior.  Flag <literal>g</> causes the function to find
4197      each match in the string, not only the first one, and return a row for
4198      each such match.  Supported flags (though
4199      not <literal>g</>)
4200      are described in <xref linkend="posix-embedded-options-table">.
4201     </para>
4202
4203    <para>
4204     Some examples:
4205 <programlisting>
4206 SELECT regexp_matches('foobarbequebaz', '(bar)(beque)');
4207  regexp_matches 
4208 ----------------
4209  {bar,beque}
4210 (1 row)
4211
4212 SELECT regexp_matches('foobarbequebazilbarfbonk', '(b[^b]+)(b[^b]+)', 'g');
4213  regexp_matches 
4214 ----------------
4215  {bar,beque}
4216  {bazil,barf}
4217 (2 rows)
4218
4219 SELECT regexp_matches('foobarbequebaz', 'barbeque');
4220  regexp_matches 
4221 ----------------
4222  {barbeque}
4223 (1 row)
4224 </programlisting>
4225    </para>
4226
4227    <para>
4228     It is possible to force <function>regexp_matches()</> to always
4229     return one row by using a sub-select;  this is particularly useful
4230     in a <literal>SELECT</> target list when you want all rows
4231     returned, even non-matching ones:
4232 <programlisting>
4233 SELECT col1, (SELECT regexp_matches(col2, '(bar)(beque)')) FROM tab;
4234 </programlisting>
4235    </para>
4236
4237     <para>
4238      The <function>regexp_split_to_table</> function splits a string using a POSIX
4239      regular expression pattern as a delimiter.  It has the syntax
4240      <function>regexp_split_to_table</function>(<replaceable>string</>, <replaceable>pattern</>
4241      <optional>, <replaceable>flags</> </optional>).
4242      If there is no match to the <replaceable>pattern</>, the function returns the
4243      <replaceable>string</>.  If there is at least one match, for each match it returns
4244      the text from the end of the last match (or the beginning of the string)
4245      to the beginning of the match.  When there are no more matches, it
4246      returns the text from the end of the last match to the end of the string.
4247      The <replaceable>flags</> parameter is an optional text string containing
4248      zero or more single-letter flags that change the function's behavior.
4249      <function>regexp_split_to_table</function> supports the flags described in
4250      <xref linkend="posix-embedded-options-table">.
4251     </para>
4252
4253     <para>
4254      The <function>regexp_split_to_array</> function behaves the same as
4255      <function>regexp_split_to_table</>, except that <function>regexp_split_to_array</>
4256      returns its result as an array of <type>text</>.  It has the syntax
4257      <function>regexp_split_to_array</function>(<replaceable>string</>, <replaceable>pattern</>
4258      <optional>, <replaceable>flags</> </optional>).
4259      The parameters are the same as for <function>regexp_split_to_table</>.
4260     </para>
4261
4262    <para>
4263     Some examples:
4264 <programlisting>
4265
4266 SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', E'\\s+') AS foo;
4267   foo   
4268 -------
4269  the    
4270  quick  
4271  brown  
4272  fox    
4273  jumps 
4274  over   
4275  the    
4276  lazy   
4277  dog    
4278 (9 rows)
4279
4280 SELECT regexp_split_to_array('the quick brown fox jumps over the lazy dog', E'\\s+');
4281               regexp_split_to_array             
4282 -----------------------------------------------
4283  {the,quick,brown,fox,jumps,over,the,lazy,dog}
4284 (1 row)
4285
4286 SELECT foo FROM regexp_split_to_table('the quick brown fox', E'\\s*') AS foo;
4287  foo 
4288 -----
4289  t         
4290  h         
4291  e         
4292  q         
4293  u         
4294  i         
4295  c         
4296  k         
4297  b         
4298  r         
4299  o         
4300  w         
4301  n         
4302  f         
4303  o         
4304  x         
4305 (16 rows)
4306 </programlisting>
4307    </para>
4308
4309    <para>
4310     As the last example demonstrates, the regexp split functions ignore
4311     zero-length matches that occur at the start or end of the string
4312     or immediately after a previous match.  This is contrary to the strict
4313     definition of regexp matching that is implemented by
4314     <function>regexp_matches</>, but is usually the most convenient behavior
4315     in practice.  Other software systems such as Perl use similar definitions.
4316    </para>
4317
4318 <!-- derived from the re_syntax.n man page -->
4319
4320    <sect3 id="posix-syntax-details">
4321     <title>Regular Expression Details</title>
4322
4323    <para>
4324     <productname>PostgreSQL</productname>'s regular expressions are implemented
4325     using a software package written by Henry Spencer.  Much of
4326     the description of regular expressions below is copied verbatim from his
4327     manual.
4328    </para>
4329
4330    <para>
4331     Regular expressions (<acronym>RE</acronym>s), as defined in
4332     <acronym>POSIX</acronym> 1003.2, come in two forms:
4333     <firstterm>extended</> <acronym>RE</acronym>s or <acronym>ERE</>s
4334     (roughly those of <command>egrep</command>), and
4335     <firstterm>basic</> <acronym>RE</acronym>s or <acronym>BRE</>s
4336     (roughly those of <command>ed</command>).
4337     <productname>PostgreSQL</productname> supports both forms, and
4338     also implements some extensions
4339     that are not in the POSIX standard, but have become widely used
4340     due to their availability in programming languages such as Perl and Tcl.
4341     <acronym>RE</acronym>s using these non-POSIX extensions are called
4342     <firstterm>advanced</> <acronym>RE</acronym>s or <acronym>ARE</>s
4343     in this documentation.  AREs are almost an exact superset of EREs,
4344     but BREs have several notational incompatibilities (as well as being
4345     much more limited).
4346     We first describe the ARE and ERE forms, noting features that apply
4347     only to AREs, and then describe how BREs differ.
4348    </para>
4349
4350    <note>
4351     <para>
4352      <productname>PostgreSQL</> always initially presumes that a regular
4353      expression follows the ARE rules.  However, the more limited ERE or
4354      BRE rules can be chosen by prepending an <firstterm>embedded option</>
4355      to the RE pattern, as described in <xref linkend="posix-metasyntax">.
4356      This can be useful for compatibility with applications that expect
4357      exactly the <acronym>POSIX</acronym> 1003.2 rules.
4358     </para>
4359    </note>
4360
4361    <para>
4362     A regular expression is defined as one or more
4363     <firstterm>branches</firstterm>, separated by
4364     <literal>|</literal>.  It matches anything that matches one of the
4365     branches.
4366    </para>
4367
4368    <para>
4369     A branch is zero or more <firstterm>quantified atoms</> or
4370     <firstterm>constraints</>, concatenated.
4371     It matches a match for the first, followed by a match for the second, etc;
4372     an empty branch matches the empty string.
4373    </para>
4374
4375    <para>
4376     A quantified atom is an <firstterm>atom</> possibly followed
4377     by a single <firstterm>quantifier</>.
4378     Without a quantifier, it matches a match for the atom.
4379     With a quantifier, it can match some number of matches of the atom.
4380     An <firstterm>atom</firstterm> can be any of the possibilities
4381     shown in <xref linkend="posix-atoms-table">.
4382     The possible quantifiers and their meanings are shown in
4383     <xref linkend="posix-quantifiers-table">.
4384    </para>
4385
4386    <para>
4387     A <firstterm>constraint</> matches an empty string, but matches only when
4388     specific conditions are met.  A constraint can be used where an atom
4389     could be used, except it cannot be followed by a quantifier.
4390     The simple constraints are shown in
4391     <xref linkend="posix-constraints-table">;
4392     some more constraints are described later.
4393    </para>
4394
4395
4396    <table id="posix-atoms-table">
4397     <title>Regular Expression Atoms</title>
4398
4399     <tgroup cols="2">
4400      <thead>
4401       <row>
4402        <entry>Atom</entry>
4403        <entry>Description</entry>
4404       </row>
4405      </thead>
4406
4407       <tbody>
4408        <row>
4409        <entry> <literal>(</><replaceable>re</><literal>)</> </entry>
4410        <entry> (where <replaceable>re</> is any regular expression)
4411        matches a match for
4412        <replaceable>re</>, with the match noted for possible reporting </entry>
4413        </row>
4414
4415        <row>
4416        <entry> <literal>(?:</><replaceable>re</><literal>)</> </entry>
4417        <entry> as above, but the match is not noted for reporting
4418        (a <quote>non-capturing</> set of parentheses)
4419        (AREs only) </entry>
4420        </row>
4421
4422        <row>
4423        <entry> <literal>.</> </entry>
4424        <entry> matches any single character </entry>
4425        </row>
4426
4427        <row>
4428        <entry> <literal>[</><replaceable>chars</><literal>]</> </entry>
4429        <entry> a <firstterm>bracket expression</>,
4430        matching any one of the <replaceable>chars</> (see
4431        <xref linkend="posix-bracket-expressions"> for more detail) </entry>
4432        </row>
4433
4434        <row>
4435        <entry> <literal>\</><replaceable>k</> </entry>
4436        <entry> (where <replaceable>k</> is a non-alphanumeric character)
4437        matches that character taken as an ordinary character,
4438        e.g., <literal>\\</> matches a backslash character </entry>
4439        </row>
4440
4441        <row>
4442        <entry> <literal>\</><replaceable>c</> </entry>
4443        <entry> where <replaceable>c</> is alphanumeric
4444        (possibly followed by other characters)
4445        is an <firstterm>escape</>, see <xref linkend="posix-escape-sequences">
4446        (AREs only; in EREs and BREs, this matches <replaceable>c</>) </entry>
4447        </row>
4448
4449        <row>
4450        <entry> <literal>{</> </entry>
4451        <entry> when followed by a character other than a digit,
4452        matches the left-brace character <literal>{</>;
4453        when followed by a digit, it is the beginning of a
4454        <replaceable>bound</> (see below) </entry>
4455        </row>
4456
4457        <row>
4458        <entry> <replaceable>x</> </entry>
4459        <entry> where <replaceable>x</> is a single character with no other
4460        significance, matches that character </entry>
4461        </row>
4462       </tbody>
4463      </tgroup>
4464     </table>
4465
4466    <para>
4467     An RE cannot end with a backslash (<literal>\</>).
4468    </para>
4469
4470    <note>
4471     <para>
4472      If you have <xref linkend="guc-standard-conforming-strings"> turned off,
4473      any backslashes you write in literal string constants will need to be
4474      doubled.  See <xref linkend="sql-syntax-strings"> for more information.
4475     </para>
4476    </note>
4477
4478    <table id="posix-quantifiers-table">
4479     <title>Regular Expression Quantifiers</title>
4480
4481     <tgroup cols="2">
4482      <thead>
4483       <row>
4484        <entry>Quantifier</entry>
4485        <entry>Matches</entry>
4486       </row>
4487      </thead>
4488
4489       <tbody>
4490        <row>
4491        <entry> <literal>*</> </entry>
4492        <entry> a sequence of 0 or more matches of the atom </entry>
4493        </row>
4494
4495        <row>
4496        <entry> <literal>+</> </entry>
4497        <entry> a sequence of 1 or more matches of the atom </entry>
4498        </row>
4499
4500        <row>
4501        <entry> <literal>?</> </entry>
4502        <entry> a sequence of 0 or 1 matches of the atom </entry>
4503        </row>
4504
4505        <row>
4506        <entry> <literal>{</><replaceable>m</><literal>}</> </entry>
4507        <entry> a sequence of exactly <replaceable>m</> matches of the atom </entry>
4508        </row>
4509
4510        <row>
4511        <entry> <literal>{</><replaceable>m</><literal>,}</> </entry>
4512        <entry> a sequence of <replaceable>m</> or more matches of the atom </entry>
4513        </row>
4514
4515        <row>
4516        <entry>
4517        <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
4518        <entry> a sequence of <replaceable>m</> through <replaceable>n</>
4519        (inclusive) matches of the atom; <replaceable>m</> cannot exceed
4520        <replaceable>n</> </entry>
4521        </row>
4522
4523        <row>
4524        <entry> <literal>*?</> </entry>
4525        <entry> non-greedy version of <literal>*</> </entry>
4526        </row>
4527
4528        <row>
4529        <entry> <literal>+?</> </entry>
4530        <entry> non-greedy version of <literal>+</> </entry>
4531        </row>
4532
4533        <row>
4534        <entry> <literal>??</> </entry>
4535        <entry> non-greedy version of <literal>?</> </entry>
4536        </row>
4537
4538        <row>
4539        <entry> <literal>{</><replaceable>m</><literal>}?</> </entry>
4540        <entry> non-greedy version of <literal>{</><replaceable>m</><literal>}</> </entry>
4541        </row>
4542
4543        <row>
4544        <entry> <literal>{</><replaceable>m</><literal>,}?</> </entry>
4545        <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,}</> </entry>
4546        </row>
4547
4548        <row>
4549        <entry>
4550        <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</> </entry>
4551        <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
4552        </row>
4553       </tbody>
4554      </tgroup>
4555     </table>
4556
4557    <para>
4558     The forms using <literal>{</><replaceable>...</><literal>}</>
4559     are known as <firstterm>bounds</>.
4560     The numbers <replaceable>m</> and <replaceable>n</> within a bound are
4561     unsigned decimal integers with permissible values from 0 to 255 inclusive.
4562    </para>
4563
4564     <para>
4565      <firstterm>Non-greedy</> quantifiers (available in AREs only) match the
4566      same possibilities as their corresponding normal (<firstterm>greedy</>)
4567      counterparts, but prefer the smallest number rather than the largest
4568      number of matches.
4569      See <xref linkend="posix-matching-rules"> for more detail.
4570    </para>
4571
4572    <note>
4573     <para>
4574      A quantifier cannot immediately follow another quantifier, e.g.,
4575      <literal>**</> is invalid.
4576      A quantifier cannot
4577      begin an expression or subexpression or follow
4578      <literal>^</literal> or <literal>|</literal>.
4579     </para>
4580    </note>
4581
4582    <table id="posix-constraints-table">
4583     <title>Regular Expression Constraints</title>
4584
4585     <tgroup cols="2">
4586      <thead>
4587       <row>
4588        <entry>Constraint</entry>
4589        <entry>Description</entry>
4590       </row>
4591      </thead>
4592
4593       <tbody>
4594        <row>
4595        <entry> <literal>^</> </entry>
4596        <entry> matches at the beginning of the string </entry>
4597        </row>
4598
4599        <row>
4600        <entry> <literal>$</> </entry>
4601        <entry> matches at the end of the string </entry>
4602        </row>
4603
4604        <row>
4605        <entry> <literal>(?=</><replaceable>re</><literal>)</> </entry>
4606        <entry> <firstterm>positive lookahead</> matches at any point
4607        where a substring matching <replaceable>re</> begins
4608        (AREs only) </entry>
4609        </row>
4610
4611        <row>
4612        <entry> <literal>(?!</><replaceable>re</><literal>)</> </entry>
4613        <entry> <firstterm>negative lookahead</> matches at any point
4614        where no substring matching <replaceable>re</> begins
4615        (AREs only) </entry>
4616        </row>
4617
4618        <row>
4619        <entry> <literal>(?&lt;=</><replaceable>re</><literal>)</> </entry>
4620        <entry> <firstterm>positive lookbehind</> matches at any point
4621        where a substring matching <replaceable>re</> ends
4622        (AREs only) </entry>
4623        </row>
4624
4625        <row>
4626        <entry> <literal>(?&lt;!</><replaceable>re</><literal>)</> </entry>
4627        <entry> <firstterm>negative lookbehind</> matches at any point
4628        where no substring matching <replaceable>re</> ends
4629        (AREs only) </entry>
4630        </row>
4631       </tbody>
4632      </tgroup>
4633     </table>
4634
4635    <para>
4636     Lookahead and lookbehind constraints cannot contain <firstterm>back
4637     references</> (see <xref linkend="posix-escape-sequences">),
4638     and all parentheses within them are considered non-capturing.
4639    </para>
4640    </sect3>
4641
4642    <sect3 id="posix-bracket-expressions">
4643     <title>Bracket Expressions</title>
4644
4645    <para>
4646     A <firstterm>bracket expression</firstterm> is a list of
4647     characters enclosed in <literal>[]</literal>.  It normally matches
4648     any single character from the list (but see below).  If the list
4649     begins with <literal>^</literal>, it matches any single character
4650     <emphasis>not</> from the rest of the list.
4651     If two characters
4652     in the list are separated by <literal>-</literal>, this is
4653     shorthand for the full range of characters between those two
4654     (inclusive) in the collating sequence,
4655     e.g., <literal>[0-9]</literal> in <acronym>ASCII</acronym> matches
4656     any decimal digit.  It is illegal for two ranges to share an
4657     endpoint, e.g.,  <literal>a-c-e</literal>.  Ranges are very
4658     collating-sequence-dependent, so portable programs should avoid
4659     relying on them.
4660    </para>
4661
4662    <para>
4663     To include a literal <literal>]</literal> in the list, make it the
4664     first character (after <literal>^</literal>, if that is used).  To
4665     include a literal <literal>-</literal>, make it the first or last
4666     character, or the second endpoint of a range.  To use a literal
4667     <literal>-</literal> as the first endpoint of a range, enclose it
4668     in <literal>[.</literal> and <literal>.]</literal> to make it a
4669     collating element (see below).  With the exception of these characters,
4670     some combinations using <literal>[</literal>
4671     (see next paragraphs), and escapes (AREs only), all other special
4672     characters lose their special significance within a bracket expression.
4673     In particular, <literal>\</literal> is not special when following
4674     ERE or BRE rules, though it is special (as introducing an escape)
4675     in AREs.
4676    </para>
4677
4678    <para>
4679     Within a bracket expression, a collating element (a character, a
4680     multiple-character sequence that collates as if it were a single
4681     character, or a collating-sequence name for either) enclosed in
4682     <literal>[.</literal> and <literal>.]</literal> stands for the
4683     sequence of characters of that collating element.  The sequence is
4684     treated as a single element of the bracket expression's list.  This
4685     allows a bracket
4686     expression containing a multiple-character collating element to
4687     match more than one character, e.g., if the collating sequence
4688     includes a <literal>ch</literal> collating element, then the RE
4689     <literal>[[.ch.]]*c</literal> matches the first five characters of
4690     <literal>chchcc</literal>.
4691    </para>
4692
4693    <note>
4694     <para>
4695      <productname>PostgreSQL</> currently does not support multi-character collating
4696      elements. This information describes possible future behavior.
4697     </para>
4698    </note>
4699
4700    <para>
4701     Within a bracket expression, a collating element enclosed in
4702     <literal>[=</literal> and <literal>=]</literal> is an <firstterm>equivalence
4703     class</>, standing for the sequences of characters of all collating
4704     elements equivalent to that one, including itself.  (If there are
4705     no other equivalent collating elements, the treatment is as if the
4706     enclosing delimiters were <literal>[.</literal> and
4707     <literal>.]</literal>.)  For example, if <literal>o</literal> and
4708     <literal>^</literal> are the members of an equivalence class, then
4709     <literal>[[=o=]]</literal>, <literal>[[=^=]]</literal>, and
4710     <literal>[o^]</literal> are all synonymous.  An equivalence class
4711     cannot be an endpoint of a range.
4712    </para>
4713
4714    <para>
4715     Within a bracket expression, the name of a character class
4716     enclosed in <literal>[:</literal> and <literal>:]</literal> stands
4717     for the list of all characters belonging to that class.  Standard
4718     character class names are: <literal>alnum</literal>,
4719     <literal>alpha</literal>, <literal>blank</literal>,
4720     <literal>cntrl</literal>, <literal>digit</literal>,
4721     <literal>graph</literal>, <literal>lower</literal>,
4722     <literal>print</literal>, <literal>punct</literal>,
4723     <literal>space</literal>, <literal>upper</literal>,
4724     <literal>xdigit</literal>.  These stand for the character classes
4725     defined in
4726     <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>.
4727     A locale can provide others.  A character class cannot be used as
4728     an endpoint of a range.
4729    </para>
4730
4731    <para>
4732     There are two special cases of bracket expressions:  the bracket
4733     expressions <literal>[[:&lt;:]]</literal> and
4734     <literal>[[:&gt;:]]</literal> are constraints,
4735     matching empty strings at the beginning
4736     and end of a word respectively.  A word is defined as a sequence
4737     of word characters that is neither preceded nor followed by word
4738     characters.  A word character is an <literal>alnum</> character (as
4739     defined by
4740     <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>)
4741     or an underscore.  This is an extension, compatible with but not
4742     specified by <acronym>POSIX</acronym> 1003.2, and should be used with
4743     caution in software intended to be portable to other systems.
4744     The constraint escapes described below are usually preferable; they
4745     are no more standard, but are easier to type.
4746    </para>
4747    </sect3>
4748
4749    <sect3 id="posix-escape-sequences">
4750     <title>Regular Expression Escapes</title>
4751
4752    <para>
4753     <firstterm>Escapes</> are special sequences beginning with <literal>\</>
4754     followed by an alphanumeric character. Escapes come in several varieties:
4755     character entry, class shorthands, constraint escapes, and back references.
4756     A <literal>\</> followed by an alphanumeric character but not constituting
4757     a valid escape is illegal in AREs.
4758     In EREs, there are no escapes: outside a bracket expression,
4759     a <literal>\</> followed by an alphanumeric character merely stands for
4760     that character as an ordinary character, and inside a bracket expression,
4761     <literal>\</> is an ordinary character.
4762     (The latter is the one actual incompatibility between EREs and AREs.)
4763    </para>
4764
4765    <para>
4766     <firstterm>Character-entry escapes</> exist to make it easier to specify
4767     non-printing and other inconvenient characters in REs.  They are
4768     shown in <xref linkend="posix-character-entry-escapes-table">.
4769    </para>
4770
4771    <para>
4772     <firstterm>Class-shorthand escapes</> provide shorthands for certain
4773     commonly-used character classes.  They are
4774     shown in <xref linkend="posix-class-shorthand-escapes-table">.
4775    </para>
4776
4777    <para>
4778     A <firstterm>constraint escape</> is a constraint,
4779     matching the empty string if specific conditions are met,
4780     written as an escape.  They are
4781     shown in <xref linkend="posix-constraint-escapes-table">.
4782    </para>
4783
4784    <para>
4785     A <firstterm>back reference</> (<literal>\</><replaceable>n</>) matches the
4786     same string matched by the previous parenthesized subexpression specified
4787     by the number <replaceable>n</>
4788     (see <xref linkend="posix-constraint-backref-table">).  For example,
4789     <literal>([bc])\1</> matches <literal>bb</> or <literal>cc</>
4790     but not <literal>bc</> or <literal>cb</>.
4791     The subexpression must entirely precede the back reference in the RE.
4792     Subexpressions are numbered in the order of their leading parentheses.
4793     Non-capturing parentheses do not define subexpressions.
4794    </para>
4795
4796    <table id="posix-character-entry-escapes-table">
4797     <title>Regular Expression Character-entry Escapes</title>
4798
4799     <tgroup cols="2">
4800      <thead>
4801       <row>
4802        <entry>Escape</entry>
4803        <entry>Description</entry>
4804       </row>
4805      </thead>
4806
4807       <tbody>
4808        <row>
4809        <entry> <literal>\a</> </entry>
4810        <entry> alert (bell) character, as in C </entry>
4811        </row>
4812
4813        <row>
4814        <entry> <literal>\b</> </entry>
4815        <entry> backspace, as in C </entry>
4816        </row>
4817
4818        <row>
4819        <entry> <literal>\B</> </entry>
4820        <entry> synonym for backslash (<literal>\</>) to help reduce the need for backslash
4821        doubling </entry>
4822        </row>
4823
4824        <row>
4825        <entry> <literal>\c</><replaceable>X</> </entry>
4826        <entry> (where <replaceable>X</> is any character) the character whose
4827        low-order 5 bits are the same as those of
4828        <replaceable>X</>, and whose other bits are all zero </entry>
4829        </row>
4830
4831        <row>
4832        <entry> <literal>\e</> </entry>
4833        <entry> the character whose collating-sequence name
4834        is <literal>ESC</>,
4835        or failing that, the character with octal value <literal>033</> </entry>
4836        </row>
4837
4838        <row>
4839        <entry> <literal>\f</> </entry>
4840        <entry> form feed, as in C </entry>
4841        </row>
4842
4843        <row>
4844        <entry> <literal>\n</> </entry>
4845        <entry> newline, as in C </entry>
4846        </row>
4847
4848        <row>
4849        <entry> <literal>\r</> </entry>
4850        <entry> carriage return, as in C </entry>
4851        </row>
4852
4853        <row>
4854        <entry> <literal>\t</> </entry>
4855        <entry> horizontal tab, as in C </entry>
4856        </row>
4857
4858        <row>
4859        <entry> <literal>\u</><replaceable>wxyz</> </entry>
4860        <entry> (where <replaceable>wxyz</> is exactly four hexadecimal digits)
4861        the character whose hexadecimal value is
4862        <literal>0x</><replaceable>wxyz</>
4863        </entry>
4864        </row>
4865
4866        <row>
4867        <entry> <literal>\U</><replaceable>stuvwxyz</> </entry>
4868        <entry> (where <replaceable>stuvwxyz</> is exactly eight hexadecimal
4869        digits)
4870        the character whose hexadecimal value is
4871        <literal>0x</><replaceable>stuvwxyz</>
4872        </entry>
4873        </row>
4874
4875        <row>
4876        <entry> <literal>\v</> </entry>
4877        <entry> vertical tab, as in C </entry>
4878        </row>
4879
4880        <row>
4881        <entry> <literal>\x</><replaceable>hhh</> </entry>
4882        <entry> (where <replaceable>hhh</> is any sequence of hexadecimal
4883        digits)
4884        the character whose hexadecimal value is
4885        <literal>0x</><replaceable>hhh</>
4886        (a single character no matter how many hexadecimal digits are used)
4887        </entry>
4888        </row>
4889
4890        <row>
4891        <entry> <literal>\0</> </entry>
4892        <entry> the character whose value is <literal>0</> (the null byte)</entry>
4893        </row>
4894
4895        <row>
4896        <entry> <literal>\</><replaceable>xy</> </entry>
4897        <entry> (where <replaceable>xy</> is exactly two octal digits,
4898        and is not a <firstterm>back reference</>)
4899        the character whose octal value is
4900        <literal>0</><replaceable>xy</> </entry>
4901        </row>
4902
4903        <row>
4904        <entry> <literal>\</><replaceable>xyz</> </entry>
4905        <entry> (where <replaceable>xyz</> is exactly three octal digits,
4906        and is not a <firstterm>back reference</>)
4907        the character whose octal value is
4908        <literal>0</><replaceable>xyz</> </entry>
4909        </row>
4910       </tbody>
4911      </tgroup>
4912     </table>
4913
4914    <para>
4915     Hexadecimal digits are <literal>0</>-<literal>9</>,
4916     <literal>a</>-<literal>f</>, and <literal>A</>-<literal>F</>.
4917     Octal digits are <literal>0</>-<literal>7</>.
4918    </para>
4919
4920    <para>
4921     Numeric character-entry escapes specifying values outside the ASCII range
4922     (0-127) have meanings dependent on the database encoding.  When the
4923     encoding is UTF-8, escape values are equivalent to Unicode code points,
4924     for example <literal>\u1234</> means the character <literal>U+1234</>.
4925     For other multibyte encodings, character-entry escapes usually just
4926     specify the concatenation of the byte values for the character.  If the
4927     escape value does not correspond to any legal character in the database
4928     encoding, no error will be raised, but it will never match any data.
4929    </para>
4930
4931    <para>
4932     The character-entry escapes are always taken as ordinary characters.
4933     For example, <literal>\135</> is <literal>]</> in ASCII, but
4934     <literal>\135</> does not terminate a bracket expression.
4935    </para>
4936
4937    <table id="posix-class-shorthand-escapes-table">
4938     <title>Regular Expression Class-shorthand Escapes</title>
4939
4940     <tgroup cols="2">
4941      <thead>
4942       <row>
4943        <entry>Escape</entry>
4944        <entry>Description</entry>
4945       </row>
4946      </thead>
4947
4948       <tbody>
4949        <row>
4950        <entry> <literal>\d</> </entry>
4951        <entry> <literal>[[:digit:]]</> </entry>
4952        </row>
4953
4954        <row>
4955        <entry> <literal>\s</> </entry>
4956        <entry> <literal>[[:space:]]</> </entry>
4957        </row>
4958
4959        <row>
4960        <entry> <literal>\w</> </entry>
4961        <entry> <literal>[[:alnum:]_]</>
4962        (note underscore is included) </entry>
4963        </row>
4964
4965        <row>
4966        <entry> <literal>\D</> </entry>
4967        <entry> <literal>[^[:digit:]]</> </entry>
4968        </row>
4969
4970        <row>
4971        <entry> <literal>\S</> </entry>
4972        <entry> <literal>[^[:space:]]</> </entry>
4973        </row>
4974
4975        <row>
4976        <entry> <literal>\W</> </entry>
4977        <entry> <literal>[^[:alnum:]_]</>
4978        (note underscore is included) </entry>
4979        </row>
4980       </tbody>
4981      </tgroup>
4982     </table>
4983
4984    <para>
4985     Within bracket expressions, <literal>\d</>, <literal>\s</>,
4986     and <literal>\w</> lose their outer brackets,
4987     and <literal>\D</>, <literal>\S</>, and <literal>\W</> are illegal.
4988     (So, for example, <literal>[a-c\d]</> is equivalent to
4989     <literal>[a-c[:digit:]]</>.
4990     Also, <literal>[a-c\D]</>, which is equivalent to
4991     <literal>[a-c^[:digit:]]</>, is illegal.)
4992    </para>
4993
4994    <table id="posix-constraint-escapes-table">
4995     <title>Regular Expression Constraint Escapes</title>
4996
4997     <tgroup cols="2">
4998      <thead>
4999       <row>
5000        <entry>Escape</entry>
5001        <entry>Description</entry>
5002       </row>
5003      </thead>
5004
5005       <tbody>
5006        <row>
5007        <entry> <literal>\A</> </entry>
5008        <entry> matches only at the beginning of the string
5009        (see <xref linkend="posix-matching-rules"> for how this differs from
5010        <literal>^</>) </entry>
5011        </row>
5012
5013        <row>
5014        <entry> <literal>\m</> </entry>
5015        <entry> matches only at the beginning of a word </entry>
5016        </row>
5017
5018        <row>
5019        <entry> <literal>\M</> </entry>
5020        <entry> matches only at the end of a word </entry>
5021        </row>
5022
5023        <row>
5024        <entry> <literal>\y</> </entry>
5025        <entry> matches only at the beginning or end of a word </entry>
5026        </row>
5027
5028        <row>
5029        <entry> <literal>\Y</> </entry>
5030        <entry> matches only at a point that is not the beginning or end of a
5031        word </entry>
5032        </row>
5033
5034        <row>
5035        <entry> <literal>\Z</> </entry>
5036        <entry> matches only at the end of the string
5037        (see <xref linkend="posix-matching-rules"> for how this differs from
5038        <literal>$</>) </entry>
5039        </row>
5040       </tbody>
5041      </tgroup>
5042     </table>
5043
5044    <para>
5045     A word is defined as in the specification of
5046     <literal>[[:&lt;:]]</> and <literal>[[:&gt;:]]</> above.
5047     Constraint escapes are illegal within bracket expressions.
5048    </para>
5049
5050    <table id="posix-constraint-backref-table">
5051     <title>Regular Expression Back References</title>
5052
5053     <tgroup cols="2">
5054      <thead>
5055       <row>
5056        <entry>Escape</entry>
5057        <entry>Description</entry>
5058       </row>
5059      </thead>
5060
5061       <tbody>
5062        <row>
5063        <entry> <literal>\</><replaceable>m</> </entry>
5064        <entry> (where <replaceable>m</> is a nonzero digit)
5065        a back reference to the <replaceable>m</>'th subexpression </entry>
5066        </row>
5067
5068        <row>
5069        <entry> <literal>\</><replaceable>mnn</> </entry>
5070        <entry> (where <replaceable>m</> is a nonzero digit, and
5071        <replaceable>nn</> is some more digits, and the decimal value
5072        <replaceable>mnn</> is not greater than the number of closing capturing
5073        parentheses seen so far)
5074        a back reference to the <replaceable>mnn</>'th subexpression </entry>
5075        </row>
5076       </tbody>
5077      </tgroup>
5078     </table>
5079
5080    <note>
5081     <para>
5082      There is an inherent ambiguity between octal character-entry
5083      escapes and back references, which is resolved by the following heuristics,
5084      as hinted at above.
5085      A leading zero always indicates an octal escape.
5086      A single non-zero digit, not followed by another digit,
5087      is always taken as a back reference.
5088      A multi-digit sequence not starting with a zero is taken as a back
5089      reference if it comes after a suitable subexpression
5090      (i.e., the number is in the legal range for a back reference),
5091      and otherwise is taken as octal.
5092     </para>
5093    </note>
5094    </sect3>
5095
5096    <sect3 id="posix-metasyntax">
5097     <title>Regular Expression Metasyntax</title>
5098
5099    <para>
5100     In addition to the main syntax described above, there are some special
5101     forms and miscellaneous syntactic facilities available.
5102    </para>
5103
5104    <para>
5105     An RE can begin with one of two special <firstterm>director</> prefixes.
5106     If an RE begins with <literal>***:</>,
5107     the rest of the RE is taken as an ARE.  (This normally has no effect in
5108     <productname>PostgreSQL</>, since REs are assumed to be AREs;
5109     but it does have an effect if ERE or BRE mode had been specified by
5110     the <replaceable>flags</> parameter to a regex function.)
5111     If an RE begins with <literal>***=</>,
5112     the rest of the RE is taken to be a literal string,
5113     with all characters considered ordinary characters.
5114    </para>
5115
5116    <para>
5117     An ARE can begin with <firstterm>embedded options</>:
5118     a sequence <literal>(?</><replaceable>xyz</><literal>)</>
5119     (where <replaceable>xyz</> is one or more alphabetic characters)
5120     specifies options affecting the rest of the RE.
5121     These options override any previously determined options &mdash;
5122     in particular, they can override the case-sensitivity behavior implied by
5123     a regex operator, or the <replaceable>flags</> parameter to a regex
5124     function.
5125     The available option letters are
5126     shown in <xref linkend="posix-embedded-options-table">.
5127     Note that these same option letters are used in the <replaceable>flags</>
5128     parameters of regex functions.
5129    </para>
5130
5131    <table id="posix-embedded-options-table">
5132     <title>ARE Embedded-option Letters</title>
5133
5134     <tgroup cols="2">
5135      <thead>
5136       <row>
5137        <entry>Option</entry>
5138        <entry>Description</entry>
5139       </row>
5140      </thead>
5141
5142       <tbody>
5143        <row>
5144        <entry> <literal>b</> </entry>
5145        <entry> rest of RE is a BRE </entry>
5146        </row>
5147
5148        <row>
5149        <entry> <literal>c</> </entry>
5150        <entry> case-sensitive matching (overrides operator type) </entry>
5151        </row>
5152
5153        <row>
5154        <entry> <literal>e</> </entry>
5155        <entry> rest of RE is an ERE </entry>
5156        </row>
5157
5158        <row>
5159        <entry> <literal>i</> </entry>
5160        <entry> case-insensitive matching (see
5161        <xref linkend="posix-matching-rules">) (overrides operator type) </entry>
5162        </row>
5163
5164        <row>
5165        <entry> <literal>m</> </entry>
5166        <entry> historical synonym for <literal>n</> </entry>
5167        </row>
5168
5169        <row>
5170        <entry> <literal>n</> </entry>
5171        <entry> newline-sensitive matching (see
5172        <xref linkend="posix-matching-rules">) </entry>
5173        </row>
5174
5175        <row>
5176        <entry> <literal>p</> </entry>
5177        <entry> partial newline-sensitive matching (see
5178        <xref linkend="posix-matching-rules">) </entry>
5179        </row>
5180
5181        <row>
5182        <entry> <literal>q</> </entry>
5183        <entry> rest of RE is a literal (<quote>quoted</>) string, all ordinary
5184        characters </entry>
5185        </row>
5186
5187        <row>
5188        <entry> <literal>s</> </entry>
5189        <entry> non-newline-sensitive matching (default) </entry>
5190        </row>
5191
5192        <row>
5193        <entry> <literal>t</> </entry>
5194        <entry> tight syntax (default; see below) </entry>
5195        </row>
5196
5197        <row>
5198        <entry> <literal>w</> </entry>
5199        <entry> inverse partial newline-sensitive (<quote>weird</>) matching
5200        (see <xref linkend="posix-matching-rules">) </entry>
5201        </row>
5202
5203        <row>
5204        <entry> <literal>x</> </entry>
5205        <entry> expanded syntax (see below) </entry>
5206        </row>
5207       </tbody>
5208      </tgroup>
5209     </table>
5210
5211    <para>
5212     Embedded options take effect at the <literal>)</> terminating the sequence.
5213     They can appear only at the start of an ARE (after the
5214     <literal>***:</> director if any).
5215    </para>
5216
5217    <para>
5218     In addition to the usual (<firstterm>tight</>) RE syntax, in which all
5219     characters are significant, there is an <firstterm>expanded</> syntax,
5220     available by specifying the embedded <literal>x</> option.
5221     In the expanded syntax,
5222     white-space characters in the RE are ignored, as are
5223     all characters between a <literal>#</>
5224     and the following newline (or the end of the RE).  This
5225     permits paragraphing and commenting a complex RE.
5226     There are three exceptions to that basic rule:
5227
5228     <itemizedlist>
5229      <listitem>
5230       <para>
5231        a white-space character or <literal>#</> preceded by <literal>\</> is
5232        retained
5233       </para>
5234      </listitem>
5235      <listitem>
5236       <para>
5237        white space or <literal>#</> within a bracket expression is retained
5238       </para>
5239      </listitem>
5240      <listitem>
5241       <para>
5242        white space and comments cannot appear within multi-character symbols,
5243        such as <literal>(?:</>
5244       </para>
5245      </listitem>
5246     </itemizedlist>
5247
5248     For this purpose, white-space characters are blank, tab, newline, and
5249     any character that belongs to the <replaceable>space</> character class.
5250    </para>
5251
5252    <para>
5253     Finally, in an ARE, outside bracket expressions, the sequence
5254     <literal>(?#</><replaceable>ttt</><literal>)</>
5255     (where <replaceable>ttt</> is any text not containing a <literal>)</>)
5256     is a comment, completely ignored.
5257     Again, this is not allowed between the characters of
5258     multi-character symbols, like <literal>(?:</>.
5259     Such comments are more a historical artifact than a useful facility,
5260     and their use is deprecated; use the expanded syntax instead.
5261    </para>
5262
5263    <para>
5264     <emphasis>None</> of these metasyntax extensions is available if
5265     an initial <literal>***=</> director
5266     has specified that the user's input be treated as a literal string
5267     rather than as an RE.
5268    </para>
5269    </sect3>
5270
5271    <sect3 id="posix-matching-rules">
5272     <title>Regular Expression Matching Rules</title>
5273
5274    <para>
5275     In the event that an RE could match more than one substring of a given
5276     string, the RE matches the one starting earliest in the string.
5277     If the RE could match more than one substring starting at that point,
5278     either the longest possible match or the shortest possible match will
5279     be taken, depending on whether the RE is <firstterm>greedy</> or
5280     <firstterm>non-greedy</>.
5281    </para>
5282
5283    <para>
5284     Whether an RE is greedy or not is determined by the following rules:
5285     <itemizedlist>
5286      <listitem>
5287       <para>
5288        Most atoms, and all constraints, have no greediness attribute (because
5289        they cannot match variable amounts of text anyway).
5290       </para>
5291      </listitem>
5292      <listitem>
5293       <para>
5294        Adding parentheses around an RE does not change its greediness.
5295       </para>
5296      </listitem>
5297      <listitem>
5298       <para>
5299        A quantified atom with a fixed-repetition quantifier
5300        (<literal>{</><replaceable>m</><literal>}</>
5301        or
5302        <literal>{</><replaceable>m</><literal>}?</>)
5303        has the same greediness (possibly none) as the atom itself.
5304       </para>
5305      </listitem>
5306      <listitem>
5307       <para>
5308        A quantified atom with other normal quantifiers (including
5309        <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</>
5310        with <replaceable>m</> equal to <replaceable>n</>)
5311        is greedy (prefers longest match).
5312       </para>
5313      </listitem>
5314      <listitem>
5315       <para>
5316        A quantified atom with a non-greedy quantifier (including
5317        <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</>
5318        with <replaceable>m</> equal to <replaceable>n</>)
5319        is non-greedy (prefers shortest match).
5320       </para>
5321      </listitem>
5322      <listitem>
5323       <para>
5324        A branch &mdash; that is, an RE that has no top-level
5325        <literal>|</> operator &mdash; has the same greediness as the first
5326        quantified atom in it that has a greediness attribute.
5327       </para>
5328      </listitem>
5329      <listitem>
5330       <para>
5331        An RE consisting of two or more branches connected by the
5332        <literal>|</> operator is always greedy.
5333       </para>
5334      </listitem>
5335     </itemizedlist>
5336    </para>
5337
5338    <para>
5339     The above rules associate greediness attributes not only with individual
5340     quantified atoms, but with branches and entire REs that contain quantified
5341     atoms.  What that means is that the matching is done in such a way that
5342     the branch, or whole RE, matches the longest or shortest possible
5343     substring <emphasis>as a whole</>.  Once the length of the entire match
5344     is determined, the part of it that matches any particular subexpression
5345     is determined on the basis of the greediness attribute of that
5346     subexpression, with subexpressions starting earlier in the RE taking
5347     priority over ones starting later.
5348    </para>
5349
5350    <para>
5351     An example of what this means:
5352 <screen>
5353 SELECT SUBSTRING('XY1234Z', 'Y*([0-9]{1,3})');
5354 <lineannotation>Result: </lineannotation><computeroutput>123</computeroutput>
5355 SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{1,3})');
5356 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
5357 </screen>
5358     In the first case, the RE as a whole is greedy because <literal>Y*</>
5359     is greedy.  It can match beginning at the <literal>Y</>, and it matches
5360     the longest possible string starting there, i.e., <literal>Y123</>.
5361     The output is the parenthesized part of that, or <literal>123</>.
5362     In the second case, the RE as a whole is non-greedy because <literal>Y*?</>
5363     is non-greedy.  It can match beginning at the <literal>Y</>, and it matches
5364     the shortest possible string starting there, i.e., <literal>Y1</>.
5365     The subexpression <literal>[0-9]{1,3}</> is greedy but it cannot change
5366     the decision as to the overall match length; so it is forced to match
5367     just <literal>1</>.
5368    </para>
5369
5370    <para>
5371     In short, when an RE contains both greedy and non-greedy subexpressions,
5372     the total match length is either as long as possible or as short as
5373     possible, according to the attribute assigned to the whole RE.  The
5374     attributes assigned to the subexpressions only affect how much of that
5375     match they are allowed to <quote>eat</> relative to each other.
5376    </para>
5377
5378    <para>
5379     The quantifiers <literal>{1,1}</> and <literal>{1,1}?</>
5380     can be used to force greediness or non-greediness, respectively,
5381     on a subexpression or a whole RE.
5382     This is useful when you need the whole RE to have a greediness attribute
5383     different from what's deduced from its elements.  As an example,
5384     suppose that we are trying to separate a string containing some digits
5385     into the digits and the parts before and after them.  We might try to
5386     do that like this:
5387 <screen>
5388 SELECT regexp_matches('abc01234xyz', '(.*)(\d+)(.*)');
5389 <lineannotation>Result: </lineannotation><computeroutput>{abc0123,4,xyz}</computeroutput>
5390 </screen>
5391     That didn't work: the first <literal>.*</> is greedy so
5392     it <quote>eats</> as much as it can, leaving the <literal>\d+</> to
5393     match at the last possible place, the last digit.  We might try to fix
5394     that by making it non-greedy:
5395 <screen>
5396 SELECT regexp_matches('abc01234xyz', '(.*?)(\d+)(.*)');
5397 <lineannotation>Result: </lineannotation><computeroutput>{abc,0,""}</computeroutput>
5398 </screen>
5399     That didn't work either, because now the RE as a whole is non-greedy
5400     and so it ends the overall match as soon as possible.  We can get what
5401     we want by forcing the RE as a whole to be greedy:
5402 <screen>
5403 SELECT regexp_matches('abc01234xyz', '(?:(.*?)(\d+)(.*)){1,1}');
5404 <lineannotation>Result: </lineannotation><computeroutput>{abc,01234,xyz}</computeroutput>
5405 </screen>
5406     Controlling the RE's overall greediness separately from its components'
5407     greediness allows great flexibility in handling variable-length patterns.
5408    </para>
5409
5410    <para>
5411     When deciding what is a longer or shorter match,
5412     match lengths are measured in characters, not collating elements.
5413     An empty string is considered longer than no match at all.
5414     For example:
5415     <literal>bb*</>
5416     matches the three middle characters of <literal>abbbc</>;
5417     <literal>(week|wee)(night|knights)</>
5418     matches all ten characters of <literal>weeknights</>;
5419     when <literal>(.*).*</>
5420     is matched against <literal>abc</> the parenthesized subexpression
5421     matches all three characters; and when
5422     <literal>(a*)*</> is matched against <literal>bc</>
5423     both the whole RE and the parenthesized
5424     subexpression match an empty string.
5425    </para>
5426
5427    <para>
5428     If case-independent matching is specified,
5429     the effect is much as if all case distinctions had vanished from the
5430     alphabet.
5431     When an alphabetic that exists in multiple cases appears as an
5432     ordinary character outside a bracket expression, it is effectively
5433     transformed into a bracket expression containing both cases,
5434     e.g., <literal>x</> becomes <literal>[xX]</>.
5435     When it appears inside a bracket expression, all case counterparts
5436     of it are added to the bracket expression, e.g.,
5437     <literal>[x]</> becomes <literal>[xX]</>
5438     and <literal>[^x]</> becomes <literal>[^xX]</>.
5439    </para>
5440
5441    <para>
5442     If newline-sensitive matching is specified, <literal>.</>
5443     and bracket expressions using <literal>^</>
5444     will never match the newline character
5445     (so that matches will never cross newlines unless the RE
5446     explicitly arranges it)
5447     and <literal>^</> and <literal>$</>
5448     will match the empty string after and before a newline
5449     respectively, in addition to matching at beginning and end of string
5450     respectively.
5451     But the ARE escapes <literal>\A</> and <literal>\Z</>
5452     continue to match beginning or end of string <emphasis>only</>.
5453    </para>
5454
5455    <para>
5456     If partial newline-sensitive matching is specified,
5457     this affects <literal>.</> and bracket expressions
5458     as with newline-sensitive matching, but not <literal>^</>
5459     and <literal>$</>.
5460    </para>
5461
5462    <para>
5463     If inverse partial newline-sensitive matching is specified,
5464     this affects <literal>^</> and <literal>$</>
5465     as with newline-sensitive matching, but not <literal>.</>
5466     and bracket expressions.
5467     This isn't very useful but is provided for symmetry.
5468    </para>
5469    </sect3>
5470
5471    <sect3 id="posix-limits-compatibility">
5472     <title>Limits and Compatibility</title>
5473
5474    <para>
5475     No particular limit is imposed on the length of REs in this
5476     implementation.  However,
5477     programs intended to be highly portable should not employ REs longer
5478     than 256 bytes,
5479     as a POSIX-compliant implementation can refuse to accept such REs.
5480    </para>
5481
5482    <para>
5483     The only feature of AREs that is actually incompatible with
5484     POSIX EREs is that <literal>\</> does not lose its special
5485     significance inside bracket expressions.
5486     All other ARE features use syntax which is illegal or has
5487     undefined or unspecified effects in POSIX EREs;
5488     the <literal>***</> syntax of directors likewise is outside the POSIX
5489     syntax for both BREs and EREs.
5490    </para>
5491
5492    <para>
5493     Many of the ARE extensions are borrowed from Perl, but some have
5494     been changed to clean them up, and a few Perl extensions are not present.
5495     Incompatibilities of note include <literal>\b</>, <literal>\B</>,
5496     the lack of special treatment for a trailing newline,
5497     the addition of complemented bracket expressions to the things
5498     affected by newline-sensitive matching,
5499     the restrictions on parentheses and back references in lookahead/lookbehind
5500     constraints, and the longest/shortest-match (rather than first-match)
5501     matching semantics.
5502    </para>
5503
5504    <para>
5505     Two significant incompatibilities exist between AREs and the ERE syntax
5506     recognized by pre-7.4 releases of <productname>PostgreSQL</>:
5507
5508     <itemizedlist>
5509      <listitem>
5510       <para>
5511        In AREs, <literal>\</> followed by an alphanumeric character is either
5512        an escape or an error, while in previous releases, it was just another
5513        way of writing the alphanumeric.
5514        This should not be much of a problem because there was no reason to
5515        write such a sequence in earlier releases.
5516       </para>
5517      </listitem>
5518      <listitem>
5519       <para>
5520        In AREs, <literal>\</> remains a special character within
5521        <literal>[]</>, so a literal <literal>\</> within a bracket
5522        expression must be written <literal>\\</>.
5523       </para>
5524      </listitem>
5525     </itemizedlist>
5526    </para>
5527    </sect3>
5528
5529    <sect3 id="posix-basic-regexes">
5530     <title>Basic Regular Expressions</title>
5531
5532    <para>
5533     BREs differ from EREs in several respects.
5534     In BREs, <literal>|</>, <literal>+</>, and <literal>?</>
5535     are ordinary characters and there is no equivalent
5536     for their functionality.
5537     The delimiters for bounds are
5538     <literal>\{</> and <literal>\}</>,
5539     with <literal>{</> and <literal>}</>
5540     by themselves ordinary characters.
5541     The parentheses for nested subexpressions are
5542     <literal>\(</> and <literal>\)</>,
5543     with <literal>(</> and <literal>)</> by themselves ordinary characters.
5544     <literal>^</> is an ordinary character except at the beginning of the
5545     RE or the beginning of a parenthesized subexpression,
5546     <literal>$</> is an ordinary character except at the end of the
5547     RE or the end of a parenthesized subexpression,
5548     and <literal>*</> is an ordinary character if it appears at the beginning
5549     of the RE or the beginning of a parenthesized subexpression
5550     (after a possible leading <literal>^</>).
5551     Finally, single-digit back references are available, and
5552     <literal>\&lt;</> and <literal>\&gt;</>
5553     are synonyms for
5554     <literal>[[:&lt;:]]</> and <literal>[[:&gt;:]]</>
5555     respectively; no other escapes are available in BREs.
5556    </para>
5557    </sect3>
5558
5559 <!-- end re_syntax.n man page -->
5560
5561   </sect2>
5562  </sect1>
5563
5564
5565   <sect1 id="functions-formatting">
5566    <title>Data Type Formatting Functions</title>
5567
5568    <indexterm>
5569     <primary>formatting</primary>
5570    </indexterm>
5571
5572    <para>
5573     The <productname>PostgreSQL</productname> formatting functions
5574     provide a powerful set of tools for converting various data types
5575     (date/time, integer, floating point, numeric) to formatted strings
5576     and for converting from formatted strings to specific data types.
5577     <xref linkend="functions-formatting-table"> lists them.
5578     These functions all follow a common calling convention: the first
5579     argument is the value to be formatted and the second argument is a
5580     template that defines the output or input format.
5581    </para>
5582
5583     <table id="functions-formatting-table">
5584      <title>Formatting Functions</title>
5585      <tgroup cols="4">
5586       <thead>
5587        <row>
5588         <entry>Function</entry>
5589         <entry>Return Type</entry>
5590         <entry>Description</entry>
5591         <entry>Example</entry>
5592        </row>
5593       </thead>
5594       <tbody>
5595        <row>
5596         <entry>
5597          <indexterm>
5598           <primary>to_char</primary>
5599          </indexterm>
5600          <literal><function>to_char(<type>timestamp</type>, <type>text</type>)</function></literal>
5601         </entry>
5602         <entry><type>text</type></entry>
5603         <entry>convert time stamp to string</entry>
5604         <entry><literal>to_char(current_timestamp, 'HH12:MI:SS')</literal></entry>
5605        </row>
5606        <row>
5607         <entry><literal><function>to_char(<type>interval</type>, <type>text</type>)</function></literal></entry>
5608         <entry><type>text</type></entry>
5609         <entry>convert interval to string</entry>
5610         <entry><literal>to_char(interval '15h&nbsp;2m&nbsp;12s', 'HH24:MI:SS')</literal></entry>
5611        </row>
5612        <row>
5613         <entry><literal><function>to_char(<type>int</type>, <type>text</type>)</function></literal></entry>
5614         <entry><type>text</type></entry>
5615         <entry>convert integer to string</entry>
5616         <entry><literal>to_char(125, '999')</literal></entry>
5617        </row>
5618        <row>
5619         <entry><literal><function>to_char</function>(<type>double precision</type>,
5620         <type>text</type>)</literal></entry>
5621         <entry><type>text</type></entry>
5622         <entry>convert real/double precision to string</entry>
5623         <entry><literal>to_char(125.8::real, '999D9')</literal></entry>
5624        </row>
5625        <row>
5626         <entry><literal><function>to_char(<type>numeric</type>, <type>text</type>)</function></literal></entry>
5627         <entry><type>text</type></entry>
5628         <entry>convert numeric to string</entry>
5629         <entry><literal>to_char(-125.8, '999D99S')</literal></entry>
5630        </row>
5631        <row>
5632         <entry>
5633          <indexterm>
5634           <primary>to_date</primary>
5635          </indexterm>
5636          <literal><function>to_date(<type>text</type>, <type>text</type>)</function></literal>
5637         </entry>
5638         <entry><type>date</type></entry>
5639         <entry>convert string to date</entry>
5640         <entry><literal>to_date('05&nbsp;Dec&nbsp;2000', 'DD&nbsp;Mon&nbsp;YYYY')</literal></entry>
5641        </row>
5642        <row>
5643         <entry>
5644          <indexterm>
5645           <primary>to_number</primary>
5646          </indexterm>
5647          <literal><function>to_number(<type>text</type>, <type>text</type>)</function></literal>
5648         </entry>
5649         <entry><type>numeric</type></entry>
5650         <entry>convert string to numeric</entry>
5651         <entry><literal>to_number('12,454.8-', '99G999D9S')</literal></entry>
5652        </row>
5653        <row>
5654         <entry>
5655          <indexterm>
5656           <primary>to_timestamp</primary>
5657          </indexterm>
5658          <literal><function>to_timestamp(<type>text</type>, <type>text</type>)</function></literal>
5659         </entry>
5660         <entry><type>timestamp with time zone</type></entry>
5661         <entry>convert string to time stamp</entry>
5662         <entry><literal>to_timestamp('05&nbsp;Dec&nbsp;2000', 'DD&nbsp;Mon&nbsp;YYYY')</literal></entry>
5663        </row>
5664       </tbody>
5665      </tgroup>
5666     </table>
5667
5668    <note>
5669     <para>
5670      There is also a single-argument <function>to_timestamp</function>
5671      function; see <xref linkend="functions-datetime-table">.
5672     </para>
5673    </note>
5674
5675    <para>
5676     In a <function>to_char</> output template string, there are certain
5677     patterns that are recognized and replaced with appropriately-formatted
5678     data based on the given value.  Any text that is not a template pattern is
5679     simply copied verbatim.  Similarly, in an input template string (for the
5680     other functions), template patterns identify the values to be supplied by
5681     the input data string.
5682    </para>
5683
5684   <para>
5685    <xref linkend="functions-formatting-datetime-table"> shows the
5686    template patterns available for formatting date and time values.
5687   </para>
5688
5689     <table id="functions-formatting-datetime-table">
5690      <title>Template Patterns for Date/Time Formatting</title>
5691      <tgroup cols="2">
5692       <thead>
5693        <row>
5694         <entry>Pattern</entry>
5695         <entry>Description</entry>
5696        </row>
5697       </thead>
5698       <tbody>
5699        <row>
5700         <entry><literal>HH</literal></entry>
5701         <entry>hour of day (01-12)</entry>
5702        </row>
5703        <row>
5704         <entry><literal>HH12</literal></entry>
5705         <entry>hour of day (01-12)</entry>
5706        </row>
5707        <row>
5708         <entry><literal>HH24</literal></entry>
5709         <entry>hour of day (00-23)</entry>
5710        </row>
5711        <row>
5712         <entry><literal>MI</literal></entry>
5713         <entry>minute (00-59)</entry>
5714        </row>
5715        <row>
5716         <entry><literal>SS</literal></entry>
5717         <entry>second (00-59)</entry>
5718        </row>
5719        <row>
5720         <entry><literal>MS</literal></entry>
5721         <entry>millisecond (000-999)</entry>
5722        </row>
5723        <row>
5724         <entry><literal>US</literal></entry>
5725         <entry>microsecond (000000-999999)</entry>
5726        </row>
5727        <row>
5728         <entry><literal>SSSS</literal></entry>
5729         <entry>seconds past midnight (0-86399)</entry>
5730        </row>
5731        <row>
5732         <entry><literal>AM</literal>, <literal>am</literal>,
5733         <literal>PM</literal> or <literal>pm</literal></entry>
5734         <entry>meridiem indicator (without periods)</entry>
5735        </row>
5736        <row>
5737         <entry><literal>A.M.</literal>, <literal>a.m.</literal>,
5738         <literal>P.M.</literal> or <literal>p.m.</literal></entry>
5739         <entry>meridiem indicator (with periods)</entry>
5740        </row>
5741        <row>
5742         <entry><literal>Y,YYY</literal></entry>
5743         <entry>year (4 or more digits) with comma</entry>
5744        </row>
5745        <row>
5746         <entry><literal>YYYY</literal></entry>
5747         <entry>year (4 or more digits)</entry>
5748        </row>
5749        <row>
5750         <entry><literal>YYY</literal></entry>
5751         <entry>last 3 digits of year</entry>
5752        </row>
5753        <row>
5754         <entry><literal>YY</literal></entry>
5755         <entry>last 2 digits of year</entry>
5756        </row>
5757        <row>
5758         <entry><literal>Y</literal></entry>
5759         <entry>last digit of year</entry>
5760        </row>
5761        <row>
5762         <entry><literal>IYYY</literal></entry>
5763         <entry>ISO 8601 week-numbering year (4 or more digits)</entry>
5764        </row>
5765        <row>
5766         <entry><literal>IYY</literal></entry>
5767         <entry>last 3 digits of ISO 8601 week-numbering year</entry>
5768        </row>
5769        <row>
5770         <entry><literal>IY</literal></entry>
5771         <entry>last 2 digits of ISO 8601 week-numbering year</entry>
5772        </row>
5773        <row>
5774         <entry><literal>I</literal></entry>
5775         <entry>last digit of ISO 8601 week-numbering year</entry>
5776        </row>
5777        <row>
5778         <entry><literal>BC</literal>, <literal>bc</literal>,
5779         <literal>AD</literal> or <literal>ad</literal></entry>
5780         <entry>era indicator (without periods)</entry>
5781        </row>
5782        <row>
5783         <entry><literal>B.C.</literal>, <literal>b.c.</literal>,
5784         <literal>A.D.</literal> or <literal>a.d.</literal></entry>
5785         <entry>era indicator (with periods)</entry>
5786        </row>
5787        <row>
5788         <entry><literal>MONTH</literal></entry>
5789         <entry>full upper case month name (blank-padded to 9 chars)</entry>
5790        </row>
5791        <row>
5792         <entry><literal>Month</literal></entry>
5793         <entry>full capitalized month name (blank-padded to 9 chars)</entry>
5794        </row>
5795        <row>
5796         <entry><literal>month</literal></entry>
5797         <entry>full lower case month name (blank-padded to 9 chars)</entry>
5798        </row>
5799        <row>
5800         <entry><literal>MON</literal></entry>
5801         <entry>abbreviated upper case month name (3 chars in English, localized lengths vary)</entry>
5802        </row>
5803        <row>
5804         <entry><literal>Mon</literal></entry>
5805         <entry>abbreviated capitalized month name (3 chars in English, localized lengths vary)</entry>
5806        </row>
5807        <row>
5808         <entry><literal>mon</literal></entry>
5809         <entry>abbreviated lower case month name (3 chars in English, localized lengths vary)</entry>
5810        </row>
5811        <row>
5812         <entry><literal>MM</literal></entry>
5813         <entry>month number (01-12)</entry>
5814        </row>
5815        <row>
5816         <entry><literal>DAY</literal></entry>
5817         <entry>full upper case day name (blank-padded to 9 chars)</entry>
5818        </row>
5819        <row>
5820         <entry><literal>Day</literal></entry>
5821         <entry>full capitalized day name (blank-padded to 9 chars)</entry>
5822        </row>
5823        <row>
5824         <entry><literal>day</literal></entry>
5825         <entry>full lower case day name (blank-padded to 9 chars)</entry>
5826        </row>
5827        <row>
5828         <entry><literal>DY</literal></entry>
5829         <entry>abbreviated upper case day name (3 chars in English, localized lengths vary)</entry>
5830        </row>
5831        <row>
5832         <entry><literal>Dy</literal></entry>
5833         <entry>abbreviated capitalized day name (3 chars in English, localized lengths vary)</entry>
5834        </row>
5835        <row>
5836         <entry><literal>dy</literal></entry>
5837         <entry>abbreviated lower case day name (3 chars in English, localized lengths vary)</entry>
5838        </row>
5839        <row>
5840         <entry><literal>DDD</literal></entry>
5841         <entry>day of year (001-366)</entry>
5842        </row>
5843        <row>
5844         <entry><literal>IDDD</literal></entry>
5845         <entry>day of ISO 8601 week-numbering year (001-371; day 1 of the year is Monday of the first ISO week)</entry>
5846        </row>
5847        <row>
5848         <entry><literal>DD</literal></entry>
5849         <entry>day of month (01-31)</entry>
5850        </row>
5851        <row>
5852         <entry><literal>D</literal></entry>
5853         <entry>day of the week, Sunday (<literal>1</>) to Saturday (<literal>7</>)</entry>
5854        </row>
5855        <row>
5856         <entry><literal>ID</literal></entry>
5857         <entry>ISO 8601 day of the week, Monday (<literal>1</>) to Sunday (<literal>7</>)</entry>
5858        </row>
5859        <row>
5860         <entry><literal>W</literal></entry>
5861         <entry>week of month (1-5) (the first week starts on the first day of the month)</entry>
5862        </row>
5863        <row>
5864         <entry><literal>WW</literal></entry>
5865         <entry>week number of year (1-53) (the first week starts on the first day of the year)</entry>
5866        </row>
5867        <row>
5868         <entry><literal>IW</literal></entry>
5869         <entry>week number of ISO 8601 week-numbering year (01-53; the first Thursday of the year is in week 1)</entry>
5870        </row>
5871        <row>
5872         <entry><literal>CC</literal></entry>
5873         <entry>century (2 digits) (the twenty-first century starts on 2001-01-01)</entry>
5874        </row>
5875        <row>
5876         <entry><literal>J</literal></entry>
5877         <entry>Julian Day (integer days since November 24, 4714 BC at midnight UTC)</entry>
5878        </row>
5879        <row>
5880         <entry><literal>Q</literal></entry>
5881         <entry>quarter (ignored by <function>to_date</> and <function>to_timestamp</>)</entry>
5882        </row>
5883        <row>
5884         <entry><literal>RM</literal></entry>
5885         <entry>month in upper case Roman numerals (I-XII; I=January)</entry>
5886        </row>
5887        <row>
5888         <entry><literal>rm</literal></entry>
5889         <entry>month in lower case Roman numerals (i-xii; i=January)</entry>
5890        </row>
5891        <row>
5892         <entry><literal>TZ</literal></entry>
5893         <entry>upper case time-zone name</entry>
5894        </row>
5895        <row>
5896         <entry><literal>tz</literal></entry>
5897         <entry>lower case time-zone name</entry>
5898        </row>
5899        <row>
5900         <entry><literal>OF</literal></entry>
5901         <entry>time-zone offset</entry>
5902        </row>
5903       </tbody>
5904      </tgroup>
5905     </table>
5906
5907    <para>
5908     Modifiers can be applied to any template pattern to alter its
5909     behavior.  For example, <literal>FMMonth</literal>
5910     is the <literal>Month</literal> pattern with the
5911     <literal>FM</literal> modifier.
5912     <xref linkend="functions-formatting-datetimemod-table"> shows the
5913     modifier patterns for date/time formatting.
5914    </para>
5915
5916     <table id="functions-formatting-datetimemod-table">
5917      <title>Template Pattern Modifiers for Date/Time Formatting</title>
5918      <tgroup cols="3">
5919       <thead>
5920        <row>
5921         <entry>Modifier</entry>
5922         <entry>Description</entry>
5923         <entry>Example</entry>
5924        </row>
5925       </thead>
5926       <tbody>
5927        <row>
5928         <entry><literal>FM</literal> prefix</entry>
5929         <entry>fill mode (suppress leading zeroes and padding blanks)</entry>
5930         <entry><literal>FMMonth</literal></entry>
5931        </row>
5932        <row>
5933         <entry><literal>TH</literal> suffix</entry>
5934         <entry>upper case ordinal number suffix</entry>
5935         <entry><literal>DDTH</literal>, e.g., <literal>12TH</></entry>
5936        </row>
5937        <row>
5938         <entry><literal>th</literal> suffix</entry>
5939         <entry>lower case ordinal number suffix</entry>
5940         <entry><literal>DDth</literal>, e.g., <literal>12th</></entry>
5941        </row>
5942        <row>
5943         <entry><literal>FX</literal> prefix</entry>
5944         <entry>fixed format global option (see usage notes)</entry>
5945         <entry><literal>FX&nbsp;Month&nbsp;DD&nbsp;Day</literal></entry>
5946        </row>
5947        <row>
5948         <entry><literal>TM</literal> prefix</entry>
5949         <entry>translation mode (print localized day and month names based on
5950          <xref linkend="guc-lc-time">)</entry>
5951         <entry><literal>TMMonth</literal></entry>
5952        </row>
5953        <row>
5954         <entry><literal>SP</literal> suffix</entry>
5955         <entry>spell mode (not implemented)</entry>
5956         <entry><literal>DDSP</literal></entry>
5957        </row>
5958       </tbody>
5959      </tgroup>
5960     </table>
5961
5962    <para>
5963     Usage notes for date/time formatting:
5964
5965     <itemizedlist>
5966      <listitem>
5967       <para>
5968        <literal>FM</literal> suppresses leading zeroes and trailing blanks
5969        that would otherwise be added to make the output of a pattern be
5970        fixed-width.  In <productname>PostgreSQL</productname>,
5971        <literal>FM</literal> modifies only the next specification, while in
5972        Oracle <literal>FM</literal> affects all subsequent
5973        specifications, and repeated <literal>FM</literal> modifiers
5974        toggle fill mode on and off.
5975       </para>
5976      </listitem>
5977
5978      <listitem>
5979       <para>
5980        <literal>TM</literal> does not include trailing blanks.
5981        <function>to_timestamp</> and <function>to_date</> ignore
5982        the <literal>TM</literal> modifier.
5983       </para>
5984      </listitem>
5985
5986      <listitem>
5987       <para>
5988        <function>to_timestamp</function> and <function>to_date</function>
5989        skip multiple blank spaces in the input string unless the
5990        <literal>FX</literal> option is used. For example,
5991        <literal>to_timestamp('2000&nbsp;&nbsp;&nbsp;&nbsp;JUN', 'YYYY MON')</literal> works, but
5992        <literal>to_timestamp('2000&nbsp;&nbsp;&nbsp;&nbsp;JUN', 'FXYYYY MON')</literal> returns an error
5993        because <function>to_timestamp</function> expects one space only.
5994        <literal>FX</literal> must be specified as the first item in
5995        the template.
5996       </para>
5997      </listitem>
5998
5999      <listitem>
6000       <para>
6001        <function>to_timestamp</function> and <function>to_date</function>
6002        exist to handle input formats that cannot be converted by
6003        simple casting.  These functions interpret input liberally,
6004        with minimal error checking.  While they produce valid output,
6005        the conversion can yield unexpected results.  For example,
6006        input to these functions is not restricted by normal ranges,
6007        thus <literal>to_date('20096040','YYYYMMDD')</literal> returns
6008        <literal>2014-01-17</literal> rather than causing an error.
6009        Casting does not have this behavior.
6010       </para>
6011      </listitem>
6012
6013      <listitem>
6014       <para>
6015        Ordinary text is allowed in <function>to_char</function>
6016        templates and will be output literally.  You can put a substring
6017        in double quotes to force it to be interpreted as literal text
6018        even if it contains pattern key words.  For example, in
6019        <literal>'"Hello Year "YYYY'</literal>, the <literal>YYYY</literal>
6020        will be replaced by the year data, but the single <literal>Y</literal> in <literal>Year</literal>
6021        will not be.  In <function>to_date</>, <function>to_number</>,
6022        and <function>to_timestamp</>, double-quoted strings skip the number of
6023        input characters contained in the string, e.g. <literal>"XX"</>
6024        skips two input characters.
6025       </para>
6026      </listitem>
6027
6028      <listitem>
6029       <para>
6030        If you want to have a double quote in the output you must
6031        precede it with a backslash, for example <literal>'\"YYYY
6032        Month\"'</literal>. <!-- "" font-lock sanity :-) -->
6033       </para>
6034      </listitem>
6035
6036      <listitem>
6037       <para>
6038        If the year format specification is less than four digits, e.g.
6039        <literal>YYY</>, and the supplied year is less than four digits,
6040        the year will be adjusted to be nearest to the year 2020, e.g.
6041        <literal>95</> becomes 1995.
6042       </para>
6043      </listitem>
6044
6045      <listitem>
6046       <para>
6047        The <literal>YYYY</literal> conversion from string to <type>timestamp</type> or
6048        <type>date</type> has a restriction when processing years with more than 4 digits. You must
6049        use some non-digit character or template after <literal>YYYY</literal>,
6050        otherwise the year is always interpreted as 4 digits. For example
6051        (with the year 20000):
6052        <literal>to_date('200001131', 'YYYYMMDD')</literal> will be
6053        interpreted as a 4-digit year; instead use a non-digit
6054        separator after the year, like
6055        <literal>to_date('20000-1131', 'YYYY-MMDD')</literal> or
6056        <literal>to_date('20000Nov31', 'YYYYMonDD')</literal>.
6057       </para>
6058      </listitem>
6059
6060      <listitem>
6061       <para>
6062        In conversions from string to <type>timestamp</type> or
6063        <type>date</type>, the <literal>CC</literal> (century) field is ignored
6064        if there is a <literal>YYY</literal>, <literal>YYYY</literal> or
6065        <literal>Y,YYY</literal> field. If <literal>CC</literal> is used with
6066        <literal>YY</literal> or <literal>Y</literal> then the year is computed
6067        as the year in the specified century.  If the century is
6068        specified but the year is not, the first year of the century
6069        is assumed.
6070       </para>
6071      </listitem>
6072
6073      <listitem>
6074       <para>
6075        An ISO 8601 week-numbering date (as distinct from a Gregorian date)
6076        can be specified to <function>to_timestamp</function> and
6077        <function>to_date</function> in one of two ways:
6078        <itemizedlist>
6079         <listitem>
6080          <para>
6081           Year, week number, and weekday:  for
6082           example <literal>to_date('2006-42-4', 'IYYY-IW-ID')</literal>
6083           returns the date <literal>2006-10-19</literal>.
6084           If you omit the weekday it is assumed to be 1 (Monday).
6085          </para>
6086         </listitem>
6087         <listitem>
6088          <para>
6089           Year and day of year:  for example <literal>to_date('2006-291',
6090           'IYYY-IDDD')</literal> also returns <literal>2006-10-19</literal>.
6091          </para>
6092         </listitem>
6093        </itemizedlist>
6094       </para>
6095       <para>
6096        Attempting to enter a date using a mixture of ISO 8601 week-numbering
6097        fields and Gregorian date fields is nonsensical, and will cause an
6098        error.  In the context of an ISO 8601 week-numbering year, the
6099        concept of a <quote>month</> or <quote>day of month</> has no
6100        meaning.  In the context of a Gregorian year, the ISO week has no
6101        meaning.
6102       </para>
6103       <caution>
6104        <para>
6105         While <function>to_date</function> will reject a mixture of
6106         Gregorian and ISO week-numbering date
6107         fields, <function>to_char</function> will not, since output format
6108         specifications like <literal>YYYY-MM-DD (IYYY-IDDD)</> can be
6109         useful.  But avoid writing something like <literal>IYYY-MM-DD</>;
6110         that would yield surprising results near the start of the year.
6111         (See <xref linkend="functions-datetime-extract"> for more
6112         information.)
6113        </para>
6114       </caution>
6115      </listitem>
6116
6117      <listitem>
6118       <para>
6119        In a conversion from string to <type>timestamp</type>, millisecond
6120        (<literal>MS</literal>) or microsecond (<literal>US</literal>)
6121        values are used as the
6122        seconds digits after the decimal point. For example
6123        <literal>to_timestamp('12:3', 'SS:MS')</literal> is not 3 milliseconds,
6124        but 300, because the conversion counts it as 12 + 0.3 seconds.
6125        This means for the format <literal>SS:MS</literal>, the input values
6126        <literal>12:3</literal>, <literal>12:30</literal>, and <literal>12:300</literal> specify the
6127        same number of milliseconds. To get three milliseconds, one must use
6128        <literal>12:003</literal>, which the conversion counts as
6129        12 + 0.003 = 12.003 seconds.
6130       </para>
6131
6132       <para>
6133        Here is a more
6134        complex example:
6135        <literal>to_timestamp('15:12:02.020.001230', 'HH:MI:SS.MS.US')</literal>
6136        is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds +
6137        1230 microseconds = 2.021230 seconds.
6138       </para>
6139      </listitem>
6140
6141      <listitem>
6142       <para>
6143         <function>to_char(..., 'ID')</function>'s day of the week numbering
6144         matches the <function>extract(isodow from ...)</function> function, but
6145         <function>to_char(..., 'D')</function>'s does not match
6146         <function>extract(dow from ...)</function>'s day numbering.
6147       </para>
6148      </listitem>
6149
6150      <listitem>
6151       <para>
6152         <function>to_char(interval)</function> formats <literal>HH</> and
6153         <literal>HH12</> as shown on a 12-hour clock, i.e. zero hours
6154         and 36 hours output as <literal>12</>, while <literal>HH24</>
6155         outputs the full hour value, which can exceed 23 for intervals.
6156       </para>
6157      </listitem>
6158
6159     </itemizedlist>
6160    </para>
6161
6162   <para>
6163    <xref linkend="functions-formatting-numeric-table"> shows the
6164    template patterns available for formatting numeric values.
6165   </para>
6166
6167     <table id="functions-formatting-numeric-table">
6168      <title>Template Patterns for Numeric Formatting</title>
6169      <tgroup cols="2">
6170       <thead>
6171        <row>
6172         <entry>Pattern</entry>
6173         <entry>Description</entry>
6174        </row>
6175       </thead>
6176       <tbody>
6177        <row>
6178         <entry><literal>9</literal></entry>
6179         <entry>value with the specified number of digits</entry>
6180        </row>
6181        <row>
6182         <entry><literal>0</literal></entry>
6183         <entry>value with leading zeros</entry>
6184        </row>
6185        <row>
6186         <entry><literal>.</literal> (period)</entry>
6187         <entry>decimal point</entry>
6188        </row>
6189        <row>
6190         <entry><literal>,</literal> (comma)</entry>
6191         <entry>group (thousand) separator</entry>
6192        </row>
6193        <row>
6194         <entry><literal>PR</literal></entry>
6195         <entry>negative value in angle brackets</entry>
6196        </row>
6197        <row>
6198         <entry><literal>S</literal></entry>
6199         <entry>sign anchored to number (uses locale)</entry>
6200        </row>
6201        <row>
6202         <entry><literal>L</literal></entry>
6203         <entry>currency symbol (uses locale)</entry>
6204        </row>
6205        <row>
6206         <entry><literal>D</literal></entry>
6207         <entry>decimal point (uses locale)</entry>
6208        </row>
6209        <row>
6210         <entry><literal>G</literal></entry>
6211         <entry>group separator (uses locale)</entry>
6212        </row>
6213        <row>
6214         <entry><literal>MI</literal></entry>
6215         <entry>minus sign in specified position (if number &lt; 0)</entry>
6216        </row>
6217        <row>
6218         <entry><literal>PL</literal></entry>
6219         <entry>plus sign in specified position (if number &gt; 0)</entry>
6220        </row>
6221        <row>
6222         <entry><literal>SG</literal></entry>
6223         <entry>plus/minus sign in specified position</entry>
6224        </row>
6225        <row>
6226         <entry><literal>RN</literal></entry>
6227         <entry>Roman numeral (input between 1 and 3999)</entry>
6228        </row>
6229        <row>
6230         <entry><literal>TH</literal> or <literal>th</literal></entry>
6231         <entry>ordinal number suffix</entry>
6232        </row>
6233        <row>
6234         <entry><literal>V</literal></entry>
6235         <entry>shift specified number of digits (see notes)</entry>
6236        </row>
6237        <row>
6238         <entry><literal>EEEE</literal></entry>
6239         <entry>exponent for scientific notation</entry>
6240        </row>
6241       </tbody>
6242      </tgroup>
6243     </table>
6244
6245    <para>
6246     Usage notes for numeric formatting:
6247
6248     <itemizedlist>
6249      <listitem>
6250       <para>
6251        A sign formatted using <literal>SG</literal>, <literal>PL</literal>, or
6252        <literal>MI</literal> is not anchored to
6253        the number; for example,
6254        <literal>to_char(-12, 'MI9999')</literal> produces <literal>'-&nbsp;&nbsp;12'</literal>
6255        but <literal>to_char(-12, 'S9999')</literal> produces <literal>'&nbsp;&nbsp;-12'</literal>.
6256        The Oracle implementation does not allow the use of
6257        <literal>MI</literal> before <literal>9</literal>, but rather
6258        requires that <literal>9</literal> precede
6259        <literal>MI</literal>.
6260       </para>
6261      </listitem>
6262
6263      <listitem>
6264       <para>
6265        <literal>9</literal> results in a value with the same number of
6266        digits as there are <literal>9</literal>s. If a digit is
6267        not available it outputs a space.
6268       </para>
6269      </listitem>
6270
6271      <listitem>
6272       <para>
6273        <literal>TH</literal> does not convert values less than zero
6274        and does not convert fractional numbers.
6275       </para>
6276      </listitem>
6277
6278      <listitem>
6279       <para>
6280        <literal>PL</literal>, <literal>SG</literal>, and
6281        <literal>TH</literal> are <productname>PostgreSQL</productname>
6282        extensions.
6283       </para>
6284      </listitem>
6285
6286      <listitem>
6287       <para>
6288        <literal>V</literal> with <function>to_char</function>
6289        multiplies the input values by
6290        <literal>10^<replaceable>n</replaceable></literal>, where
6291        <replaceable>n</replaceable> is the number of digits following
6292        <literal>V</literal>.  <literal>V</literal> with
6293        <function>to_number</function> divides in a similar manner.
6294        <function>to_char</function> and <function>to_number</function>
6295        do not support the use of
6296        <literal>V</literal> combined with a decimal point
6297        (e.g., <literal>99.9V99</literal> is not allowed).
6298       </para>
6299      </listitem>
6300
6301      <listitem>
6302       <para>
6303        <literal>EEEE</literal> (scientific notation) cannot be used in
6304        combination with any of the other formatting patterns or
6305        modifiers other than digit and decimal point patterns, and must be at the end of the format string
6306        (e.g., <literal>9.99EEEE</literal> is a valid pattern).
6307       </para>
6308      </listitem>
6309     </itemizedlist>
6310    </para>
6311
6312    <para>
6313     Certain modifiers can be applied to any template pattern to alter its
6314     behavior.  For example, <literal>FM9999</literal>
6315     is the <literal>9999</literal> pattern with the
6316     <literal>FM</literal> modifier.
6317     <xref linkend="functions-formatting-numericmod-table"> shows the
6318     modifier patterns for numeric formatting.
6319    </para>
6320
6321     <table id="functions-formatting-numericmod-table">
6322      <title>Template Pattern Modifiers for Numeric Formatting</title>
6323      <tgroup cols="3">
6324       <thead>
6325        <row>
6326         <entry>Modifier</entry>
6327         <entry>Description</entry>
6328         <entry>Example</entry>
6329        </row>
6330       </thead>
6331       <tbody>
6332        <row>
6333         <entry><literal>FM</literal> prefix</entry>
6334         <entry>fill mode (suppress leading zeroes and padding blanks)</entry>
6335         <entry><literal>FM9999</literal></entry>
6336        </row>
6337        <row>
6338         <entry><literal>TH</literal> suffix</entry>
6339         <entry>upper case ordinal number suffix</entry>
6340         <entry><literal>999TH</literal></entry>
6341        </row>
6342        <row>
6343         <entry><literal>th</literal> suffix</entry>
6344         <entry>lower case ordinal number suffix</entry>
6345         <entry><literal>999th</literal></entry>
6346        </row>
6347       </tbody>
6348      </tgroup>
6349     </table>
6350
6351   <para>
6352    <xref linkend="functions-formatting-examples-table"> shows some
6353    examples of the use of the <function>to_char</function> function.
6354   </para>
6355
6356     <table id="functions-formatting-examples-table">
6357      <title><function>to_char</function> Examples</title>
6358      <tgroup cols="2">
6359       <thead>
6360        <row>
6361         <entry>Expression</entry>
6362         <entry>Result</entry>
6363        </row>
6364       </thead>
6365       <tbody>
6366        <row>
6367         <entry><literal>to_char(current_timestamp, 'Day,&nbsp;DD&nbsp;&nbsp;HH12:MI:SS')</literal></entry>
6368         <entry><literal>'Tuesday&nbsp;&nbsp;,&nbsp;06&nbsp;&nbsp;05:39:18'</literal></entry>
6369        </row>
6370        <row>
6371         <entry><literal>to_char(current_timestamp, 'FMDay,&nbsp;FMDD&nbsp;&nbsp;HH12:MI:SS')</literal></entry>
6372         <entry><literal>'Tuesday,&nbsp;6&nbsp;&nbsp;05:39:18'</literal></entry>
6373        </row>
6374        <row>
6375         <entry><literal>to_char(-0.1, '99.99')</literal></entry>
6376         <entry><literal>'&nbsp;&nbsp;-.10'</literal></entry>
6377        </row>
6378        <row>
6379         <entry><literal>to_char(-0.1, 'FM9.99')</literal></entry>
6380         <entry><literal>'-.1'</literal></entry>
6381        </row>
6382        <row>
6383         <entry><literal>to_char(0.1, '0.9')</literal></entry>
6384         <entry><literal>'&nbsp;0.1'</literal></entry>
6385        </row>
6386        <row>
6387         <entry><literal>to_char(12, '9990999.9')</literal></entry>
6388         <entry><literal>'&nbsp;&nbsp;&nbsp;&nbsp;0012.0'</literal></entry>
6389        </row>
6390        <row>
6391         <entry><literal>to_char(12, 'FM9990999.9')</literal></entry>
6392         <entry><literal>'0012.'</literal></entry>
6393        </row>
6394        <row>
6395         <entry><literal>to_char(485, '999')</literal></entry>
6396         <entry><literal>'&nbsp;485'</literal></entry>
6397        </row>
6398        <row>
6399         <entry><literal>to_char(-485, '999')</literal></entry>
6400         <entry><literal>'-485'</literal></entry>
6401        </row>
6402        <row>
6403         <entry><literal>to_char(485, '9&nbsp;9&nbsp;9')</literal></entry>
6404         <entry><literal>'&nbsp;4&nbsp;8&nbsp;5'</literal></entry>
6405        </row>
6406        <row>
6407         <entry><literal>to_char(1485, '9,999')</literal></entry>
6408         <entry><literal>'&nbsp;1,485'</literal></entry>
6409        </row>
6410        <row>
6411         <entry><literal>to_char(1485, '9G999')</literal></entry>
6412         <entry><literal>'&nbsp;1&nbsp;485'</literal></entry>
6413        </row>
6414        <row>
6415         <entry><literal>to_char(148.5, '999.999')</literal></entry>
6416         <entry><literal>'&nbsp;148.500'</literal></entry>
6417        </row>
6418        <row>
6419         <entry><literal>to_char(148.5, 'FM999.999')</literal></entry>
6420         <entry><literal>'148.5'</literal></entry>
6421        </row>
6422        <row>
6423         <entry><literal>to_char(148.5, 'FM999.990')</literal></entry>
6424         <entry><literal>'148.500'</literal></entry>
6425        </row>
6426        <row>
6427         <entry><literal>to_char(148.5, '999D999')</literal></entry>
6428         <entry><literal>'&nbsp;148,500'</literal></entry>
6429        </row>
6430        <row>
6431         <entry><literal>to_char(3148.5, '9G999D999')</literal></entry>
6432         <entry><literal>'&nbsp;3&nbsp;148,500'</literal></entry>
6433        </row>
6434        <row>
6435         <entry><literal>to_char(-485, '999S')</literal></entry>
6436         <entry><literal>'485-'</literal></entry>
6437        </row>
6438        <row>
6439         <entry><literal>to_char(-485, '999MI')</literal></entry>
6440         <entry><literal>'485-'</literal></entry>
6441        </row>
6442        <row>
6443         <entry><literal>to_char(485, '999MI')</literal></entry>
6444         <entry><literal>'485&nbsp;'</literal></entry>
6445        </row>
6446        <row>
6447         <entry><literal>to_char(485, 'FM999MI')</literal></entry>
6448         <entry><literal>'485'</literal></entry>
6449        </row>
6450        <row>
6451         <entry><literal>to_char(485, 'PL999')</literal></entry>
6452         <entry><literal>'+485'</literal></entry>
6453        </row>
6454        <row>
6455         <entry><literal>to_char(485, 'SG999')</literal></entry>
6456         <entry><literal>'+485'</literal></entry>
6457        </row>
6458        <row>
6459         <entry><literal>to_char(-485, 'SG999')</literal></entry>
6460         <entry><literal>'-485'</literal></entry>
6461        </row>
6462        <row>
6463         <entry><literal>to_char(-485, '9SG99')</literal></entry>
6464         <entry><literal>'4-85'</literal></entry>
6465        </row>
6466        <row>
6467         <entry><literal>to_char(-485, '999PR')</literal></entry>
6468         <entry><literal>'&lt;485&gt;'</literal></entry>
6469        </row>
6470        <row>
6471         <entry><literal>to_char(485, 'L999')</literal></entry>
6472         <entry><literal>'DM&nbsp;485'</literal></entry>
6473        </row>
6474        <row>
6475         <entry><literal>to_char(485, 'RN')</literal></entry>
6476         <entry><literal>'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CDLXXXV'</literal></entry>
6477        </row>
6478        <row>
6479         <entry><literal>to_char(485, 'FMRN')</literal></entry>
6480         <entry><literal>'CDLXXXV'</literal></entry>
6481        </row>
6482        <row>
6483         <entry><literal>to_char(5.2, 'FMRN')</literal></entry>
6484         <entry><literal>'V'</literal></entry>
6485        </row>
6486        <row>
6487         <entry><literal>to_char(482, '999th')</literal></entry>
6488         <entry><literal>'&nbsp;482nd'</literal></entry>
6489        </row>
6490        <row>
6491         <entry><literal>to_char(485, '"Good&nbsp;number:"999')</literal></entry>
6492         <entry><literal>'Good&nbsp;number:&nbsp;485'</literal></entry>
6493        </row>
6494        <row>
6495         <entry><literal>to_char(485.8, '"Pre:"999"&nbsp;Post:"&nbsp;.999')</literal></entry>
6496         <entry><literal>'Pre:&nbsp;485&nbsp;Post:&nbsp;.800'</literal></entry>
6497        </row>
6498        <row>
6499         <entry><literal>to_char(12, '99V999')</literal></entry>
6500         <entry><literal>'&nbsp;12000'</literal></entry>
6501        </row>
6502        <row>
6503         <entry><literal>to_char(12.4, '99V999')</literal></entry>
6504         <entry><literal>'&nbsp;12400'</literal></entry>
6505        </row>
6506        <row>
6507         <entry><literal>to_char(12.45, '99V9')</literal></entry>
6508         <entry><literal>'&nbsp;125'</literal></entry>
6509        </row>
6510        <row>
6511         <entry><literal>to_char(0.0004859, '9.99EEEE')</literal></entry>
6512         <entry><literal>' 4.86e-04'</literal></entry>
6513        </row>
6514       </tbody>
6515      </tgroup>
6516     </table>
6517
6518   </sect1>
6519
6520
6521   <sect1 id="functions-datetime">
6522    <title>Date/Time Functions and Operators</title>
6523
6524   <para>
6525    <xref linkend="functions-datetime-table"> shows the available
6526    functions for date/time value processing, with details appearing in
6527    the following subsections.  <xref
6528    linkend="operators-datetime-table"> illustrates the behaviors of
6529    the basic arithmetic operators (<literal>+</literal>,
6530    <literal>*</literal>, etc.).  For formatting functions, refer to
6531    <xref linkend="functions-formatting">.  You should be familiar with
6532    the background information on date/time data types from <xref
6533    linkend="datatype-datetime">.
6534   </para>
6535
6536   <para>
6537    All the functions and operators described below that take <type>time</type> or <type>timestamp</type>
6538    inputs actually come in two variants: one that takes <type>time with time zone</type> or <type>timestamp
6539    with time zone</type>, and one that takes <type>time without time zone</type> or <type>timestamp without time zone</type>.
6540    For brevity, these variants are not shown separately.  Also, the
6541    <literal>+</> and <literal>*</> operators come in commutative pairs (for
6542    example both date + integer and integer + date); we show only one of each
6543    such pair.
6544   </para>
6545
6546     <table id="operators-datetime-table">
6547      <title>Date/Time Operators</title>
6548
6549      <tgroup cols="3">
6550       <thead>
6551        <row>
6552         <entry>Operator</entry>
6553         <entry>Example</entry>
6554         <entry>Result</entry>
6555        </row>
6556       </thead>
6557
6558       <tbody>
6559        <row>
6560         <entry> <literal>+</literal> </entry>
6561         <entry><literal>date '2001-09-28' + integer '7'</literal></entry>
6562         <entry><literal>date '2001-10-05'</literal></entry>
6563        </row>
6564
6565        <row>
6566         <entry> <literal>+</literal> </entry>
6567         <entry><literal>date '2001-09-28' + interval '1 hour'</literal></entry>
6568         <entry><literal>timestamp '2001-09-28 01:00:00'</literal></entry>
6569        </row>
6570
6571        <row>
6572         <entry> <literal>+</literal> </entry>
6573         <entry><literal>date '2001-09-28' + time '03:00'</literal></entry>
6574         <entry><literal>timestamp '2001-09-28 03:00:00'</literal></entry>
6575        </row>
6576
6577        <row>
6578         <entry> <literal>+</literal> </entry>
6579         <entry><literal>interval '1 day' + interval '1 hour'</literal></entry>
6580         <entry><literal>interval '1 day 01:00:00'</literal></entry>
6581        </row>
6582
6583        <row>
6584         <entry> <literal>+</literal> </entry>
6585         <entry><literal>timestamp '2001-09-28 01:00' + interval '23 hours'</literal></entry>
6586         <entry><literal>timestamp '2001-09-29 00:00:00'</literal></entry>
6587        </row>
6588
6589        <row>
6590         <entry> <literal>+</literal> </entry>
6591         <entry><literal>time '01:00' + interval '3 hours'</literal></entry>
6592         <entry><literal>time '04:00:00'</literal></entry>
6593        </row>
6594
6595        <row>
6596         <entry> <literal>-</literal> </entry>
6597         <entry><literal>- interval '23 hours'</literal></entry>
6598         <entry><literal>interval '-23:00:00'</literal></entry>
6599        </row>
6600
6601        <row>
6602         <entry> <literal>-</literal> </entry>
6603         <entry><literal>date '2001-10-01' - date '2001-09-28'</literal></entry>
6604         <entry><literal>integer '3'</literal> (days)</entry>
6605        </row>
6606
6607        <row>
6608         <entry> <literal>-</literal> </entry>
6609         <entry><literal>date '2001-10-01' - integer '7'</literal></entry>
6610         <entry><literal>date '2001-09-24'</literal></entry>
6611        </row>
6612
6613        <row>
6614         <entry> <literal>-</literal> </entry>
6615         <entry><literal>date '2001-09-28' - interval '1 hour'</literal></entry>
6616         <entry><literal>timestamp '2001-09-27 23:00:00'</literal></entry>
6617        </row>
6618
6619        <row>
6620         <entry> <literal>-</literal> </entry>
6621         <entry><literal>time '05:00' - time '03:00'</literal></entry>
6622         <entry><literal>interval '02:00:00'</literal></entry>
6623        </row>
6624
6625        <row>
6626         <entry> <literal>-</literal> </entry>
6627         <entry><literal>time '05:00' - interval '2 hours'</literal></entry>
6628         <entry><literal>time '03:00:00'</literal></entry>
6629        </row>
6630
6631        <row>
6632         <entry> <literal>-</literal> </entry>
6633         <entry><literal>timestamp '2001-09-28 23:00' - interval '23 hours'</literal></entry>
6634         <entry><literal>timestamp '2001-09-28 00:00:00'</literal></entry>
6635        </row>
6636
6637        <row>
6638         <entry> <literal>-</literal> </entry>
6639         <entry><literal>interval '1 day' - interval '1 hour'</literal></entry>
6640         <entry><literal>interval '1 day -01:00:00'</literal></entry>
6641        </row>
6642
6643        <row>
6644         <entry> <literal>-</literal> </entry>
6645         <entry><literal>timestamp '2001-09-29 03:00' - timestamp '2001-09-27 12:00'</literal></entry>
6646         <entry><literal>interval '1 day 15:00:00'</literal></entry>
6647        </row>
6648
6649        <row>
6650         <entry> <literal>*</literal> </entry>
6651         <entry><literal>900 * interval '1 second'</literal></entry>
6652         <entry><literal>interval '00:15:00'</literal></entry>
6653        </row>
6654
6655        <row>
6656         <entry> <literal>*</literal> </entry>
6657         <entry><literal>21 * interval '1 day'</literal></entry>
6658         <entry><literal>interval '21 days'</literal></entry>
6659        </row>
6660
6661        <row>
6662         <entry> <literal>*</literal> </entry>
6663         <entry><literal>double precision '3.5' * interval '1 hour'</literal></entry>
6664         <entry><literal>interval '03:30:00'</literal></entry>
6665        </row>
6666
6667        <row>
6668         <entry> <literal>/</literal> </entry>
6669         <entry><literal>interval '1 hour' / double precision '1.5'</literal></entry>
6670         <entry><literal>interval '00:40:00'</literal></entry>
6671        </row>
6672       </tbody>
6673      </tgroup>
6674     </table>
6675
6676     <table id="functions-datetime-table">
6677      <title>Date/Time Functions</title>
6678      <tgroup cols="5">
6679       <thead>
6680        <row>
6681         <entry>Function</entry>
6682         <entry>Return Type</entry>
6683         <entry>Description</entry>
6684         <entry>Example</entry>
6685         <entry>Result</entry>
6686        </row>
6687       </thead>
6688
6689       <tbody>
6690        <row>
6691         <entry>
6692          <indexterm>
6693           <primary>age</primary>
6694          </indexterm>
6695          <literal><function>age(<type>timestamp</type>, <type>timestamp</type>)</function></literal>
6696         </entry>
6697         <entry><type>interval</type></entry>
6698         <entry>Subtract arguments, producing a <quote>symbolic</> result that
6699         uses years and months, rather than just days</entry>
6700         <entry><literal>age(timestamp '2001-04-10', timestamp '1957-06-13')</literal></entry>
6701         <entry><literal>43 years 9 mons 27 days</literal></entry>
6702        </row>
6703
6704        <row>
6705         <entry><literal><function>age(<type>timestamp</type>)</function></literal></entry>
6706         <entry><type>interval</type></entry>
6707         <entry>Subtract from <function>current_date</function> (at midnight)</entry>
6708         <entry><literal>age(timestamp '1957-06-13')</literal></entry>
6709         <entry><literal>43 years 8 mons 3 days</literal></entry>
6710        </row>
6711
6712        <row>
6713         <entry>
6714          <indexterm>
6715           <primary>clock_timestamp</primary>
6716          </indexterm>
6717          <literal><function>clock_timestamp()</function></literal>
6718         </entry>
6719         <entry><type>timestamp with time zone</type></entry>
6720         <entry>Current date and time (changes during statement execution);
6721          see <xref linkend="functions-datetime-current">
6722         </entry>
6723         <entry></entry>
6724         <entry></entry>
6725        </row>
6726
6727        <row>
6728         <entry>
6729          <indexterm>
6730           <primary>current_date</primary>
6731          </indexterm>
6732          <literal><function>current_date</function></literal>
6733         </entry>
6734         <entry><type>date</type></entry>
6735         <entry>Current date;
6736          see <xref linkend="functions-datetime-current">
6737         </entry>
6738         <entry></entry>
6739         <entry></entry>
6740        </row>
6741
6742        <row>
6743         <entry>
6744          <indexterm>
6745           <primary>current_time</primary>
6746          </indexterm>
6747          <literal><function>current_time</function></literal>
6748         </entry>
6749         <entry><type>time with time zone</type></entry>
6750         <entry>Current time of day;
6751          see <xref linkend="functions-datetime-current">
6752         </entry>
6753         <entry></entry>
6754         <entry></entry>
6755        </row>
6756
6757        <row>
6758         <entry>
6759          <indexterm>
6760           <primary>current_timestamp</primary>
6761          </indexterm>
6762          <literal><function>current_timestamp</function></literal>
6763         </entry>
6764         <entry><type>timestamp with time zone</type></entry>
6765         <entry>Current date and time (start of current transaction);
6766          see <xref linkend="functions-datetime-current">
6767         </entry>
6768         <entry></entry>
6769         <entry></entry>
6770        </row>
6771
6772        <row>
6773         <entry>
6774          <indexterm>
6775           <primary>date_part</primary>
6776          </indexterm>
6777          <literal><function>date_part(<type>text</type>, <type>timestamp</type>)</function></literal>
6778         </entry>
6779         <entry><type>double precision</type></entry>
6780         <entry>Get subfield (equivalent to <function>extract</function>);
6781          see <xref linkend="functions-datetime-extract">
6782         </entry>
6783         <entry><literal>date_part('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
6784         <entry><literal>20</literal></entry>
6785        </row>
6786
6787        <row>
6788         <entry><literal><function>date_part(<type>text</type>, <type>interval</type>)</function></literal></entry>
6789         <entry><type>double precision</type></entry>
6790         <entry>Get subfield (equivalent to
6791          <function>extract</function>); see <xref linkend="functions-datetime-extract">
6792         </entry>
6793         <entry><literal>date_part('month', interval '2 years 3 months')</literal></entry>
6794         <entry><literal>3</literal></entry>
6795        </row>
6796
6797        <row>
6798         <entry>
6799          <indexterm>
6800           <primary>date_trunc</primary>
6801          </indexterm>
6802          <literal><function>date_trunc(<type>text</type>, <type>timestamp</type>)</function></literal>
6803         </entry>
6804         <entry><type>timestamp</type></entry>
6805         <entry>Truncate to specified precision; see also <xref linkend="functions-datetime-trunc">
6806         </entry>
6807         <entry><literal>date_trunc('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
6808         <entry><literal>2001-02-16 20:00:00</literal></entry>
6809        </row>
6810
6811        <row>
6812         <entry><literal><function>date_trunc(<type>text</type>, <type>interval</type>)</function></literal></entry>
6813         <entry><type>interval</type></entry>
6814         <entry>Truncate to specified precision; see also <xref linkend="functions-datetime-trunc">
6815         </entry>
6816         <entry><literal>date_trunc('hour', interval '2 days 3 hours 40 minutes')</literal></entry>
6817         <entry><literal>2 days 03:00:00</literal></entry>
6818        </row>
6819
6820        <row>
6821         <entry>
6822          <indexterm>
6823           <primary>extract</primary>
6824          </indexterm>
6825          <literal><function>extract</function>(<parameter>field</parameter> from
6826          <type>timestamp</type>)</literal>
6827         </entry>
6828         <entry><type>double precision</type></entry>
6829         <entry>Get subfield; see <xref linkend="functions-datetime-extract">
6830         </entry>
6831         <entry><literal>extract(hour from timestamp '2001-02-16 20:38:40')</literal></entry>
6832         <entry><literal>20</literal></entry>
6833        </row>
6834
6835        <row>
6836         <entry><literal><function>extract</function>(<parameter>field</parameter> from
6837          <type>interval</type>)</literal></entry>
6838         <entry><type>double precision</type></entry>
6839         <entry>Get subfield; see <xref linkend="functions-datetime-extract">
6840         </entry>
6841         <entry><literal>extract(month from interval '2 years 3 months')</literal></entry>
6842         <entry><literal>3</literal></entry>
6843        </row>
6844
6845        <row>
6846         <entry>
6847          <indexterm>
6848           <primary>isfinite</primary>
6849          </indexterm>
6850          <literal><function>isfinite(<type>date</type>)</function></literal>
6851         </entry>
6852         <entry><type>boolean</type></entry>
6853         <entry>Test for finite date (not +/-infinity)</entry>
6854         <entry><literal>isfinite(date '2001-02-16')</literal></entry>
6855         <entry><literal>true</literal></entry>
6856        </row>
6857
6858        <row>
6859         <entry><literal><function>isfinite(<type>timestamp</type>)</function></literal></entry>
6860         <entry><type>boolean</type></entry>
6861         <entry>Test for finite time stamp (not +/-infinity)</entry>
6862         <entry><literal>isfinite(timestamp '2001-02-16 21:28:30')</literal></entry>
6863         <entry><literal>true</literal></entry>
6864        </row>
6865
6866        <row>
6867         <entry><literal><function>isfinite(<type>interval</type>)</function></literal></entry>
6868         <entry><type>boolean</type></entry>
6869         <entry>Test for finite interval</entry>
6870         <entry><literal>isfinite(interval '4 hours')</literal></entry>
6871         <entry><literal>true</literal></entry>
6872        </row>
6873
6874        <row>
6875         <entry>
6876          <indexterm>
6877           <primary>justify_days</primary>
6878          </indexterm>
6879          <literal><function>justify_days(<type>interval</type>)</function></literal>
6880         </entry>
6881         <entry><type>interval</type></entry>
6882         <entry>Adjust interval so 30-day time periods are represented as months</entry>
6883         <entry><literal>justify_days(interval '35 days')</literal></entry>
6884         <entry><literal>1 mon 5 days</literal></entry>
6885        </row>
6886
6887        <row>
6888         <entry>
6889          <indexterm>
6890           <primary>justify_hours</primary>
6891          </indexterm>
6892          <literal><function>justify_hours(<type>interval</type>)</function></literal>
6893         </entry>
6894         <entry><type>interval</type></entry>
6895         <entry>Adjust interval so 24-hour time periods are represented as days</entry>
6896         <entry><literal>justify_hours(interval '27 hours')</literal></entry>
6897         <entry><literal>1 day 03:00:00</literal></entry>
6898        </row>
6899
6900        <row>
6901         <entry>
6902          <indexterm>
6903           <primary>justify_interval</primary>
6904          </indexterm>
6905          <literal><function>justify_interval(<type>interval</type>)</function></literal>
6906         </entry>
6907         <entry><type>interval</type></entry>
6908         <entry>Adjust interval using <function>justify_days</> and <function>justify_hours</>, with additional sign adjustments</entry>
6909         <entry><literal>justify_interval(interval '1 mon -1 hour')</literal></entry>
6910         <entry><literal>29 days 23:00:00</literal></entry>
6911        </row>
6912
6913        <row>
6914         <entry>
6915          <indexterm>
6916           <primary>localtime</primary>
6917          </indexterm>
6918          <literal><function>localtime</function></literal>
6919         </entry>
6920         <entry><type>time</type></entry>
6921         <entry>Current time of day;
6922          see <xref linkend="functions-datetime-current">
6923         </entry>
6924         <entry></entry>
6925         <entry></entry>
6926        </row>
6927
6928        <row>
6929         <entry>
6930          <indexterm>
6931           <primary>localtimestamp</primary>
6932          </indexterm>
6933          <literal><function>localtimestamp</function></literal>
6934         </entry>
6935         <entry><type>timestamp</type></entry>
6936         <entry>Current date and time (start of current transaction);
6937          see <xref linkend="functions-datetime-current">
6938         </entry>
6939         <entry></entry>
6940         <entry></entry>
6941        </row>
6942
6943        <row>
6944         <entry>
6945          <indexterm>
6946           <primary>make_date</primary>
6947          </indexterm>
6948          <literal>
6949             <function>
6950              make_date(<parameter>year</parameter> <type>int</type>,
6951              <parameter>month</parameter> <type>int</type>,
6952              <parameter>day</parameter> <type>int</type>)
6953             </function>
6954          </literal>
6955         </entry>
6956         <entry><type>date</type></entry>
6957         <entry>
6958          Create date from year, month and day fields
6959         </entry>
6960         <entry><literal>make_date(2013, 7, 15)</literal></entry>
6961         <entry><literal>2013-07-15</literal></entry>
6962        </row>
6963
6964        <row>
6965         <entry>
6966          <indexterm>
6967           <primary>make_interval</primary>
6968          </indexterm>
6969          <literal>
6970           <function>
6971            make_interval(<parameter>years</parameter> <type>int</type> DEFAULT 0,
6972            <parameter>months</parameter> <type>int</type> DEFAULT 0,
6973            <parameter>weeks</parameter> <type>int</type> DEFAULT 0,
6974            <parameter>days</parameter> <type>int</type> DEFAULT 0,
6975            <parameter>hours</parameter> <type>int</type> DEFAULT 0,
6976            <parameter>mins</parameter> <type>int</type> DEFAULT 0,
6977            <parameter>secs</parameter> <type>double precision</type> DEFAULT 0.0)
6978           </function>
6979          </literal>
6980         </entry>
6981         <entry><type>interval</type></entry>
6982         <entry>
6983          Create interval from years, months, weeks, days, hours, minutes and
6984          seconds fields
6985         </entry>
6986         <entry><literal>make_interval(days =&gt; 10)</literal></entry>
6987         <entry><literal>10 days</literal></entry>
6988        </row>
6989
6990        <row>
6991         <entry>
6992          <indexterm>
6993           <primary>make_time</primary>
6994          </indexterm>
6995          <literal>
6996           <function>
6997            make_time(<parameter>hour</parameter> <type>int</type>,
6998            <parameter>min</parameter> <type>int</type>,
6999            <parameter>sec</parameter> <type>double precision</type>)
7000           </function>
7001          </literal>
7002         </entry>
7003         <entry><type>time</type></entry>
7004         <entry>
7005          Create time from hour, minute and seconds fields
7006         </entry>
7007         <entry><literal>make_time(8, 15, 23.5)</literal></entry>
7008         <entry><literal>08:15:23.5</literal></entry>
7009        </row>
7010
7011        <row>
7012         <entry>
7013          <indexterm>
7014           <primary>make_timestamp</primary>
7015          </indexterm>
7016          <literal>
7017           <function>
7018            make_timestamp(<parameter>year</parameter> <type>int</type>,
7019            <parameter>month</parameter> <type>int</type>,
7020            <parameter>day</parameter> <type>int</type>,
7021            <parameter>hour</parameter> <type>int</type>,
7022            <parameter>min</parameter> <type>int</type>,
7023            <parameter>sec</parameter> <type>double precision</type>)
7024           </function>
7025          </literal>
7026         </entry>
7027         <entry><type>timestamp</type></entry>
7028         <entry>
7029          Create timestamp from year, month, day, hour, minute and seconds fields
7030         </entry>
7031         <entry><literal>make_timestamp(2013, 7, 15, 8, 15, 23.5)</literal></entry>
7032         <entry><literal>2013-07-15 08:15:23.5</literal></entry>
7033        </row>
7034
7035        <row>
7036         <entry>
7037          <indexterm>
7038           <primary>make_timestamptz</primary>
7039          </indexterm>
7040          <literal>
7041           <function>
7042            make_timestamptz(<parameter>year</parameter> <type>int</type>,
7043            <parameter>month</parameter> <type>int</type>,
7044            <parameter>day</parameter> <type>int</type>,
7045            <parameter>hour</parameter> <type>int</type>,
7046            <parameter>min</parameter> <type>int</type>,
7047            <parameter>sec</parameter> <type>double precision</type>,
7048            <optional> <parameter>timezone</parameter> <type>text</type> </optional>)
7049           </function>
7050          </literal>
7051         </entry>
7052         <entry><type>timestamp with time zone</type></entry>
7053         <entry>
7054          Create timestamp with time zone from year, month, day, hour, minute
7055          and seconds fields; if <parameter>timezone</parameter> is not
7056          specified, the current time zone is used
7057         </entry>
7058         <entry><literal>make_timestamptz(2013, 7, 15, 8, 15, 23.5)</literal></entry>
7059         <entry><literal>2013-07-15 08:15:23.5+01</literal></entry>
7060        </row>
7061
7062        <row>
7063         <entry>
7064          <indexterm>
7065           <primary>now</primary>
7066          </indexterm>
7067          <literal><function>now()</function></literal>
7068         </entry>
7069         <entry><type>timestamp with time zone</type></entry>
7070         <entry>Current date and time (start of current transaction);
7071          see <xref linkend="functions-datetime-current">
7072         </entry>
7073         <entry></entry>
7074         <entry></entry>
7075        </row>
7076
7077        <row>
7078         <entry>
7079          <indexterm>
7080           <primary>statement_timestamp</primary>
7081          </indexterm>
7082          <literal><function>statement_timestamp()</function></literal>
7083         </entry>
7084         <entry><type>timestamp with time zone</type></entry>
7085         <entry>Current date and time (start of current statement);
7086          see <xref linkend="functions-datetime-current">
7087         </entry>
7088         <entry></entry>
7089         <entry></entry>
7090        </row>
7091
7092        <row>
7093         <entry>
7094          <indexterm>
7095           <primary>timeofday</primary>
7096          </indexterm>
7097          <literal><function>timeofday()</function></literal>
7098         </entry>
7099         <entry><type>text</type></entry>
7100         <entry>Current date and time
7101          (like <function>clock_timestamp</>, but as a <type>text</> string);
7102          see <xref linkend="functions-datetime-current">
7103         </entry>
7104         <entry></entry>
7105         <entry></entry>
7106        </row>
7107
7108        <row>
7109         <entry>
7110          <indexterm>
7111           <primary>transaction_timestamp</primary>
7112          </indexterm>
7113          <literal><function>transaction_timestamp()</function></literal>
7114         </entry>
7115         <entry><type>timestamp with time zone</type></entry>
7116         <entry>Current date and time (start of current transaction);
7117          see <xref linkend="functions-datetime-current">
7118         </entry>
7119         <entry></entry>
7120         <entry></entry>
7121        </row>
7122        <row>
7123         <entry>
7124          <indexterm>
7125           <primary>to_timestamp</primary>
7126          </indexterm>
7127          <literal><function>to_timestamp(<type>double precision</type>)</function></literal>
7128         </entry>
7129         <entry><type>timestamp with time zone</type></entry>
7130         <entry>Convert Unix epoch (seconds since 1970-01-01 00:00:00+00) to
7131          timestamp</entry>
7132         <entry><literal>to_timestamp(1284352323)</literal></entry>
7133         <entry><literal>2010-09-13 04:32:03+00</literal></entry>
7134        </row>
7135       </tbody>
7136      </tgroup>
7137     </table>
7138
7139    <para>
7140     <indexterm>
7141       <primary>OVERLAPS</primary>
7142     </indexterm>
7143     In addition to these functions, the SQL <literal>OVERLAPS</> operator is
7144     supported:
7145 <synopsis>
7146 (<replaceable>start1</replaceable>, <replaceable>end1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>end2</replaceable>)
7147 (<replaceable>start1</replaceable>, <replaceable>length1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>length2</replaceable>)
7148 </synopsis>
7149     This expression yields true when two time periods (defined by their
7150     endpoints) overlap, false when they do not overlap.  The endpoints
7151     can be specified as pairs of dates, times, or time stamps; or as
7152     a date, time, or time stamp followed by an interval.  When a pair
7153     of values is provided, either the start or the end can be written
7154     first; <literal>OVERLAPS</> automatically takes the earlier value
7155     of the pair as the start.  Each time period is considered to
7156     represent the half-open interval <replaceable>start</> <literal>&lt;=</>
7157     <replaceable>time</> <literal>&lt;</> <replaceable>end</>, unless
7158     <replaceable>start</> and <replaceable>end</> are equal in which case it
7159     represents that single time instant.  This means for instance that two
7160     time periods with only an endpoint in common do not overlap.
7161    </para>
7162
7163 <screen>
7164 SELECT (DATE '2001-02-16', DATE '2001-12-21') OVERLAPS
7165        (DATE '2001-10-30', DATE '2002-10-30');
7166 <lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
7167 SELECT (DATE '2001-02-16', INTERVAL '100 days') OVERLAPS
7168        (DATE '2001-10-30', DATE '2002-10-30');
7169 <lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
7170 SELECT (DATE '2001-10-29', DATE '2001-10-30') OVERLAPS
7171        (DATE '2001-10-30', DATE '2001-10-31');
7172 <lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
7173 SELECT (DATE '2001-10-30', DATE '2001-10-30') OVERLAPS
7174        (DATE '2001-10-30', DATE '2001-10-31');
7175 <lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
7176 </screen>
7177
7178   <para>
7179    When adding an <type>interval</type> value to (or subtracting an
7180    <type>interval</type> value from) a <type>timestamp with time zone</type>
7181    value, the days component advances or decrements the date of the
7182    <type>timestamp with time zone</type> by the indicated number of days.
7183    Across daylight saving time changes (when the session time zone is set to a
7184    time zone that recognizes DST), this means <literal>interval '1 day'</literal>
7185    does not necessarily equal <literal>interval '24 hours'</literal>.
7186    For example, with the session time zone set to <literal>CST7CDT</literal>,
7187    <literal>timestamp with time zone '2005-04-02 12:00-07' + interval '1 day'</literal>
7188    will produce <literal>timestamp with time zone '2005-04-03 12:00-06'</literal>,
7189    while adding <literal>interval '24 hours'</literal> to the same initial
7190    <type>timestamp with time zone</type> produces
7191    <literal>timestamp with time zone '2005-04-03 13:00-06'</literal>, as there is
7192    a change in daylight saving time at <literal>2005-04-03 02:00</literal> in time zone
7193    <literal>CST7CDT</literal>.
7194   </para>
7195
7196   <para>
7197    Note there can be ambiguity in the <literal>months</> field returned by
7198    <function>age</> because different months have different numbers of
7199    days.  <productname>PostgreSQL</>'s approach uses the month from the
7200    earlier of the two dates when calculating partial months.  For example,
7201    <literal>age('2004-06-01', '2004-04-30')</> uses April to yield
7202    <literal>1 mon 1 day</>, while using May would yield <literal>1 mon 2
7203    days</> because May has 31 days, while April has only 30.
7204   </para>
7205
7206   <para>
7207    Subtraction of dates and timestamps can also be complex.  One conceptually
7208    simple way to perform subtraction is to convert each value to a number
7209    of seconds using <literal>EXTRACT(EPOCH FROM ...)</>, then subtract the
7210    results; this produces the
7211    number of <emphasis>seconds</> between the two values.  This will adjust
7212    for the number of days in each month, timezone changes, and daylight
7213    saving time adjustments.  Subtraction of date or timestamp
7214    values with the <quote><literal>-</></quote> operator
7215    returns the number of days (24-hours) and hours/minutes/seconds
7216    between the values, making the same adjustments.  The <function>age</>
7217    function returns years, months, days, and hours/minutes/seconds,
7218    performing field-by-field subtraction and then adjusting for negative
7219    field values.  The following queries illustrate the differences in these
7220    approaches.  The sample results were produced with <literal>timezone
7221    = 'US/Eastern'</>; there is a daylight saving time change between the
7222    two dates used:
7223   </para>
7224
7225 <screen>
7226 SELECT EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
7227        EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00');
7228 <lineannotation>Result: </lineannotation><computeroutput>10537200</computeroutput>
7229 SELECT (EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
7230         EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00'))
7231         / 60 / 60 / 24;
7232 <lineannotation>Result: </lineannotation><computeroutput>121.958333333333</computeroutput>
7233 SELECT timestamptz '2013-07-01 12:00:00' - timestamptz '2013-03-01 12:00:00';
7234 <lineannotation>Result: </lineannotation><computeroutput>121 days 23:00:00</computeroutput>
7235 SELECT age(timestamptz '2013-07-01 12:00:00', timestamptz '2013-03-01 12:00:00');
7236 <lineannotation>Result: </lineannotation><computeroutput>4 mons</computeroutput>
7237 </screen>
7238
7239   <sect2 id="functions-datetime-extract">
7240    <title><function>EXTRACT</function>, <function>date_part</function></title>
7241
7242    <indexterm>
7243     <primary>date_part</primary>
7244    </indexterm>
7245    <indexterm>
7246     <primary>extract</primary>
7247    </indexterm>
7248
7249 <synopsis>
7250 EXTRACT(<replaceable>field</replaceable> FROM <replaceable>source</replaceable>)
7251 </synopsis>
7252
7253    <para>
7254     The <function>extract</function> function retrieves subfields
7255     such as year or hour from date/time values.
7256     <replaceable>source</replaceable> must be a value expression of
7257     type <type>timestamp</type>, <type>time</type>, or <type>interval</type>.
7258     (Expressions of type <type>date</type> are
7259     cast to <type>timestamp</type> and can therefore be used as
7260     well.)  <replaceable>field</replaceable> is an identifier or
7261     string that selects what field to extract from the source value.
7262     The <function>extract</function> function returns values of type
7263     <type>double precision</type>.
7264     The following are valid field names:
7265
7266     <!-- alphabetical -->
7267     <variablelist>
7268      <varlistentry>
7269       <term><literal>century</literal></term>
7270       <listitem>
7271        <para>
7272         The century
7273        </para>
7274
7275 <screen>
7276 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');
7277 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
7278 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
7279 <lineannotation>Result: </lineannotation><computeroutput>21</computeroutput>
7280 </screen>
7281
7282        <para>
7283         The first century starts at 0001-01-01 00:00:00 AD, although
7284         they did not know it at the time. This definition applies to all
7285         Gregorian calendar countries. There is no century number 0,
7286         you go from -1 century to 1 century.
7287
7288         If you disagree with this, please write your complaint to:
7289         Pope, Cathedral Saint-Peter of Roma, Vatican.
7290        </para>
7291       </listitem>
7292      </varlistentry>
7293
7294      <varlistentry>
7295       <term><literal>day</literal></term>
7296       <listitem>
7297        <para>
7298         For <type>timestamp</type> values, the day (of the month) field
7299         (1 - 31) ; for <type>interval</type> values, the number of days
7300        </para>
7301
7302 <screen>
7303 SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
7304 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
7305
7306 SELECT EXTRACT(DAY FROM INTERVAL '40 days 1 minute');
7307 <lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
7308 </screen>
7309
7310
7311
7312       </listitem>
7313      </varlistentry>
7314
7315      <varlistentry>
7316       <term><literal>decade</literal></term>
7317       <listitem>
7318        <para>
7319         The year field divided by 10
7320        </para>
7321
7322 <screen>
7323 SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
7324 <lineannotation>Result: </lineannotation><computeroutput>200</computeroutput>
7325 </screen>
7326       </listitem>
7327      </varlistentry>
7328
7329      <varlistentry>
7330       <term><literal>dow</literal></term>
7331       <listitem>
7332        <para>
7333         The day of the week as Sunday (<literal>0</>) to
7334         Saturday (<literal>6</>)
7335        </para>
7336
7337 <screen>
7338 SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
7339 <lineannotation>Result: </lineannotation><computeroutput>5</computeroutput>
7340 </screen>
7341        <para>
7342         Note that <function>extract</function>'s day of the week numbering
7343         differs from that of the <function>to_char(...,
7344         'D')</function> function.
7345        </para>
7346
7347       </listitem>
7348      </varlistentry>
7349
7350      <varlistentry>
7351       <term><literal>doy</literal></term>
7352       <listitem>
7353        <para>
7354         The day of the year (1 - 365/366)
7355        </para>
7356
7357 <screen>
7358 SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
7359 <lineannotation>Result: </lineannotation><computeroutput>47</computeroutput>
7360 </screen>
7361       </listitem>
7362      </varlistentry>
7363
7364      <varlistentry>
7365       <term><literal>epoch</literal></term>
7366       <listitem>
7367        <para>
7368         For <type>timestamp with time zone</type> values, the
7369         number of seconds since 1970-01-01 00:00:00 UTC (can be negative);
7370         for <type>date</type> and <type>timestamp</type> values, the
7371         number of seconds since 1970-01-01 00:00:00 local time;
7372         for <type>interval</type> values, the total number
7373         of seconds in the interval
7374        </para>
7375
7376 <screen>
7377 SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');
7378 <lineannotation>Result: </lineannotation><computeroutput>982384720.12</computeroutput>
7379
7380 SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
7381 <lineannotation>Result: </lineannotation><computeroutput>442800</computeroutput>
7382 </screen>
7383
7384        <para>
7385         You can convert an epoch value back to a time stamp
7386         with <function>to_timestamp</>:
7387        </para>
7388 <screen>
7389 SELECT to_timestamp(982384720.12);
7390 <lineannotation>Result: </lineannotation><computeroutput>2001-02-17 04:38:40.12+00</computeroutput>
7391 </screen>
7392       </listitem>
7393      </varlistentry>
7394
7395      <varlistentry>
7396       <term><literal>hour</literal></term>
7397       <listitem>
7398        <para>
7399         The hour field (0 - 23)
7400        </para>
7401
7402 <screen>
7403 SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
7404 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
7405 </screen>
7406       </listitem>
7407      </varlistentry>
7408
7409      <varlistentry>
7410       <term><literal>isodow</literal></term>
7411       <listitem>
7412        <para>
7413         The day of the week as Monday (<literal>1</>) to
7414         Sunday (<literal>7</>)
7415        </para>
7416
7417 <screen>
7418 SELECT EXTRACT(ISODOW FROM TIMESTAMP '2001-02-18 20:38:40');
7419 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
7420 </screen>
7421        <para>
7422         This is identical to <literal>dow</> except for Sunday.  This
7423         matches the <acronym>ISO</> 8601 day of the week numbering.
7424        </para>
7425
7426       </listitem>
7427      </varlistentry>
7428
7429      <varlistentry>
7430       <term><literal>isoyear</literal></term>
7431       <listitem>
7432        <para>
7433         The <acronym>ISO</acronym> 8601 week-numbering year that the date
7434         falls in (not applicable to intervals)
7435        </para>
7436
7437 <screen>
7438 SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-01');
7439 <lineannotation>Result: </lineannotation><computeroutput>2005</computeroutput>
7440 SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-02');
7441 <lineannotation>Result: </lineannotation><computeroutput>2006</computeroutput>
7442 </screen>
7443
7444        <para>
7445         Each <acronym>ISO</acronym> 8601 week-numbering year begins with the
7446         Monday of the week containing the 4th of January, so in early
7447         January or late December the <acronym>ISO</acronym> year may be
7448         different from the Gregorian year.  See the <literal>week</literal>
7449         field for more information.
7450        </para>
7451        <para>
7452         This field is not available in PostgreSQL releases prior to 8.3.
7453        </para>
7454       </listitem>
7455      </varlistentry>
7456
7457      <varlistentry>
7458       <term><literal>microseconds</literal></term>
7459       <listitem>
7460        <para>
7461         The seconds field, including fractional parts, multiplied by 1
7462         000 000;  note that this includes full seconds
7463        </para>
7464
7465 <screen>
7466 SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
7467 <lineannotation>Result: </lineannotation><computeroutput>28500000</computeroutput>
7468 </screen>
7469       </listitem>
7470      </varlistentry>
7471
7472      <varlistentry>
7473       <term><literal>millennium</literal></term>
7474       <listitem>
7475        <para>
7476         The millennium
7477        </para>
7478
7479 <screen>
7480 SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
7481 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
7482 </screen>
7483
7484        <para>
7485         Years in the 1900s are in the second millennium.
7486         The third millennium started January 1, 2001.
7487        </para>
7488       </listitem>
7489      </varlistentry>
7490
7491      <varlistentry>
7492       <term><literal>milliseconds</literal></term>
7493       <listitem>
7494        <para>
7495         The seconds field, including fractional parts, multiplied by
7496         1000.  Note that this includes full seconds.
7497        </para>
7498
7499 <screen>
7500 SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
7501 <lineannotation>Result: </lineannotation><computeroutput>28500</computeroutput>
7502 </screen>
7503       </listitem>
7504      </varlistentry>
7505
7506      <varlistentry>
7507       <term><literal>minute</literal></term>
7508       <listitem>
7509        <para>
7510         The minutes field (0 - 59)
7511        </para>
7512
7513 <screen>
7514 SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
7515 <lineannotation>Result: </lineannotation><computeroutput>38</computeroutput>
7516 </screen>
7517       </listitem>
7518      </varlistentry>
7519
7520      <varlistentry>
7521       <term><literal>month</literal></term>
7522       <listitem>
7523        <para>
7524         For <type>timestamp</type> values, the number of the month
7525         within the year (1 - 12) ; for <type>interval</type> values,
7526         the number of months, modulo 12 (0 - 11)
7527        </para>
7528
7529 <screen>
7530 SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
7531 <lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
7532
7533 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
7534 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
7535
7536 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
7537 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
7538 </screen>
7539       </listitem>
7540      </varlistentry>
7541
7542      <varlistentry>
7543       <term><literal>quarter</literal></term>
7544       <listitem>
7545        <para>
7546         The quarter of the year (1 - 4) that the date is in
7547        </para>
7548
7549 <screen>
7550 SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
7551 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
7552 </screen>
7553       </listitem>
7554      </varlistentry>
7555
7556      <varlistentry>
7557       <term><literal>second</literal></term>
7558       <listitem>
7559        <para>
7560         The seconds field, including fractional parts (0 -
7561         59<footnote><simpara>60 if leap seconds are
7562         implemented by the operating system</simpara></footnote>)
7563        </para>
7564
7565 <screen>
7566 SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
7567 <lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
7568
7569 SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
7570 <lineannotation>Result: </lineannotation><computeroutput>28.5</computeroutput>
7571 </screen>
7572       </listitem>
7573      </varlistentry>
7574      <varlistentry>
7575       <term><literal>timezone</literal></term>
7576       <listitem>
7577        <para>
7578         The time zone offset from UTC, measured in seconds.  Positive values
7579         correspond to time zones east of UTC, negative values to
7580         zones west of UTC.  (Technically,
7581         <productname>PostgreSQL</productname> uses <acronym>UT1</> because
7582         leap seconds are not handled.)
7583        </para>
7584       </listitem>
7585      </varlistentry>
7586
7587      <varlistentry>
7588       <term><literal>timezone_hour</literal></term>
7589       <listitem>
7590        <para>
7591         The hour component of the time zone offset
7592        </para>
7593       </listitem>
7594      </varlistentry>
7595
7596      <varlistentry>
7597       <term><literal>timezone_minute</literal></term>
7598       <listitem>
7599        <para>
7600         The minute component of the time zone offset
7601        </para>
7602       </listitem>
7603      </varlistentry>
7604
7605      <varlistentry>
7606       <term><literal>week</literal></term>
7607       <listitem>
7608        <para>
7609         The number of the <acronym>ISO</acronym> 8601 week-numbering week of
7610         the year.  By definition, ISO weeks start on Mondays and the first
7611         week of a year contains January 4 of that year.  In other words, the
7612         first Thursday of a year is in week 1 of that year.
7613        </para>
7614        <para>
7615         In the ISO week-numbering system, it is possible for early-January
7616         dates to be part of the 52nd or 53rd week of the previous year, and for
7617         late-December dates to be part of the first week of the next year.
7618         For example, <literal>2005-01-01</> is part of the 53rd week of year
7619         2004, and <literal>2006-01-01</> is part of the 52nd week of year
7620         2005, while <literal>2012-12-31</> is part of the first week of 2013.
7621         It's recommended to use the <literal>isoyear</> field together with
7622         <literal>week</> to get consistent results.
7623        </para>
7624
7625 <screen>
7626 SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
7627 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
7628 </screen>
7629       </listitem>
7630      </varlistentry>
7631
7632      <varlistentry>
7633       <term><literal>year</literal></term>
7634       <listitem>
7635        <para>
7636         The year field.  Keep in mind there is no <literal>0 AD</>, so subtracting
7637         <literal>BC</> years from <literal>AD</> years should be done with care.
7638        </para>
7639
7640 <screen>
7641 SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
7642 <lineannotation>Result: </lineannotation><computeroutput>2001</computeroutput>
7643 </screen>
7644       </listitem>
7645      </varlistentry>
7646
7647     </variablelist>
7648    </para>
7649
7650    <note>
7651     <para>
7652      When the input value is +/-Infinity, <function>extract</> returns
7653      +/-Infinity for monotonically-increasing fields (<literal>epoch</>,
7654      <literal>julian</>, <literal>year</>, <literal>isoyear</>,
7655      <literal>decade</>, <literal>century</>, and <literal>millennium</>).
7656      For other fields, NULL is returned.  <productname>PostgreSQL</>
7657      versions before 9.6 returned zero for all cases of infinite input.
7658     </para>
7659    </note>
7660
7661    <para>
7662     The <function>extract</function> function is primarily intended
7663     for computational processing.  For formatting date/time values for
7664     display, see <xref linkend="functions-formatting">.
7665    </para>
7666
7667    <para>
7668     The <function>date_part</function> function is modeled on the traditional
7669     <productname>Ingres</productname> equivalent to the
7670     <acronym>SQL</acronym>-standard function <function>extract</function>:
7671 <synopsis>
7672 date_part('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
7673 </synopsis>
7674     Note that here the <replaceable>field</replaceable> parameter needs to
7675     be a string value, not a name.  The valid field names for
7676     <function>date_part</function> are the same as for
7677     <function>extract</function>.
7678    </para>
7679
7680 <screen>
7681 SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
7682 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
7683
7684 SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
7685 <lineannotation>Result: </lineannotation><computeroutput>4</computeroutput>
7686 </screen>
7687
7688   </sect2>
7689
7690   <sect2 id="functions-datetime-trunc">
7691    <title><function>date_trunc</function></title>
7692
7693    <indexterm>
7694     <primary>date_trunc</primary>
7695    </indexterm>
7696
7697    <para>
7698     The function <function>date_trunc</function> is conceptually
7699     similar to the <function>trunc</function> function for numbers.
7700    </para>
7701
7702    <para>
7703 <synopsis>
7704 date_trunc('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
7705 </synopsis>
7706     <replaceable>source</replaceable> is a value expression of type
7707     <type>timestamp</type> or <type>interval</>.
7708     (Values of type <type>date</type> and
7709     <type>time</type> are cast automatically to <type>timestamp</type> or
7710     <type>interval</>, respectively.)
7711     <replaceable>field</replaceable> selects to which precision to
7712     truncate the input value.  The return value is of type
7713     <type>timestamp</type> or <type>interval</>
7714     with all fields that are less significant than the
7715     selected one set to zero (or one, for day and month).
7716    </para>
7717
7718    <para>
7719     Valid values for <replaceable>field</replaceable> are:
7720     <simplelist>
7721      <member><literal>microseconds</literal></member>
7722      <member><literal>milliseconds</literal></member>
7723      <member><literal>second</literal></member>
7724      <member><literal>minute</literal></member>
7725      <member><literal>hour</literal></member>
7726      <member><literal>day</literal></member>
7727      <member><literal>week</literal></member>
7728      <member><literal>month</literal></member>
7729      <member><literal>quarter</literal></member>
7730      <member><literal>year</literal></member>
7731      <member><literal>decade</literal></member>
7732      <member><literal>century</literal></member>
7733      <member><literal>millennium</literal></member>
7734     </simplelist>
7735    </para>
7736
7737    <para>
7738     Examples:
7739 <screen>
7740 SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
7741 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 20:00:00</computeroutput>
7742
7743 SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
7744 <lineannotation>Result: </lineannotation><computeroutput>2001-01-01 00:00:00</computeroutput>
7745 </screen>
7746    </para>
7747   </sect2>
7748
7749   <sect2 id="functions-datetime-zoneconvert">
7750    <title><literal>AT TIME ZONE</literal></title>
7751
7752    <indexterm>
7753     <primary>time zone</primary>
7754     <secondary>conversion</secondary>
7755    </indexterm>
7756
7757    <indexterm>
7758     <primary>AT TIME ZONE</primary>
7759    </indexterm>
7760
7761    <para>
7762     The <literal>AT TIME ZONE</literal> construct allows conversions
7763     of time stamps to different time zones.  <xref
7764     linkend="functions-datetime-zoneconvert-table"> shows its
7765     variants.
7766    </para>
7767
7768     <table id="functions-datetime-zoneconvert-table">
7769      <title><literal>AT TIME ZONE</literal> Variants</title>
7770      <tgroup cols="3">
7771       <thead>
7772        <row>
7773         <entry>Expression</entry>
7774         <entry>Return Type</entry>
7775         <entry>Description</entry>
7776        </row>
7777       </thead>
7778
7779       <tbody>
7780        <row>
7781         <entry>
7782          <literal><type>timestamp without time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7783         </entry>
7784         <entry><type>timestamp with time zone</type></entry>
7785         <entry>Treat given time stamp <emphasis>without time zone</> as located in the specified time zone</entry>
7786        </row>
7787
7788        <row>
7789         <entry>
7790          <literal><type>timestamp with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7791         </entry>
7792         <entry><type>timestamp without time zone</type></entry>
7793         <entry>Convert given time stamp <emphasis>with time zone</> to the new time
7794         zone, with no time zone designation</entry>
7795        </row>
7796
7797        <row>
7798         <entry>
7799          <literal><type>time with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7800         </entry>
7801         <entry><type>time with time zone</type></entry>
7802         <entry>Convert given time <emphasis>with time zone</> to the new time zone</entry>
7803        </row>
7804       </tbody>
7805      </tgroup>
7806     </table>
7807
7808    <para>
7809     In these expressions, the desired time zone <replaceable>zone</> can be
7810     specified either as a text string (e.g., <literal>'PST'</literal>)
7811     or as an interval (e.g., <literal>INTERVAL '-08:00'</literal>).
7812     In the text case, a time zone name can be specified in any of the ways
7813     described in <xref linkend="datatype-timezones">.
7814    </para>
7815
7816    <para>
7817     Examples (assuming the local time zone is <literal>PST8PDT</>):
7818 <screen>
7819 SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'MST';
7820 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 19:38:40-08</computeroutput>
7821
7822 SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'MST';
7823 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 18:38:40</computeroutput>
7824 </screen>
7825     The first example takes a time stamp without time zone and interprets it as MST time
7826     (UTC-7), which is then converted to PST (UTC-8) for display.  The second example takes
7827     a time stamp specified in EST (UTC-5) and converts it to local time in MST (UTC-7).
7828    </para>
7829
7830    <para>
7831     The function <literal><function>timezone</function>(<replaceable>zone</>,
7832     <replaceable>timestamp</>)</literal> is equivalent to the SQL-conforming construct
7833     <literal><replaceable>timestamp</> AT TIME ZONE
7834     <replaceable>zone</></literal>.
7835    </para>
7836   </sect2>
7837
7838   <sect2 id="functions-datetime-current">
7839    <title>Current Date/Time</title>
7840
7841    <indexterm>
7842     <primary>date</primary>
7843     <secondary>current</secondary>
7844    </indexterm>
7845
7846    <indexterm>
7847     <primary>time</primary>
7848     <secondary>current</secondary>
7849    </indexterm>
7850
7851    <para>
7852     <productname>PostgreSQL</productname> provides a number of functions
7853     that return values related to the current date and time.  These
7854     SQL-standard functions all return values based on the start time of
7855     the current transaction:
7856 <synopsis>
7857 CURRENT_DATE
7858 CURRENT_TIME
7859 CURRENT_TIMESTAMP
7860 CURRENT_TIME(<replaceable>precision</replaceable>)
7861 CURRENT_TIMESTAMP(<replaceable>precision</replaceable>)
7862 LOCALTIME
7863 LOCALTIMESTAMP
7864 LOCALTIME(<replaceable>precision</replaceable>)
7865 LOCALTIMESTAMP(<replaceable>precision</replaceable>)
7866 </synopsis>
7867     </para>
7868
7869     <para>
7870      <function>CURRENT_TIME</function> and
7871      <function>CURRENT_TIMESTAMP</function> deliver values with time zone;
7872      <function>LOCALTIME</function> and
7873      <function>LOCALTIMESTAMP</function> deliver values without time zone.
7874     </para>
7875
7876     <para>
7877      <function>CURRENT_TIME</function>,
7878      <function>CURRENT_TIMESTAMP</function>,
7879      <function>LOCALTIME</function>, and
7880      <function>LOCALTIMESTAMP</function>
7881      can optionally take
7882      a precision parameter, which causes the result to be rounded
7883      to that many fractional digits in the seconds field.  Without a precision parameter,
7884      the result is given to the full available precision.
7885     </para>
7886
7887    <para>
7888     Some examples:
7889 <screen>
7890 SELECT CURRENT_TIME;
7891 <lineannotation>Result: </lineannotation><computeroutput>14:39:53.662522-05</computeroutput>
7892
7893 SELECT CURRENT_DATE;
7894 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23</computeroutput>
7895
7896 SELECT CURRENT_TIMESTAMP;
7897 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522-05</computeroutput>
7898
7899 SELECT CURRENT_TIMESTAMP(2);
7900 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.66-05</computeroutput>
7901
7902 SELECT LOCALTIMESTAMP;
7903 <lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522</computeroutput>
7904 </screen>
7905    </para>
7906
7907    <para>
7908     Since these functions return
7909     the start time of the current transaction, their values do not
7910     change during the transaction. This is considered a feature:
7911     the intent is to allow a single transaction to have a consistent
7912     notion of the <quote>current</quote> time, so that multiple
7913     modifications within the same transaction bear the same
7914     time stamp.
7915    </para>
7916
7917    <note>
7918     <para>
7919      Other database systems might advance these values more
7920      frequently.
7921     </para>
7922    </note>
7923
7924    <para>
7925     <productname>PostgreSQL</productname> also provides functions that
7926     return the start time of the current statement, as well as the actual
7927     current time at the instant the function is called.  The complete list
7928     of non-SQL-standard time functions is:
7929 <synopsis>
7930 transaction_timestamp()
7931 statement_timestamp()
7932 clock_timestamp()
7933 timeofday()
7934 now()
7935 </synopsis>
7936    </para>
7937
7938    <para>
7939     <function>transaction_timestamp()</> is equivalent to
7940     <function>CURRENT_TIMESTAMP</function>, but is named to clearly reflect
7941     what it returns.
7942     <function>statement_timestamp()</> returns the start time of the current
7943     statement (more specifically, the time of receipt of the latest command
7944     message from the client).
7945     <function>statement_timestamp()</> and <function>transaction_timestamp()</>
7946     return the same value during the first command of a transaction, but might
7947     differ during subsequent commands.
7948     <function>clock_timestamp()</> returns the actual current time, and
7949     therefore its value changes even within a single SQL command.
7950     <function>timeofday()</> is a historical
7951     <productname>PostgreSQL</productname> function.  Like
7952     <function>clock_timestamp()</>, it returns the actual current time,
7953     but as a formatted <type>text</> string rather than a <type>timestamp
7954     with time zone</> value.
7955     <function>now()</> is a traditional <productname>PostgreSQL</productname>
7956     equivalent to <function>transaction_timestamp()</function>.
7957    </para>
7958
7959    <para>
7960     All the date/time data types also accept the special literal value
7961     <literal>now</literal> to specify the current date and time (again,
7962     interpreted as the transaction start time).  Thus,
7963     the following three all return the same result:
7964 <programlisting>
7965 SELECT CURRENT_TIMESTAMP;
7966 SELECT now();
7967 SELECT TIMESTAMP 'now';  -- incorrect for use with DEFAULT
7968 </programlisting>
7969    </para>
7970
7971     <tip>
7972      <para>
7973       You do not want to use the third form when specifying a <literal>DEFAULT</>
7974       clause while creating a table.  The system will convert <literal>now</literal>
7975       to a <type>timestamp</type> as soon as the constant is parsed, so that when
7976       the default value is needed,
7977       the time of the table creation would be used!  The first two
7978       forms will not be evaluated until the default value is used,
7979       because they are function calls.  Thus they will give the desired
7980       behavior of defaulting to the time of row insertion.
7981      </para>
7982     </tip>
7983   </sect2>
7984
7985   <sect2 id="functions-datetime-delay">
7986    <title>Delaying Execution</title>
7987
7988    <indexterm>
7989     <primary>pg_sleep</primary>
7990    </indexterm>
7991    <indexterm>
7992     <primary>pg_sleep_for</primary>
7993    </indexterm>
7994    <indexterm>
7995     <primary>pg_sleep_until</primary>
7996    </indexterm>
7997    <indexterm>
7998     <primary>sleep</primary>
7999    </indexterm>
8000    <indexterm>
8001     <primary>delay</primary>
8002    </indexterm>
8003
8004    <para>
8005     The following functions are available to delay execution of the server
8006     process:
8007 <synopsis>
8008 pg_sleep(<replaceable>seconds</replaceable>)
8009 pg_sleep_for(<type>interval</>)
8010 pg_sleep_until(<type>timestamp with time zone</>)
8011 </synopsis>
8012
8013     <function>pg_sleep</function> makes the current session's process
8014     sleep until <replaceable>seconds</replaceable> seconds have
8015     elapsed.  <replaceable>seconds</replaceable> is a value of type
8016     <type>double precision</>, so fractional-second delays can be specified.
8017     <function>pg_sleep_for</function> is a convenience function for larger
8018     sleep times specified as an <type>interval</>.
8019     <function>pg_sleep_until</function> is a convenience function for when
8020     a specific wake-up time is desired.
8021     For example:
8022
8023 <programlisting>
8024 SELECT pg_sleep(1.5);
8025 SELECT pg_sleep_for('5 minutes');
8026 SELECT pg_sleep_until('tomorrow 03:00');
8027 </programlisting>
8028    </para>
8029
8030    <note>
8031      <para>
8032       The effective resolution of the sleep interval is platform-specific;
8033       0.01 seconds is a common value.  The sleep delay will be at least as long
8034       as specified. It might be longer depending on factors such as server load.
8035       In particular, <function>pg_sleep_until</function> is not guaranteed to
8036       wake up exactly at the specified time, but it will not wake up any earlier.
8037      </para>
8038    </note>
8039
8040    <warning>
8041      <para>
8042       Make sure that your session does not hold more locks than necessary
8043       when calling <function>pg_sleep</function> or its variants.  Otherwise
8044       other sessions might have to wait for your sleeping process, slowing down
8045       the entire system.
8046      </para>
8047    </warning>
8048   </sect2>
8049
8050  </sect1>
8051
8052
8053  <sect1 id="functions-enum">
8054   <title>Enum Support Functions</title>
8055
8056   <para>
8057    For enum types (described in <xref linkend="datatype-enum">),
8058    there are several functions that allow cleaner programming without
8059    hard-coding particular values of an enum type.
8060    These are listed in <xref linkend="functions-enum-table">. The examples
8061    assume an enum type created as:
8062
8063 <programlisting>
8064 CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'purple');
8065 </programlisting>
8066
8067   </para>
8068
8069   <table id="functions-enum-table">
8070     <title>Enum Support Functions</title>
8071     <tgroup cols="4">
8072      <thead>
8073       <row>
8074        <entry>Function</entry>
8075        <entry>Description</entry>
8076        <entry>Example</entry>
8077        <entry>Example Result</entry>
8078       </row>
8079      </thead>
8080      <tbody>
8081       <row>
8082        <entry>
8083          <indexterm>
8084           <primary>enum_first</primary>
8085          </indexterm>
8086          <literal>enum_first(anyenum)</literal>
8087        </entry>
8088        <entry>Returns the first value of the input enum type</entry>
8089        <entry><literal>enum_first(null::rainbow)</literal></entry>
8090        <entry><literal>red</literal></entry>
8091       </row>
8092       <row>
8093        <entry>
8094          <indexterm>
8095           <primary>enum_last</primary>
8096          </indexterm>
8097          <literal>enum_last(anyenum)</literal>
8098        </entry>
8099        <entry>Returns the last value of the input enum type</entry>
8100        <entry><literal>enum_last(null::rainbow)</literal></entry>
8101        <entry><literal>purple</literal></entry>
8102       </row>
8103       <row>
8104        <entry>
8105          <indexterm>
8106           <primary>enum_range</primary>
8107          </indexterm>
8108          <literal>enum_range(anyenum)</literal>
8109        </entry>
8110        <entry>Returns all values of the input enum type in an ordered array</entry>
8111        <entry><literal>enum_range(null::rainbow)</literal></entry>
8112        <entry><literal>{red,orange,yellow,green,blue,purple}</literal></entry>
8113       </row>
8114       <row>
8115        <entry morerows="2"><literal>enum_range(anyenum, anyenum)</literal></entry>
8116        <entry morerows="2">
8117         Returns the range between the two given enum values, as an ordered
8118         array. The values must be from the same enum type. If the first
8119         parameter is null, the result will start with the first value of
8120         the enum type.
8121         If the second parameter is null, the result will end with the last
8122         value of the enum type.
8123        </entry>
8124        <entry><literal>enum_range('orange'::rainbow, 'green'::rainbow)</literal></entry>
8125        <entry><literal>{orange,yellow,green}</literal></entry>
8126       </row>
8127       <row>
8128        <entry><literal>enum_range(NULL, 'green'::rainbow)</literal></entry>
8129        <entry><literal>{red,orange,yellow,green}</literal></entry>
8130       </row>
8131       <row>
8132        <entry><literal>enum_range('orange'::rainbow, NULL)</literal></entry>
8133        <entry><literal>{orange,yellow,green,blue,purple}</literal></entry>
8134       </row>
8135      </tbody>
8136     </tgroup>
8137    </table>
8138
8139    <para>
8140     Notice that except for the two-argument form of <function>enum_range</>,
8141     these functions disregard the specific value passed to them; they care
8142     only about its declared data type.  Either null or a specific value of
8143     the type can be passed, with the same result.  It is more common to
8144     apply these functions to a table column or function argument than to
8145     a hardwired type name as suggested by the examples.
8146    </para>
8147  </sect1>
8148
8149  <sect1 id="functions-geometry">
8150   <title>Geometric Functions and Operators</title>
8151
8152    <para>
8153     The geometric types <type>point</type>, <type>box</type>,
8154     <type>lseg</type>, <type>line</type>, <type>path</type>,
8155     <type>polygon</type>, and <type>circle</type> have a large set of
8156     native support functions and operators, shown in <xref
8157     linkend="functions-geometry-op-table">, <xref
8158     linkend="functions-geometry-func-table">, and <xref
8159     linkend="functions-geometry-conv-table">.
8160    </para>
8161
8162    <caution>
8163     <para>
8164      Note that the <quote>same as</> operator, <literal>~=</>, represents
8165      the usual notion of equality for the <type>point</type>,
8166      <type>box</type>, <type>polygon</type>, and <type>circle</type> types.
8167      Some of these types also have an <literal>=</> operator, but
8168      <literal>=</> compares
8169      for equal <emphasis>areas</> only.  The other scalar comparison operators
8170      (<literal>&lt;=</> and so on) likewise compare areas for these types.
8171     </para>
8172    </caution>
8173
8174    <table id="functions-geometry-op-table">
8175      <title>Geometric Operators</title>
8176      <tgroup cols="3">
8177       <thead>
8178        <row>
8179         <entry>Operator</entry>
8180         <entry>Description</entry>
8181         <entry>Example</entry>
8182        </row>
8183       </thead>
8184       <tbody>
8185        <row>
8186         <entry> <literal>+</literal> </entry>
8187         <entry>Translation</entry>
8188         <entry><literal>box '((0,0),(1,1))' + point '(2.0,0)'</literal></entry>
8189        </row>
8190        <row>
8191         <entry> <literal>-</literal> </entry>
8192         <entry>Translation</entry>
8193         <entry><literal>box '((0,0),(1,1))' - point '(2.0,0)'</literal></entry>
8194        </row>
8195        <row>
8196         <entry> <literal>*</literal> </entry>
8197         <entry>Scaling/rotation</entry>
8198         <entry><literal>box '((0,0),(1,1))' * point '(2.0,0)'</literal></entry>
8199        </row>
8200        <row>
8201         <entry> <literal>/</literal> </entry>
8202         <entry>Scaling/rotation</entry>
8203         <entry><literal>box '((0,0),(2,2))' / point '(2.0,0)'</literal></entry>
8204        </row>
8205        <row>
8206         <entry> <literal>#</literal> </entry>
8207         <entry>Point or box of intersection</entry>
8208         <entry><literal>'((1,-1),(-1,1))' # '((1,1),(-1,-1))'</literal></entry>
8209        </row>
8210        <row>
8211         <entry> <literal>#</literal> </entry>
8212         <entry>Number of points in path or polygon</entry>
8213         <entry><literal># '((1,0),(0,1),(-1,0))'</literal></entry>
8214        </row>
8215        <row>
8216         <entry> <literal>@-@</literal> </entry>
8217         <entry>Length or circumference</entry>
8218         <entry><literal>@-@ path '((0,0),(1,0))'</literal></entry>
8219        </row>
8220        <row>
8221         <entry> <literal>@@</literal> </entry>
8222         <entry>Center</entry>
8223         <entry><literal>@@ circle '((0,0),10)'</literal></entry>
8224        </row>
8225        <row>
8226         <entry> <literal>##</literal> </entry>
8227         <entry>Closest point to first operand on second operand</entry>
8228         <entry><literal>point '(0,0)' ## lseg '((2,0),(0,2))'</literal></entry>
8229        </row>
8230        <row>
8231         <entry> <literal>&lt;-&gt;</literal> </entry>
8232         <entry>Distance between</entry>
8233         <entry><literal>circle '((0,0),1)' &lt;-&gt; circle '((5,0),1)'</literal></entry>
8234        </row>
8235        <row>
8236         <entry> <literal>&amp;&amp;</literal> </entry>
8237         <entry>Overlaps?  (One point in common makes this true.)</entry>
8238         <entry><literal>box '((0,0),(1,1))' &amp;&amp; box '((0,0),(2,2))'</literal></entry>
8239        </row>
8240        <row>
8241         <entry> <literal>&lt;&lt;</literal> </entry>
8242         <entry>Is strictly left of?</entry>
8243         <entry><literal>circle '((0,0),1)' &lt;&lt; circle '((5,0),1)'</literal></entry>
8244        </row>
8245        <row>
8246         <entry> <literal>&gt;&gt;</literal> </entry>
8247         <entry>Is strictly right of?</entry>
8248         <entry><literal>circle '((5,0),1)' &gt;&gt; circle '((0,0),1)'</literal></entry>
8249        </row>
8250        <row>
8251         <entry> <literal>&amp;&lt;</literal> </entry>
8252         <entry>Does not extend to the right of?</entry>
8253         <entry><literal>box '((0,0),(1,1))' &amp;&lt; box '((0,0),(2,2))'</literal></entry>
8254        </row>
8255        <row>
8256         <entry> <literal>&amp;&gt;</literal> </entry>
8257         <entry>Does not extend to the left of?</entry>
8258         <entry><literal>box '((0,0),(3,3))' &amp;&gt; box '((0,0),(2,2))'</literal></entry>
8259        </row>
8260        <row>
8261         <entry> <literal>&lt;&lt;|</literal> </entry>
8262         <entry>Is strictly below?</entry>
8263         <entry><literal>box '((0,0),(3,3))' &lt;&lt;| box '((3,4),(5,5))'</literal></entry>
8264        </row>
8265        <row>
8266         <entry> <literal>|&gt;&gt;</literal> </entry>
8267         <entry>Is strictly above?</entry>
8268         <entry><literal>box '((3,4),(5,5))' |&gt;&gt; box '((0,0),(3,3))'</literal></entry>
8269        </row>
8270        <row>
8271         <entry> <literal>&amp;&lt;|</literal> </entry>
8272         <entry>Does not extend above?</entry>
8273         <entry><literal>box '((0,0),(1,1))' &amp;&lt;| box '((0,0),(2,2))'</literal></entry>
8274        </row>
8275        <row>
8276         <entry> <literal>|&amp;&gt;</literal> </entry>
8277         <entry>Does not extend below?</entry>
8278         <entry><literal>box '((0,0),(3,3))' |&amp;&gt; box '((0,0),(2,2))'</literal></entry>
8279        </row>
8280        <row>
8281         <entry> <literal>&lt;^</literal> </entry>
8282         <entry>Is below (allows touching)?</entry>
8283         <entry><literal>circle '((0,0),1)' &lt;^ circle '((0,5),1)'</literal></entry>
8284        </row>
8285        <row>
8286         <entry> <literal>&gt;^</literal> </entry>
8287         <entry>Is above (allows touching)?</entry>
8288         <entry><literal>circle '((0,5),1)' &gt;^ circle '((0,0),1)'</literal></entry>
8289        </row>
8290        <row>
8291         <entry> <literal>?#</literal> </entry>
8292         <entry>Intersects?</entry>
8293         <entry><literal>lseg '((-1,0),(1,0))' ?# box '((-2,-2),(2,2))'</literal></entry>
8294        </row>
8295        <row>
8296         <entry> <literal>?-</literal> </entry>
8297         <entry>Is horizontal?</entry>
8298         <entry><literal>?- lseg '((-1,0),(1,0))'</literal></entry>
8299        </row>
8300        <row>
8301         <entry> <literal>?-</literal> </entry>
8302         <entry>Are horizontally aligned?</entry>
8303         <entry><literal>point '(1,0)' ?- point '(0,0)'</literal></entry>
8304        </row>
8305        <row>
8306         <entry> <literal>?|</literal> </entry>
8307         <entry>Is vertical?</entry>
8308         <entry><literal>?| lseg '((-1,0),(1,0))'</literal></entry>
8309        </row>
8310        <row>
8311         <entry> <literal>?|</literal> </entry>
8312         <entry>Are vertically aligned?</entry>
8313         <entry><literal>point '(0,1)' ?| point '(0,0)'</literal></entry>
8314        </row>
8315        <row>
8316         <entry> <literal>?-|</literal> </entry>
8317         <entry>Is perpendicular?</entry>
8318         <entry><literal>lseg '((0,0),(0,1))' ?-| lseg '((0,0),(1,0))'</literal></entry>
8319        </row>
8320        <row>
8321         <entry> <literal>?||</literal> </entry>
8322         <entry>Are parallel?</entry>
8323         <entry><literal>lseg '((-1,0),(1,0))' ?|| lseg '((-1,2),(1,2))'</literal></entry>
8324        </row>
8325        <row>
8326         <entry> <literal>@&gt;</literal> </entry>
8327         <entry>Contains?</entry>
8328         <entry><literal>circle '((0,0),2)' @&gt; point '(1,1)'</literal></entry>
8329        </row>
8330        <row>
8331         <entry> <literal>&lt;@</literal> </entry>
8332         <entry>Contained in or on?</entry>
8333         <entry><literal>point '(1,1)' &lt;@ circle '((0,0),2)'</literal></entry>
8334        </row>
8335        <row>
8336         <entry> <literal>~=</literal> </entry>
8337         <entry>Same as?</entry>
8338         <entry><literal>polygon '((0,0),(1,1))' ~= polygon '((1,1),(0,0))'</literal></entry>
8339        </row>
8340       </tbody>
8341      </tgroup>
8342    </table>
8343
8344    <note>
8345     <para>
8346      Before <productname>PostgreSQL</productname> 8.2, the containment
8347      operators <literal>@&gt;</> and <literal>&lt;@</> were respectively
8348      called <literal>~</> and <literal>@</>.  These names are still
8349      available, but are deprecated and will eventually be removed.
8350     </para>
8351    </note>
8352
8353    <indexterm>
8354     <primary>area</primary>
8355    </indexterm>
8356    <indexterm>
8357     <primary>center</primary>
8358    </indexterm>
8359    <indexterm>
8360     <primary>diameter</primary>
8361    </indexterm>
8362    <indexterm>
8363     <primary>height</primary>
8364    </indexterm>
8365    <indexterm>
8366     <primary>isclosed</primary>
8367    </indexterm>
8368    <indexterm>
8369     <primary>isopen</primary>
8370    </indexterm>
8371    <indexterm>
8372     <primary>length</primary>
8373    </indexterm>
8374    <indexterm>
8375     <primary>npoints</primary>
8376    </indexterm>
8377    <indexterm>
8378     <primary>pclose</primary>
8379    </indexterm>
8380    <indexterm>
8381     <primary>popen</primary>
8382    </indexterm>
8383    <indexterm>
8384     <primary>radius</primary>
8385    </indexterm>
8386    <indexterm>
8387     <primary>width</primary>
8388    </indexterm>
8389
8390    <table id="functions-geometry-func-table">
8391      <title>Geometric Functions</title>
8392      <tgroup cols="4">
8393       <thead>
8394        <row>
8395         <entry>Function</entry>
8396         <entry>Return Type</entry>
8397         <entry>Description</entry>
8398         <entry>Example</entry>
8399        </row>
8400       </thead>
8401       <tbody>
8402        <row>
8403         <entry><literal><function>area(<replaceable>object</>)</function></literal></entry>
8404         <entry><type>double precision</type></entry>
8405         <entry>area</entry>
8406         <entry><literal>area(box '((0,0),(1,1))')</literal></entry>
8407        </row>
8408        <row>
8409         <entry><literal><function>center(<replaceable>object</>)</function></literal></entry>
8410         <entry><type>point</type></entry>
8411         <entry>center</entry>
8412         <entry><literal>center(box '((0,0),(1,2))')</literal></entry>
8413        </row>
8414        <row>
8415         <entry><literal><function>diameter(<type>circle</>)</function></literal></entry>
8416         <entry><type>double precision</type></entry>
8417         <entry>diameter of circle</entry>
8418         <entry><literal>diameter(circle '((0,0),2.0)')</literal></entry>
8419        </row>
8420        <row>
8421         <entry><literal><function>height(<type>box</>)</function></literal></entry>
8422         <entry><type>double precision</type></entry>
8423         <entry>vertical size of box</entry>
8424         <entry><literal>height(box '((0,0),(1,1))')</literal></entry>
8425        </row>
8426        <row>
8427         <entry><literal><function>isclosed(<type>path</>)</function></literal></entry>
8428         <entry><type>boolean</type></entry>
8429         <entry>a closed path?</entry>
8430         <entry><literal>isclosed(path '((0,0),(1,1),(2,0))')</literal></entry>
8431        </row>
8432        <row>
8433         <entry><literal><function>isopen(<type>path</>)</function></literal></entry>
8434         <entry><type>boolean</type></entry>
8435         <entry>an open path?</entry>
8436         <entry><literal>isopen(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8437        </row>
8438        <row>
8439         <entry><literal><function>length(<replaceable>object</>)</function></literal></entry>
8440         <entry><type>double precision</type></entry>
8441         <entry>length</entry>
8442         <entry><literal>length(path '((-1,0),(1,0))')</literal></entry>
8443        </row>
8444        <row>
8445         <entry><literal><function>npoints(<type>path</>)</function></literal></entry>
8446         <entry><type>int</type></entry>
8447         <entry>number of points</entry>
8448         <entry><literal>npoints(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8449        </row>
8450        <row>
8451         <entry><literal><function>npoints(<type>polygon</>)</function></literal></entry>
8452         <entry><type>int</type></entry>
8453         <entry>number of points</entry>
8454         <entry><literal>npoints(polygon '((1,1),(0,0))')</literal></entry>
8455        </row>
8456        <row>
8457         <entry><literal><function>pclose(<type>path</>)</function></literal></entry>
8458         <entry><type>path</type></entry>
8459         <entry>convert path to closed</entry>
8460         <entry><literal>pclose(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8461        </row>
8462 <![IGNORE[
8463 <!-- Not defined by this name. Implements the intersection operator '#' -->
8464        <row>
8465         <entry><literal><function>point(<type>lseg</>, <type>lseg</>)</function></literal></entry>
8466         <entry><type>point</type></entry>
8467         <entry>intersection</entry>
8468         <entry><literal>point(lseg '((-1,0),(1,0))',lseg '((-2,-2),(2,2))')</literal></entry>
8469        </row>
8470 ]]>
8471        <row>
8472         <entry><literal><function>popen(<type>path</>)</function></literal></entry>
8473         <entry><type>path</type></entry>
8474         <entry>convert path to open</entry>
8475         <entry><literal>popen(path '((0,0),(1,1),(2,0))')</literal></entry>
8476        </row>
8477        <row>
8478         <entry><literal><function>radius(<type>circle</type>)</function></literal></entry>
8479         <entry><type>double precision</type></entry>
8480         <entry>radius of circle</entry>
8481         <entry><literal>radius(circle '((0,0),2.0)')</literal></entry>
8482        </row>
8483        <row>
8484         <entry><literal><function>width(<type>box</>)</function></literal></entry>
8485         <entry><type>double precision</type></entry>
8486         <entry>horizontal size of box</entry>
8487         <entry><literal>width(box '((0,0),(1,1))')</literal></entry>
8488        </row>
8489       </tbody>
8490      </tgroup>
8491    </table>
8492
8493    <table id="functions-geometry-conv-table">
8494      <title>Geometric Type Conversion Functions</title>
8495      <tgroup cols="4">
8496       <thead>
8497        <row>
8498         <entry>Function</entry>
8499         <entry>Return Type</entry>
8500         <entry>Description</entry>
8501         <entry>Example</entry>
8502        </row>
8503       </thead>
8504       <tbody>
8505        <row>
8506         <entry>
8507          <indexterm>
8508           <primary>box</primary>
8509          </indexterm>
8510          <literal><function>box(<type>circle</type>)</function></literal>
8511         </entry>
8512         <entry><type>box</type></entry>
8513         <entry>circle to box</entry>
8514         <entry><literal>box(circle '((0,0),2.0)')</literal></entry>
8515        </row>
8516        <row>
8517         <entry><literal><function>box(<type>point</type>)</function></literal></entry>
8518         <entry><type>box</type></entry>
8519         <entry>point to empty box</entry>
8520         <entry><literal>box(point '(0,0)')</literal></entry>
8521        </row>
8522        <row>
8523         <entry><literal><function>box(<type>point</type>, <type>point</type>)</function></literal></entry>
8524         <entry><type>box</type></entry>
8525         <entry>points to box</entry>
8526         <entry><literal>box(point '(0,0)', point '(1,1)')</literal></entry>
8527        </row>
8528        <row>
8529         <entry><literal><function>box(<type>polygon</type>)</function></literal></entry>
8530         <entry><type>box</type></entry>
8531         <entry>polygon to box</entry>
8532         <entry><literal>box(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8533        </row>
8534        <row>
8535         <entry><literal><function>bound_box(<type>box</type>, <type>box</type>)</function></literal></entry>
8536         <entry><type>box</type></entry>
8537         <entry>boxes to bounding box</entry>
8538         <entry><literal>bound_box(box '((0,0),(1,1))', box '((3,3),(4,4))')</literal></entry>
8539        </row>
8540        <row>
8541         <entry>
8542          <indexterm>
8543           <primary>circle</primary>
8544          </indexterm>
8545          <literal><function>circle(<type>box</type>)</function></literal>
8546         </entry>
8547         <entry><type>circle</type></entry>
8548         <entry>box to circle</entry>
8549         <entry><literal>circle(box '((0,0),(1,1))')</literal></entry>
8550        </row>
8551        <row>
8552         <entry><literal><function>circle(<type>point</type>, <type>double precision</type>)</function></literal></entry>
8553         <entry><type>circle</type></entry>
8554         <entry>center and radius to circle</entry>
8555         <entry><literal>circle(point '(0,0)', 2.0)</literal></entry>
8556        </row>
8557        <row>
8558         <entry><literal><function>circle(<type>polygon</type>)</function></literal></entry>
8559         <entry><type>circle</type></entry>
8560         <entry>polygon to circle</entry>
8561         <entry><literal>circle(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8562        </row>
8563        <row>
8564         <entry><literal><function>line(<type>point</type>, <type>point</type>)</function></literal></entry>
8565         <entry><type>line</type></entry>
8566         <entry>points to line</entry>
8567         <entry><literal>line(point '(-1,0)', point '(1,0)')</literal></entry>
8568        </row>
8569        <row>
8570         <entry>
8571          <indexterm>
8572           <primary>lseg</primary>
8573          </indexterm>
8574          <literal><function>lseg(<type>box</type>)</function></literal>
8575         </entry>
8576         <entry><type>lseg</type></entry>
8577         <entry>box diagonal to line segment</entry>
8578         <entry><literal>lseg(box '((-1,0),(1,0))')</literal></entry>
8579        </row>
8580        <row>
8581         <entry><literal><function>lseg(<type>point</type>, <type>point</type>)</function></literal></entry>
8582         <entry><type>lseg</type></entry>
8583         <entry>points to line segment</entry>
8584         <entry><literal>lseg(point '(-1,0)', point '(1,0)')</literal></entry>
8585        </row>
8586        <row>
8587         <entry>
8588          <indexterm>
8589           <primary>path</primary>
8590          </indexterm>
8591          <literal><function>path(<type>polygon</type>)</function></literal>
8592         </entry>
8593         <entry><type>path</type></entry>
8594         <entry>polygon to path</entry>
8595         <entry><literal>path(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8596        </row>
8597        <row>
8598         <entry>
8599          <indexterm>
8600           <primary>point</primary>
8601          </indexterm>
8602          <literal><function>point</function>(<type>double
8603          precision</type>, <type>double precision</type>)</literal>
8604         </entry>
8605         <entry><type>point</type></entry>
8606         <entry>construct point</entry>
8607         <entry><literal>point(23.4, -44.5)</literal></entry>
8608        </row>
8609        <row>
8610         <entry><literal><function>point(<type>box</type>)</function></literal></entry>
8611         <entry><type>point</type></entry>
8612         <entry>center of box</entry>
8613         <entry><literal>point(box '((-1,0),(1,0))')</literal></entry>
8614        </row>
8615        <row>
8616         <entry><literal><function>point(<type>circle</type>)</function></literal></entry>
8617         <entry><type>point</type></entry>
8618         <entry>center of circle</entry>
8619         <entry><literal>point(circle '((0,0),2.0)')</literal></entry>
8620        </row>
8621        <row>
8622         <entry><literal><function>point(<type>lseg</type>)</function></literal></entry>
8623         <entry><type>point</type></entry>
8624         <entry>center of line segment</entry>
8625         <entry><literal>point(lseg '((-1,0),(1,0))')</literal></entry>
8626        </row>
8627        <row>
8628         <entry><literal><function>point(<type>polygon</type>)</function></literal></entry>
8629         <entry><type>point</type></entry>
8630         <entry>center of polygon</entry>
8631         <entry><literal>point(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8632        </row>
8633        <row>
8634         <entry>
8635          <indexterm>
8636           <primary>polygon</primary>
8637          </indexterm>
8638          <literal><function>polygon(<type>box</type>)</function></literal>
8639         </entry>
8640         <entry><type>polygon</type></entry>
8641         <entry>box to 4-point polygon</entry>
8642         <entry><literal>polygon(box '((0,0),(1,1))')</literal></entry>
8643        </row>
8644        <row>
8645         <entry><literal><function>polygon(<type>circle</type>)</function></literal></entry>
8646         <entry><type>polygon</type></entry>
8647         <entry>circle to 12-point polygon</entry>
8648         <entry><literal>polygon(circle '((0,0),2.0)')</literal></entry>
8649        </row>
8650        <row>
8651         <entry><literal><function>polygon(<replaceable class="parameter">npts</replaceable>, <type>circle</type>)</function></literal></entry>
8652         <entry><type>polygon</type></entry>
8653         <entry>circle to <replaceable class="parameter">npts</replaceable>-point polygon</entry>
8654         <entry><literal>polygon(12, circle '((0,0),2.0)')</literal></entry>
8655        </row>
8656        <row>
8657         <entry><literal><function>polygon(<type>path</type>)</function></literal></entry>
8658         <entry><type>polygon</type></entry>
8659         <entry>path to polygon</entry>
8660         <entry><literal>polygon(path '((0,0),(1,1),(2,0))')</literal></entry>
8661        </row>
8662       </tbody>
8663      </tgroup>
8664    </table>
8665
8666     <para>
8667      It is possible to access the two component numbers of a <type>point</>
8668      as though the point were an array with indexes 0 and 1.  For example, if
8669      <literal>t.p</> is a <type>point</> column then
8670      <literal>SELECT p[0] FROM t</> retrieves the X coordinate and
8671      <literal>UPDATE t SET p[1] = ...</> changes the Y coordinate.
8672      In the same way, a value of type <type>box</> or <type>lseg</> can be treated
8673      as an array of two <type>point</> values.
8674     </para>
8675
8676     <para>
8677      The <function>area</function> function works for the types
8678      <type>box</type>, <type>circle</type>, and <type>path</type>.
8679      The <function>area</function> function only works on the
8680      <type>path</type> data type if the points in the
8681      <type>path</type> are non-intersecting.  For example, the
8682      <type>path</type>
8683      <literal>'((0,0),(0,1),(2,1),(2,2),(1,2),(1,0),(0,0))'::PATH</literal>
8684      will not work;  however, the following visually identical
8685      <type>path</type>
8686      <literal>'((0,0),(0,1),(1,1),(1,2),(2,2),(2,1),(1,1),(1,0),(0,0))'::PATH</literal>
8687      will work.  If the concept of an intersecting versus
8688      non-intersecting <type>path</type> is confusing, draw both of the
8689      above <type>path</type>s side by side on a piece of graph paper.
8690     </para>
8691
8692   </sect1>
8693
8694
8695  <sect1 id="functions-net">
8696   <title>Network Address Functions and Operators</title>
8697
8698   <para>
8699    <xref linkend="cidr-inet-operators-table"> shows the operators
8700    available for the <type>cidr</type> and <type>inet</type> types.
8701    The operators <literal>&lt;&lt;</literal>,
8702    <literal>&lt;&lt;=</literal>, <literal>&gt;&gt;</literal>,
8703    <literal>&gt;&gt;=</literal>, and <literal>&amp;&amp;</literal>
8704    test for subnet inclusion.  They
8705    consider only the network parts of the two addresses (ignoring any
8706    host part) and determine whether one network is identical to
8707    or a subnet of the other.
8708   </para>
8709
8710     <table id="cidr-inet-operators-table">
8711      <title><type>cidr</type> and <type>inet</type> Operators</title>
8712      <tgroup cols="3">
8713       <thead>
8714        <row>
8715         <entry>Operator</entry>
8716         <entry>Description</entry>
8717         <entry>Example</entry>
8718        </row>
8719       </thead>
8720       <tbody>
8721        <row>
8722         <entry> <literal>&lt;</literal> </entry>
8723         <entry>is less than</entry>
8724         <entry><literal>inet '192.168.1.5' &lt; inet '192.168.1.6'</literal></entry>
8725        </row>
8726        <row>
8727         <entry> <literal>&lt;=</literal> </entry>
8728         <entry>is less than or equal</entry>
8729         <entry><literal>inet '192.168.1.5' &lt;= inet '192.168.1.5'</literal></entry>
8730        </row>
8731        <row>
8732         <entry> <literal>=</literal> </entry>
8733         <entry>equals</entry>
8734         <entry><literal>inet '192.168.1.5' = inet '192.168.1.5'</literal></entry>
8735        </row>
8736        <row>
8737         <entry> <literal>&gt;=</literal> </entry>
8738         <entry>is greater or equal</entry>
8739         <entry><literal>inet '192.168.1.5' &gt;= inet '192.168.1.5'</literal></entry>
8740        </row>
8741        <row>
8742         <entry> <literal>&gt;</literal> </entry>
8743         <entry>is greater than</entry>
8744         <entry><literal>inet '192.168.1.5' &gt; inet '192.168.1.4'</literal></entry>
8745        </row>
8746        <row>
8747         <entry> <literal>&lt;&gt;</literal> </entry>
8748         <entry>is not equal</entry>
8749         <entry><literal>inet '192.168.1.5' &lt;&gt; inet '192.168.1.4'</literal></entry>
8750        </row>
8751        <row>
8752         <entry> <literal>&lt;&lt;</literal> </entry>
8753         <entry>is contained by</entry>
8754         <entry><literal>inet '192.168.1.5' &lt;&lt; inet '192.168.1/24'</literal></entry>
8755        </row>
8756        <row>
8757         <entry> <literal>&lt;&lt;=</literal> </entry>
8758         <entry>is contained by or equals</entry>
8759         <entry><literal>inet '192.168.1/24' &lt;&lt;= inet '192.168.1/24'</literal></entry>
8760        </row>
8761        <row>
8762         <entry> <literal>&gt;&gt;</literal> </entry>
8763         <entry>contains</entry>
8764         <entry><literal>inet '192.168.1/24' &gt;&gt; inet '192.168.1.5'</literal></entry>
8765        </row>
8766        <row>
8767         <entry> <literal>&gt;&gt;=</literal> </entry>
8768         <entry>contains or equals</entry>
8769         <entry><literal>inet '192.168.1/24' &gt;&gt;= inet '192.168.1/24'</literal></entry>
8770        </row>
8771        <row>
8772         <entry> <literal>&amp;&amp;</literal> </entry>
8773         <entry>contains or is contained by</entry>
8774         <entry><literal>inet '192.168.1/24' &amp;&amp; inet '192.168.1.80/28'</literal></entry>
8775        </row>
8776        <row>
8777         <entry> <literal>~</literal> </entry>
8778         <entry>bitwise NOT</entry>
8779         <entry><literal>~ inet '192.168.1.6'</literal></entry>
8780        </row>
8781        <row>
8782         <entry> <literal>&amp;</literal> </entry>
8783         <entry>bitwise AND</entry>
8784         <entry><literal>inet '192.168.1.6' &amp; inet '0.0.0.255'</literal></entry>
8785        </row>
8786        <row>
8787         <entry> <literal>|</literal> </entry>
8788         <entry>bitwise OR</entry>
8789         <entry><literal>inet '192.168.1.6' | inet '0.0.0.255'</literal></entry>
8790        </row>
8791        <row>
8792         <entry> <literal>+</literal> </entry>
8793         <entry>addition</entry>
8794         <entry><literal>inet '192.168.1.6' + 25</literal></entry>
8795        </row>
8796        <row>
8797         <entry> <literal>-</literal> </entry>
8798         <entry>subtraction</entry>
8799         <entry><literal>inet '192.168.1.43' - 36</literal></entry>
8800        </row>
8801        <row>
8802         <entry> <literal>-</literal> </entry>
8803         <entry>subtraction</entry>
8804         <entry><literal>inet '192.168.1.43' - inet '192.168.1.19'</literal></entry>
8805        </row>
8806       </tbody>
8807      </tgroup>
8808     </table>
8809
8810   <para>
8811    <xref linkend="cidr-inet-functions-table"> shows the functions
8812    available for use with the <type>cidr</type> and <type>inet</type>
8813    types.  The <function>abbrev</function>, <function>host</function>,
8814    and <function>text</function>
8815    functions are primarily intended to offer alternative display
8816    formats.
8817   </para>
8818
8819     <table id="cidr-inet-functions-table">
8820      <title><type>cidr</type> and <type>inet</type> Functions</title>
8821      <tgroup cols="5">
8822       <thead>
8823        <row>
8824         <entry>Function</entry>
8825         <entry>Return Type</entry>
8826         <entry>Description</entry>
8827         <entry>Example</entry>
8828         <entry>Result</entry>
8829        </row>
8830       </thead>
8831       <tbody>
8832        <row>
8833         <entry>
8834          <indexterm>
8835           <primary>abbrev</primary>
8836          </indexterm>
8837          <literal><function>abbrev(<type>inet</type>)</function></literal>
8838         </entry>
8839         <entry><type>text</type></entry>
8840         <entry>abbreviated display format as text</entry>
8841         <entry><literal>abbrev(inet '10.1.0.0/16')</literal></entry>
8842         <entry><literal>10.1.0.0/16</literal></entry>
8843        </row>
8844        <row>
8845         <entry><literal><function>abbrev(<type>cidr</type>)</function></literal></entry>
8846         <entry><type>text</type></entry>
8847         <entry>abbreviated display format as text</entry>
8848         <entry><literal>abbrev(cidr '10.1.0.0/16')</literal></entry>
8849         <entry><literal>10.1/16</literal></entry>
8850        </row>
8851        <row>
8852         <entry>
8853          <indexterm>
8854           <primary>broadcast</primary>
8855          </indexterm>
8856          <literal><function>broadcast(<type>inet</type>)</function></literal>
8857         </entry>
8858         <entry><type>inet</type></entry>
8859         <entry>broadcast address for network</entry>
8860         <entry><literal>broadcast('192.168.1.5/24')</literal></entry>
8861         <entry><literal>192.168.1.255/24</literal></entry>
8862        </row>
8863        <row>
8864         <entry>
8865          <indexterm>
8866           <primary>family</primary>
8867          </indexterm>
8868          <literal><function>family(<type>inet</type>)</function></literal>
8869         </entry>
8870         <entry><type>int</type></entry>
8871         <entry>extract family of address; <literal>4</literal> for IPv4,
8872          <literal>6</literal> for IPv6</entry>
8873         <entry><literal>family('::1')</literal></entry>
8874         <entry><literal>6</literal></entry>
8875        </row>
8876        <row>
8877         <entry>
8878          <indexterm>
8879           <primary>host</primary>
8880          </indexterm>
8881          <literal><function>host(<type>inet</type>)</function></literal>
8882         </entry>
8883         <entry><type>text</type></entry>
8884         <entry>extract IP address as text</entry>
8885         <entry><literal>host('192.168.1.5/24')</literal></entry>
8886         <entry><literal>192.168.1.5</literal></entry>
8887        </row>
8888        <row>
8889         <entry>
8890          <indexterm>
8891           <primary>hostmask</primary>
8892          </indexterm>
8893          <literal><function>hostmask(<type>inet</type>)</function></literal>
8894         </entry>
8895         <entry><type>inet</type></entry>
8896         <entry>construct host mask for network</entry>
8897         <entry><literal>hostmask('192.168.23.20/30')</literal></entry>
8898         <entry><literal>0.0.0.3</literal></entry>
8899        </row>
8900        <row>
8901         <entry>
8902          <indexterm>
8903           <primary>masklen</primary>
8904          </indexterm>
8905          <literal><function>masklen(<type>inet</type>)</function></literal>
8906         </entry>
8907         <entry><type>int</type></entry>
8908         <entry>extract netmask length</entry>
8909         <entry><literal>masklen('192.168.1.5/24')</literal></entry>
8910         <entry><literal>24</literal></entry>
8911        </row>
8912        <row>
8913         <entry>
8914          <indexterm>
8915           <primary>netmask</primary>
8916          </indexterm>
8917          <literal><function>netmask(<type>inet</type>)</function></literal>
8918         </entry>
8919         <entry><type>inet</type></entry>
8920         <entry>construct netmask for network</entry>
8921         <entry><literal>netmask('192.168.1.5/24')</literal></entry>
8922         <entry><literal>255.255.255.0</literal></entry>
8923        </row>
8924        <row>
8925         <entry>
8926          <indexterm>
8927           <primary>network</primary>
8928          </indexterm>
8929          <literal><function>network(<type>inet</type>)</function></literal>
8930         </entry>
8931         <entry><type>cidr</type></entry>
8932         <entry>extract network part of address</entry>
8933         <entry><literal>network('192.168.1.5/24')</literal></entry>
8934         <entry><literal>192.168.1.0/24</literal></entry>
8935        </row>
8936        <row>
8937         <entry>
8938          <indexterm>
8939           <primary>set_masklen</primary>
8940          </indexterm>
8941          <literal><function>set_masklen(<type>inet</type>, <type>int</type>)</function></literal>
8942         </entry>
8943         <entry><type>inet</type></entry>
8944         <entry>set netmask length for <type>inet</type> value</entry>
8945         <entry><literal>set_masklen('192.168.1.5/24', 16)</literal></entry>
8946         <entry><literal>192.168.1.5/16</literal></entry>
8947        </row>
8948        <row>
8949         <entry><literal><function>set_masklen(<type>cidr</type>, <type>int</type>)</function></literal></entry>
8950         <entry><type>cidr</type></entry>
8951         <entry>set netmask length for <type>cidr</type> value</entry>
8952         <entry><literal>set_masklen('192.168.1.0/24'::cidr, 16)</literal></entry>
8953         <entry><literal>192.168.0.0/16</literal></entry>
8954        </row>
8955        <row>
8956         <entry>
8957          <indexterm>
8958           <primary>text</primary>
8959          </indexterm>
8960          <literal><function>text(<type>inet</type>)</function></literal>
8961         </entry>
8962         <entry><type>text</type></entry>
8963         <entry>extract IP address and netmask length as text</entry>
8964         <entry><literal>text(inet '192.168.1.5')</literal></entry>
8965         <entry><literal>192.168.1.5/32</literal></entry>
8966        </row>
8967        <row>
8968         <entry>
8969          <indexterm>
8970           <primary>inet_same_family</primary>
8971          </indexterm>
8972          <literal><function>inet_same_family(<type>inet</type>, <type>inet</type>)</function></literal>
8973         </entry>
8974         <entry><type>boolean</type></entry>
8975         <entry>are the addresses from the same family?</entry>
8976         <entry><literal>inet_same_family('192.168.1.5/24', '::1')</literal></entry>
8977         <entry><literal>false</literal></entry>
8978        </row>
8979        <row>
8980         <entry>
8981          <indexterm>
8982           <primary>inet_merge</primary>
8983          </indexterm>
8984          <literal><function>inet_merge(<type>inet</type>, <type>inet</type>)</function></literal>
8985         </entry>
8986         <entry><type>cidr</type></entry>
8987         <entry>the smallest network which includes both of the given networks</entry>
8988         <entry><literal>inet_merge('192.168.1.5/24', '192.168.2.5/24')</literal></entry>
8989         <entry><literal>192.168.0.0/22</literal></entry>
8990        </row>
8991       </tbody>
8992      </tgroup>
8993     </table>
8994
8995   <para>
8996    Any <type>cidr</> value can be cast to <type>inet</> implicitly
8997    or explicitly; therefore, the functions shown above as operating on
8998    <type>inet</> also work on <type>cidr</> values.  (Where there are
8999    separate functions for <type>inet</> and <type>cidr</>, it is because
9000    the behavior should be different for the two cases.)
9001    Also, it is permitted to cast an <type>inet</> value to <type>cidr</>.
9002    When this is done, any bits to the right of the netmask are silently zeroed
9003    to create a valid <type>cidr</> value.
9004    In addition,
9005    you can cast a text value to <type>inet</> or <type>cidr</>
9006    using normal casting syntax: for example,
9007    <literal>inet(<replaceable>expression</>)</literal> or
9008    <literal><replaceable>colname</>::cidr</literal>.
9009   </para>
9010
9011   <para>
9012    <xref linkend="macaddr-functions-table"> shows the functions
9013    available for use with the <type>macaddr</type> type.  The function
9014    <literal><function>trunc(<type>macaddr</type>)</function></literal> returns a MAC
9015    address with the last 3 bytes set to zero.  This can be used to
9016    associate the remaining prefix with a manufacturer.
9017   </para>
9018
9019     <table id="macaddr-functions-table">
9020      <title><type>macaddr</type> Functions</title>
9021      <tgroup cols="5">
9022       <thead>
9023        <row>
9024         <entry>Function</entry>
9025         <entry>Return Type</entry>
9026         <entry>Description</entry>
9027         <entry>Example</entry>
9028         <entry>Result</entry>
9029        </row>
9030       </thead>
9031       <tbody>
9032        <row>
9033         <entry>
9034          <indexterm>
9035           <primary>trunc</primary>
9036          </indexterm>
9037          <literal><function>trunc(<type>macaddr</type>)</function></literal>
9038         </entry>
9039         <entry><type>macaddr</type></entry>
9040         <entry>set last 3 bytes to zero</entry>
9041         <entry><literal>trunc(macaddr '12:34:56:78:90:ab')</literal></entry>
9042         <entry><literal>12:34:56:00:00:00</literal></entry>
9043        </row>
9044       </tbody>
9045      </tgroup>
9046     </table>
9047
9048    <para>
9049     The <type>macaddr</type> type also supports the standard relational
9050     operators (<literal>&gt;</literal>, <literal>&lt;=</literal>, etc.) for
9051     lexicographical ordering, and the bitwise arithmetic operators
9052     (<literal>~</literal>, <literal>&amp;</literal> and <literal>|</literal>)
9053     for NOT, AND and OR.
9054    </para>
9055
9056   </sect1>
9057
9058
9059  <sect1 id="functions-textsearch">
9060   <title>Text Search Functions and Operators</title>
9061
9062    <indexterm zone="datatype-textsearch">
9063     <primary>full text search</primary>
9064     <secondary>functions and operators</secondary>
9065    </indexterm>
9066
9067    <indexterm zone="datatype-textsearch">
9068     <primary>text search</primary>
9069     <secondary>functions and operators</secondary>
9070    </indexterm>
9071
9072   <para>
9073    <xref linkend="textsearch-operators-table">,
9074    <xref linkend="textsearch-functions-table"> and
9075    <xref linkend="textsearch-functions-debug-table">
9076    summarize the functions and operators that are provided
9077    for full text searching.  See <xref linkend="textsearch"> for a detailed
9078    explanation of <productname>PostgreSQL</productname>'s text search
9079    facility.
9080   </para>
9081
9082     <table id="textsearch-operators-table">
9083      <title>Text Search Operators</title>
9084      <tgroup cols="5">
9085       <thead>
9086        <row>
9087         <entry>Operator</entry>
9088         <entry>Return Type</entry>
9089         <entry>Description</entry>
9090         <entry>Example</entry>
9091         <entry>Result</entry>
9092        </row>
9093       </thead>
9094       <tbody>
9095        <row>
9096         <entry> <literal>@@</literal> </entry>
9097         <entry><type>boolean</></entry>
9098         <entry><type>tsvector</> matches <type>tsquery</> ?</entry>
9099         <entry><literal>to_tsvector('fat cats ate rats') @@ to_tsquery('cat &amp; rat')</literal></entry>
9100         <entry><literal>t</literal></entry>
9101        </row>
9102        <row>
9103         <entry> <literal>@@@</literal> </entry>
9104         <entry><type>boolean</></entry>
9105         <entry>deprecated synonym for <literal>@@</></entry>
9106         <entry><literal>to_tsvector('fat cats ate rats') @@@ to_tsquery('cat &amp; rat')</literal></entry>
9107         <entry><literal>t</literal></entry>
9108        </row>
9109        <row>
9110         <entry> <literal>||</literal> </entry>
9111         <entry><type>tsvector</></entry>
9112         <entry>concatenate <type>tsvector</>s</entry>
9113         <entry><literal>'a:1 b:2'::tsvector || 'c:1 d:2 b:3'::tsvector</literal></entry>
9114         <entry><literal>'a':1 'b':2,5 'c':3 'd':4</literal></entry>
9115        </row>
9116        <row>
9117         <entry> <literal>&amp;&amp;</literal> </entry>
9118         <entry><type>tsquery</></entry>
9119         <entry>AND <type>tsquery</>s together</entry>
9120         <entry><literal>'fat | rat'::tsquery &amp;&amp; 'cat'::tsquery</literal></entry>
9121         <entry><literal>( 'fat' | 'rat' ) &amp; 'cat'</literal></entry>
9122        </row>
9123        <row>
9124         <entry> <literal>||</literal> </entry>
9125         <entry><type>tsquery</></entry>
9126         <entry>OR <type>tsquery</>s together</entry>
9127         <entry><literal>'fat | rat'::tsquery || 'cat'::tsquery</literal></entry>
9128         <entry><literal>( 'fat' | 'rat' ) | 'cat'</literal></entry>
9129        </row>
9130        <row>
9131         <entry> <literal>!!</literal> </entry>
9132         <entry><type>tsquery</></entry>
9133         <entry>negate a <type>tsquery</></entry>
9134         <entry><literal>!! 'cat'::tsquery</literal></entry>
9135         <entry><literal>!'cat'</literal></entry>
9136        </row>
9137        <row>
9138         <entry> <literal>&lt;-&gt;</literal> </entry>
9139         <entry><type>tsquery</></entry>
9140         <entry><type>tsquery</> followed by <type>tsquery</></entry>
9141         <entry><literal>to_tsquery('fat') &lt;-&gt; to_tsquery('rat')</literal></entry>
9142         <entry><literal>'fat' &lt;-&gt; 'rat'</literal></entry>
9143        </row>
9144        <row>
9145         <entry> <literal>@&gt;</literal> </entry>
9146         <entry><type>boolean</></entry>
9147         <entry><type>tsquery</> contains another ?</entry>
9148         <entry><literal>'cat'::tsquery @&gt; 'cat &amp; rat'::tsquery</literal></entry>
9149         <entry><literal>f</literal></entry>
9150        </row>
9151        <row>
9152         <entry> <literal>&lt;@</literal> </entry>
9153         <entry><type>boolean</></entry>
9154         <entry><type>tsquery</> is contained in ?</entry>
9155         <entry><literal>'cat'::tsquery &lt;@ 'cat &amp; rat'::tsquery</literal></entry>
9156         <entry><literal>t</literal></entry>
9157        </row>
9158       </tbody>
9159      </tgroup>
9160     </table>
9161
9162     <note>
9163      <para>
9164       The <type>tsquery</> containment operators consider only the lexemes
9165       listed in the two queries, ignoring the combining operators.
9166      </para>
9167     </note>
9168
9169     <para>
9170      In addition to the operators shown in the table, the ordinary B-tree
9171      comparison operators (<literal>=</>, <literal>&lt;</>, etc) are defined
9172      for types <type>tsvector</> and <type>tsquery</>.  These are not very
9173      useful for text searching but allow, for example, unique indexes to be
9174      built on columns of these types.
9175     </para>
9176
9177     <table id="textsearch-functions-table">
9178      <title>Text Search Functions</title>
9179      <tgroup cols="5">
9180       <thead>
9181        <row>
9182         <entry>Function</entry>
9183         <entry>Return Type</entry>
9184         <entry>Description</entry>
9185         <entry>Example</entry>
9186         <entry>Result</entry>
9187        </row>
9188       </thead>
9189       <tbody>
9190        <row>
9191         <entry>
9192          <indexterm>
9193           <primary>array_to_tsvector</primary>
9194          </indexterm>
9195          <literal><function>array_to_tsvector(<type>text[]</>)</function></literal>
9196         </entry>
9197         <entry><type>tsvector</type></entry>
9198         <entry>convert array of lexemes to <type>tsvector</type></entry>
9199         <entry><literal>array_to_tsvector('{fat,cat,rat}'::text[])</literal></entry>
9200         <entry><literal>'fat' 'cat' 'rat'</literal></entry>
9201        </row>
9202        <row>
9203         <entry>
9204          <indexterm>
9205           <primary>get_current_ts_config</primary>
9206          </indexterm>
9207          <literal><function>get_current_ts_config()</function></literal>
9208         </entry>
9209         <entry><type>regconfig</type></entry>
9210         <entry>get default text search configuration</entry>
9211         <entry><literal>get_current_ts_config()</literal></entry>
9212         <entry><literal>english</literal></entry>
9213        </row>
9214        <row>
9215         <entry>
9216          <indexterm>
9217           <primary>length</primary>
9218          </indexterm>
9219          <literal><function>length(<type>tsvector</>)</function></literal>
9220         </entry>
9221         <entry><type>integer</type></entry>
9222         <entry>number of lexemes in <type>tsvector</></entry>
9223         <entry><literal>length('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9224         <entry><literal>3</literal></entry>
9225        </row>
9226        <row>
9227         <entry>
9228          <indexterm>
9229           <primary>numnode</primary>
9230          </indexterm>
9231          <literal><function>numnode(<type>tsquery</>)</function></literal>
9232         </entry>
9233         <entry><type>integer</type></entry>
9234         <entry>number of lexemes plus operators in <type>tsquery</></entry>
9235         <entry><literal> numnode('(fat &amp; rat) | cat'::tsquery)</literal></entry>
9236         <entry><literal>5</literal></entry>
9237        </row>
9238        <row>
9239         <entry>
9240          <indexterm>
9241           <primary>plainto_tsquery</primary>
9242          </indexterm>
9243          <literal><function>plainto_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
9244         </entry>
9245         <entry><type>tsquery</type></entry>
9246         <entry>produce <type>tsquery</> ignoring punctuation</entry>
9247         <entry><literal>plainto_tsquery('english', 'The Fat Rats')</literal></entry>
9248         <entry><literal>'fat' &amp; 'rat'</literal></entry>
9249        </row>
9250        <row>
9251         <entry>
9252          <indexterm>
9253           <primary>phraseto_tsquery</primary>
9254          </indexterm>
9255          <literal><function>phraseto_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
9256         </entry>
9257         <entry><type>tsquery</type></entry>
9258         <entry>produce <type>tsquery</> that searches for a phrase,
9259          ignoring punctuation</entry>
9260         <entry><literal>phraseto_tsquery('english', 'The Fat Rats')</literal></entry>
9261         <entry><literal>'fat' &lt;-&gt; 'rat'</literal></entry>
9262        </row>
9263        <row>
9264         <entry>
9265          <indexterm>
9266           <primary>querytree</primary>
9267          </indexterm>
9268          <literal><function>querytree(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>)</function></literal>
9269         </entry>
9270         <entry><type>text</type></entry>
9271         <entry>get indexable part of a <type>tsquery</></entry>
9272         <entry><literal>querytree('foo &amp; ! bar'::tsquery)</literal></entry>
9273         <entry><literal>'foo'</literal></entry>
9274        </row>
9275        <row>
9276         <entry>
9277          <indexterm>
9278           <primary>setweight</primary>
9279          </indexterm>
9280          <literal><function>setweight(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">weight</replaceable> <type>"char"</>)</function></literal>
9281         </entry>
9282         <entry><type>tsvector</type></entry>
9283         <entry>assign <replaceable class="PARAMETER">weight</replaceable> to each element of <replaceable class="PARAMETER">vector</replaceable></entry>
9284         <entry><literal>setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A')</literal></entry>
9285         <entry><literal>'cat':3A 'fat':2A,4A 'rat':5A</literal></entry>
9286        </row>
9287        <row>
9288         <entry>
9289          <indexterm>
9290           <primary>setweight</primary>
9291           <secondary>setweight for specific lexeme(s)</secondary>
9292          </indexterm>
9293          <literal><function>setweight(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">weight</replaceable> <type>"char"</>, <replaceable class="PARAMETER">lexemes</replaceable> <type>text[]</>)</function></literal>
9294         </entry>
9295         <entry><type>tsvector</type></entry>
9296         <entry>assign <replaceable class="PARAMETER">weight</replaceable> to elements of <replaceable class="PARAMETER">vector</replaceable> that are listed in <replaceable class="PARAMETER">lexemes</replaceable></entry>
9297         <entry><literal>setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A', '{cat,rat}')</literal></entry>
9298         <entry><literal>'cat':3A 'fat':2,4 'rat':5A</literal></entry>
9299        </row>
9300        <row>
9301         <entry>
9302          <indexterm>
9303           <primary>strip</primary>
9304          </indexterm>
9305          <literal><function>strip(<type>tsvector</>)</function></literal>
9306         </entry>
9307         <entry><type>tsvector</type></entry>
9308         <entry>remove positions and weights from <type>tsvector</></entry>
9309         <entry><literal>strip('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9310         <entry><literal>'cat' 'fat' 'rat'</literal></entry>
9311        </row>
9312        <row>
9313         <entry>
9314          <indexterm>
9315           <primary>to_tsquery</primary>
9316          </indexterm>
9317          <literal><function>to_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
9318         </entry>
9319         <entry><type>tsquery</type></entry>
9320         <entry>normalize words and convert to <type>tsquery</></entry>
9321         <entry><literal>to_tsquery('english', 'The &amp; Fat &amp; Rats')</literal></entry>
9322         <entry><literal>'fat' &amp; 'rat'</literal></entry>
9323        </row>
9324        <row>
9325         <entry>
9326          <indexterm>
9327           <primary>to_tsvector</primary>
9328          </indexterm>
9329          <literal><function>to_tsvector(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">document</> <type>text</type>)</function></literal>
9330         </entry>
9331         <entry><type>tsvector</type></entry>
9332         <entry>reduce document text to <type>tsvector</></entry>
9333         <entry><literal>to_tsvector('english', 'The Fat Rats')</literal></entry>
9334         <entry><literal>'fat':2 'rat':3</literal></entry>
9335        </row>
9336        <row>
9337         <entry>
9338          <indexterm>
9339           <primary>ts_delete</primary>
9340          </indexterm>
9341          <literal><function>ts_delete(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">lexeme</replaceable> <type>text</>)</function></literal>
9342         </entry>
9343         <entry><type>tsvector</type></entry>
9344         <entry>remove given <replaceable class="PARAMETER">lexeme</replaceable> from <replaceable class="PARAMETER">vector</replaceable></entry>
9345         <entry><literal>ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, 'fat')</literal></entry>
9346         <entry><literal>'cat':3 'rat':5A</literal></entry>
9347        </row>
9348        <row>
9349         <entry>
9350          <!-- previous indexterm entry covers this too -->
9351          <literal><function>ts_delete(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">lexemes</replaceable> <type>text[]</>)</function></literal>
9352         </entry>
9353         <entry><type>tsvector</type></entry>
9354         <entry>remove any occurrence of lexemes in <replaceable class="PARAMETER">lexemes</replaceable> from <replaceable class="PARAMETER">vector</replaceable></entry>
9355         <entry><literal>ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, ARRAY['fat','rat'])</literal></entry>
9356         <entry><literal>'cat':3</literal></entry>
9357        </row>
9358        <row>
9359         <entry>
9360          <indexterm>
9361           <primary>ts_filter</primary>
9362          </indexterm>
9363          <literal><function>ts_filter(<replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">weights</replaceable> <type>"char"[]</>)</function></literal>
9364         </entry>
9365         <entry><type>tsvector</type></entry>
9366         <entry>Select only elements with given <replaceable class="PARAMETER">weights</replaceable> from <replaceable class="PARAMETER">vector</replaceable></entry>
9367         <entry><literal>ts_filter('fat:2,4 cat:3b rat:5A'::tsvector, '{a,b}')</literal></entry>
9368         <entry><literal>'cat':3B 'rat':5A</literal></entry>
9369        </row>
9370        <row>
9371         <entry>
9372          <indexterm>
9373           <primary>ts_headline</primary>
9374          </indexterm>
9375          <literal><function>ts_headline(<optional> <replaceable class="PARAMETER">config</replaceable> <type>regconfig</>, </optional> <replaceable class="PARAMETER">document</replaceable> <type>text</>, <replaceable class="PARAMETER">query</replaceable> <type>tsquery</> <optional>, <replaceable class="PARAMETER">options</replaceable> <type>text</> </optional>)</function></literal>
9376         </entry>
9377         <entry><type>text</type></entry>
9378         <entry>display a query match</entry>
9379         <entry><literal>ts_headline('x y z', 'z'::tsquery)</literal></entry>
9380         <entry><literal>x y &lt;b&gt;z&lt;/b&gt;</literal></entry>
9381        </row>
9382        <row>
9383         <entry>
9384          <indexterm>
9385           <primary>ts_rank</primary>
9386          </indexterm>
9387          <literal><function>ts_rank(<optional> <replaceable class="PARAMETER">weights</replaceable> <type>float4[]</>, </optional> <replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">query</replaceable> <type>tsquery</> <optional>, <replaceable class="PARAMETER">normalization</replaceable> <type>integer</> </optional>)</function></literal>
9388         </entry>
9389         <entry><type>float4</type></entry>
9390         <entry>rank document for query</entry>
9391         <entry><literal>ts_rank(textsearch, query)</literal></entry>
9392         <entry><literal>0.818</literal></entry>
9393        </row>
9394        <row>
9395         <entry>
9396          <indexterm>
9397           <primary>ts_rank_cd</primary>
9398          </indexterm>
9399          <literal><function>ts_rank_cd(<optional> <replaceable class="PARAMETER">weights</replaceable> <type>float4[]</>, </optional> <replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">query</replaceable> <type>tsquery</> <optional>, <replaceable class="PARAMETER">normalization</replaceable> <type>integer</> </optional>)</function></literal>
9400         </entry>
9401         <entry><type>float4</type></entry>
9402         <entry>rank document for query using cover density</entry>
9403         <entry><literal>ts_rank_cd('{0.1, 0.2, 0.4, 1.0}', textsearch, query)</literal></entry>
9404         <entry><literal>2.01317</literal></entry>
9405        </row>
9406        <row>
9407         <entry>
9408          <indexterm>
9409           <primary>ts_rewrite</primary>
9410          </indexterm>
9411          <literal><function>ts_rewrite(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">target</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">substitute</replaceable> <type>tsquery</>)</function></literal>
9412         </entry>
9413         <entry><type>tsquery</type></entry>
9414         <entry>replace <replaceable>target</> with <replaceable>substitute</>
9415          within query</entry>
9416         <entry><literal>ts_rewrite('a &amp; b'::tsquery, 'a'::tsquery, 'foo|bar'::tsquery)</literal></entry>
9417         <entry><literal>'b' &amp; ( 'foo' | 'bar' )</literal></entry>
9418        </row>
9419        <row>
9420         <entry><literal><function>ts_rewrite(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">select</replaceable> <type>text</>)</function></literal></entry>
9421         <entry><type>tsquery</type></entry>
9422         <entry>replace using targets and substitutes from a <command>SELECT</> command</entry>
9423         <entry><literal>SELECT ts_rewrite('a &amp; b'::tsquery, 'SELECT t,s FROM aliases')</literal></entry>
9424         <entry><literal>'b' &amp; ( 'foo' | 'bar' )</literal></entry>
9425        </row>
9426        <row>
9427         <entry>
9428          <indexterm>
9429           <primary>tsquery_phrase</primary>
9430          </indexterm>
9431          <literal><function>tsquery_phrase(<replaceable class="PARAMETER">query1</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">query2</replaceable> <type>tsquery</>)</function></literal>
9432         </entry>
9433         <entry><type>tsquery</type></entry>
9434         <entry>make query that searches for <replaceable>query1</> followed
9435          by <replaceable>query2</> (same as <literal>&lt;-&gt;</>
9436          operator)</entry>
9437         <entry><literal>tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'))</literal></entry>
9438         <entry><literal>'fat' &lt;-&gt; 'cat'</literal></entry>
9439        </row>
9440        <row>
9441         <entry>
9442          <literal><function>tsquery_phrase(<replaceable class="PARAMETER">query1</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">query2</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">distance</replaceable> <type>integer</>)</function></literal>
9443         </entry>
9444         <entry><type>tsquery</type></entry>
9445         <entry>make query that searches for <replaceable>query1</> followed by
9446          <replaceable>query2</> at maximum distance <replaceable>distance</></entry>
9447         <entry><literal>tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'), 10)</literal></entry>
9448         <entry><literal>'fat' &lt;10&gt; 'cat'</literal></entry>
9449        </row>
9450        <row>
9451         <entry>
9452          <indexterm>
9453           <primary>tsvector_to_array</primary>
9454          </indexterm>
9455          <literal><function>tsvector_to_array(<type>tsvector</>)</function></literal>
9456         </entry>
9457         <entry><type>text[]</type></entry>
9458         <entry>convert <type>tsvector</> to array of lexemes</entry>
9459         <entry><literal>tsvector_to_array('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9460         <entry><literal>{cat,fat,rat}</literal></entry>
9461        </row>
9462        <row>
9463         <entry>
9464          <indexterm>
9465           <primary>tsvector_update_trigger</primary>
9466          </indexterm>
9467          <literal><function>tsvector_update_trigger()</function></literal>
9468         </entry>
9469         <entry><type>trigger</type></entry>
9470         <entry>trigger function for automatic <type>tsvector</> column update</entry>
9471         <entry><literal>CREATE TRIGGER ... tsvector_update_trigger(tsvcol, 'pg_catalog.swedish', title, body)</literal></entry>
9472         <entry><literal></literal></entry>
9473        </row>
9474        <row>
9475         <entry>
9476          <indexterm>
9477           <primary>tsvector_update_trigger_column</primary>
9478          </indexterm>
9479          <literal><function>tsvector_update_trigger_column()</function></literal>
9480         </entry>
9481         <entry><type>trigger</type></entry>
9482         <entry>trigger function for automatic <type>tsvector</> column update</entry>
9483         <entry><literal>CREATE TRIGGER ... tsvector_update_trigger_column(tsvcol, configcol, title, body)</literal></entry>
9484         <entry><literal></literal></entry>
9485        </row>
9486        <row>
9487         <entry>
9488          <indexterm>
9489           <primary>unnest</primary>
9490           <secondary>for tsvector</secondary>
9491          </indexterm>
9492          <literal><function>unnest(<type>tsvector</>, OUT <replaceable class="PARAMETER">lexeme</> <type>text</>, OUT <replaceable class="PARAMETER">positions</> <type>smallint[]</>, OUT <replaceable class="PARAMETER">weights</> <type>text</>)</function></literal>
9493         </entry>
9494         <entry><type>setof record</type></entry>
9495         <entry>expand a tsvector to a set of rows</entry>
9496         <entry><literal>unnest('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
9497         <entry><literal>(cat,{3},{D}) ...</literal></entry>
9498        </row>
9499       </tbody>
9500      </tgroup>
9501     </table>
9502
9503   <note>
9504    <para>
9505     All the text search functions that accept an optional <type>regconfig</>
9506     argument will use the configuration specified by
9507     <xref linkend="guc-default-text-search-config">
9508     when that argument is omitted.
9509    </para>
9510   </note>
9511
9512   <para>
9513    The functions in
9514    <xref linkend="textsearch-functions-debug-table">
9515    are listed separately because they are not usually used in everyday text
9516    searching operations.  They are helpful for development and debugging
9517    of new text search configurations.
9518   </para>
9519
9520     <table id="textsearch-functions-debug-table">
9521      <title>Text Search Debugging Functions</title>
9522      <tgroup cols="5">
9523       <thead>
9524        <row>
9525         <entry>Function</entry>
9526         <entry>Return Type</entry>
9527         <entry>Description</entry>
9528         <entry>Example</entry>
9529         <entry>Result</entry>
9530        </row>
9531       </thead>
9532       <tbody>
9533        <row>
9534         <entry>
9535          <indexterm>
9536           <primary>ts_debug</primary>
9537          </indexterm>
9538          <literal><function>ts_debug(<optional> <replaceable class="PARAMETER">config</replaceable> <type>regconfig</>, </optional> <replaceable class="PARAMETER">document</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">alias</> <type>text</>, OUT <replaceable class="PARAMETER">description</> <type>text</>, OUT <replaceable class="PARAMETER">token</> <type>text</>, OUT <replaceable class="PARAMETER">dictionaries</> <type>regdictionary[]</>, OUT <replaceable class="PARAMETER">dictionary</> <type>regdictionary</>, OUT <replaceable class="PARAMETER">lexemes</> <type>text[]</>)</function></literal>
9539         </entry>
9540         <entry><type>setof record</type></entry>
9541         <entry>test a configuration</entry>
9542         <entry><literal>ts_debug('english', 'The Brightest supernovaes')</literal></entry>
9543         <entry><literal>(asciiword,"Word, all ASCII",The,{english_stem},english_stem,{}) ...</literal></entry>
9544        </row>
9545        <row>
9546         <entry>
9547          <indexterm>
9548           <primary>ts_lexize</primary>
9549          </indexterm>
9550          <literal><function>ts_lexize(<replaceable class="PARAMETER">dict</replaceable> <type>regdictionary</>, <replaceable class="PARAMETER">token</replaceable> <type>text</>)</function></literal>
9551         </entry>
9552         <entry><type>text[]</type></entry>
9553         <entry>test a dictionary</entry>
9554         <entry><literal>ts_lexize('english_stem', 'stars')</literal></entry>
9555         <entry><literal>{star}</literal></entry>
9556        </row>
9557        <row>
9558         <entry>
9559          <indexterm>
9560           <primary>ts_parse</primary>
9561          </indexterm>
9562          <literal><function>ts_parse(<replaceable class="PARAMETER">parser_name</replaceable> <type>text</>, <replaceable class="PARAMETER">document</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">token</> <type>text</>)</function></literal>
9563         </entry>
9564         <entry><type>setof record</type></entry>
9565         <entry>test a parser</entry>
9566         <entry><literal>ts_parse('default', 'foo - bar')</literal></entry>
9567         <entry><literal>(1,foo) ...</literal></entry>
9568        </row>
9569        <row>
9570         <entry><literal><function>ts_parse(<replaceable class="PARAMETER">parser_oid</replaceable> <type>oid</>, <replaceable class="PARAMETER">document</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">token</> <type>text</>)</function></literal></entry>
9571         <entry><type>setof record</type></entry>
9572         <entry>test a parser</entry>
9573         <entry><literal>ts_parse(3722, 'foo - bar')</literal></entry>
9574         <entry><literal>(1,foo) ...</literal></entry>
9575        </row>
9576        <row>
9577         <entry>
9578          <indexterm>
9579           <primary>ts_token_type</primary>
9580          </indexterm>
9581          <literal><function>ts_token_type(<replaceable class="PARAMETER">parser_name</> <type>text</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">alias</> <type>text</>, OUT <replaceable class="PARAMETER">description</> <type>text</>)</function></literal>
9582         </entry>
9583         <entry><type>setof record</type></entry>
9584         <entry>get token types defined by parser</entry>
9585         <entry><literal>ts_token_type('default')</literal></entry>
9586         <entry><literal>(1,asciiword,"Word, all ASCII") ...</literal></entry>
9587        </row>
9588        <row>
9589         <entry><literal><function>ts_token_type(<replaceable class="PARAMETER">parser_oid</> <type>oid</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">alias</> <type>text</>, OUT <replaceable class="PARAMETER">description</> <type>text</>)</function></literal></entry>
9590         <entry><type>setof record</type></entry>
9591         <entry>get token types defined by parser</entry>
9592         <entry><literal>ts_token_type(3722)</literal></entry>
9593         <entry><literal>(1,asciiword,"Word, all ASCII") ...</literal></entry>
9594        </row>
9595        <row>
9596         <entry>
9597          <indexterm>
9598           <primary>ts_stat</primary>
9599          </indexterm>
9600          <literal><function>ts_stat(<replaceable class="PARAMETER">sqlquery</replaceable> <type>text</>, <optional> <replaceable class="PARAMETER">weights</replaceable> <type>text</>, </optional> OUT <replaceable class="PARAMETER">word</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">ndoc</replaceable> <type>integer</>, OUT <replaceable class="PARAMETER">nentry</replaceable> <type>integer</>)</function></literal>
9601         </entry>
9602         <entry><type>setof record</type></entry>
9603         <entry>get statistics of a <type>tsvector</> column</entry>
9604         <entry><literal>ts_stat('SELECT vector from apod')</literal></entry>
9605         <entry><literal>(foo,10,15) ...</literal></entry>
9606        </row>
9607       </tbody>
9608      </tgroup>
9609     </table>
9610
9611  </sect1>
9612
9613
9614  <sect1 id="functions-xml">
9615   <title>XML Functions</title>
9616
9617   <para>
9618    The functions and function-like expressions described in this
9619    section operate on values of type <type>xml</type>.  Check <xref
9620    linkend="datatype-xml"> for information about the <type>xml</type>
9621    type.  The function-like expressions <function>xmlparse</function>
9622    and <function>xmlserialize</function> for converting to and from
9623    type <type>xml</type> are not repeated here.  Use of most of these
9624    functions requires the installation to have been built
9625    with <command>configure --with-libxml</>.
9626   </para>
9627
9628   <sect2 id="functions-producing-xml">
9629    <title>Producing XML Content</title>
9630
9631    <para>
9632     A set of functions and function-like expressions are available for
9633     producing XML content from SQL data.  As such, they are
9634     particularly suitable for formatting query results into XML
9635     documents for processing in client applications.
9636    </para>
9637
9638    <sect3>
9639     <title><literal>xmlcomment</literal></title>
9640
9641     <indexterm>
9642      <primary>xmlcomment</primary>
9643     </indexterm>
9644
9645 <synopsis>
9646 <function>xmlcomment</function>(<replaceable>text</replaceable>)
9647 </synopsis>
9648
9649     <para>
9650      The function <function>xmlcomment</function> creates an XML value
9651      containing an XML comment with the specified text as content.
9652      The text cannot contain <quote><literal>--</literal></quote> or end with a
9653      <quote><literal>-</literal></quote> so that the resulting construct is a valid
9654      XML comment.  If the argument is null, the result is null.
9655     </para>
9656
9657     <para>
9658      Example:
9659 <screen><![CDATA[
9660 SELECT xmlcomment('hello');
9661
9662   xmlcomment
9663 --------------
9664  <!--hello-->
9665 ]]></screen>
9666     </para>
9667    </sect3>
9668
9669    <sect3>
9670     <title><literal>xmlconcat</literal></title>
9671
9672     <indexterm>
9673      <primary>xmlconcat</primary>
9674     </indexterm>
9675
9676 <synopsis>
9677 <function>xmlconcat</function>(<replaceable>xml</replaceable><optional>, ...</optional>)
9678 </synopsis>
9679
9680     <para>
9681      The function <function>xmlconcat</function> concatenates a list
9682      of individual XML values to create a single value containing an
9683      XML content fragment.  Null values are omitted; the result is
9684      only null if there are no nonnull arguments.
9685     </para>
9686
9687     <para>
9688      Example:
9689 <screen><![CDATA[
9690 SELECT xmlconcat('<abc/>', '<bar>foo</bar>');
9691
9692       xmlconcat
9693 ----------------------
9694  <abc/><bar>foo</bar>
9695 ]]></screen>
9696     </para>
9697
9698     <para>
9699      XML declarations, if present, are combined as follows.  If all
9700      argument values have the same XML version declaration, that
9701      version is used in the result, else no version is used.  If all
9702      argument values have the standalone declaration value
9703      <quote>yes</quote>, then that value is used in the result.  If
9704      all argument values have a standalone declaration value and at
9705      least one is <quote>no</quote>, then that is used in the result.
9706      Else the result will have no standalone declaration.  If the
9707      result is determined to require a standalone declaration but no
9708      version declaration, a version declaration with version 1.0 will
9709      be used because XML requires an XML declaration to contain a
9710      version declaration.  Encoding declarations are ignored and
9711      removed in all cases.
9712     </para>
9713
9714     <para>
9715      Example:
9716 <screen><![CDATA[
9717 SELECT xmlconcat('<?xml version="1.1"?><foo/>', '<?xml version="1.1" standalone="no"?><bar/>');
9718
9719              xmlconcat
9720 -----------------------------------
9721  <?xml version="1.1"?><foo/><bar/>
9722 ]]></screen>
9723     </para>
9724    </sect3>
9725
9726    <sect3>
9727     <title><literal>xmlelement</literal></title>
9728
9729    <indexterm>
9730     <primary>xmlelement</primary>
9731    </indexterm>
9732
9733 <synopsis>
9734 <function>xmlelement</function>(name <replaceable>name</replaceable> <optional>, xmlattributes(<replaceable>value</replaceable> <optional>AS <replaceable>attname</replaceable></optional> <optional>, ... </optional>)</optional> <optional><replaceable>, content, ...</replaceable></optional>)
9735 </synopsis>
9736
9737     <para>
9738      The <function>xmlelement</function> expression produces an XML
9739      element with the given name, attributes, and content.
9740     </para>
9741
9742     <para>
9743      Examples:
9744 <screen><![CDATA[
9745 SELECT xmlelement(name foo);
9746
9747  xmlelement
9748 ------------
9749  <foo/>
9750
9751 SELECT xmlelement(name foo, xmlattributes('xyz' as bar));
9752
9753     xmlelement
9754 ------------------
9755  <foo bar="xyz"/>
9756
9757 SELECT xmlelement(name foo, xmlattributes(current_date as bar), 'cont', 'ent');
9758
9759              xmlelement
9760 -------------------------------------
9761  <foo bar="2007-01-26">content</foo>
9762 ]]></screen>
9763     </para>
9764
9765     <para>
9766      Element and attribute names that are not valid XML names are
9767      escaped by replacing the offending characters by the sequence
9768      <literal>_x<replaceable>HHHH</replaceable>_</literal>, where
9769      <replaceable>HHHH</replaceable> is the character's Unicode
9770      codepoint in hexadecimal notation.  For example:
9771 <screen><![CDATA[
9772 SELECT xmlelement(name "foo$bar", xmlattributes('xyz' as "a&b"));
9773
9774             xmlelement
9775 ----------------------------------
9776  <foo_x0024_bar a_x0026_b="xyz"/>
9777 ]]></screen>
9778     </para>
9779
9780     <para>
9781      An explicit attribute name need not be specified if the attribute
9782      value is a column reference, in which case the column's name will
9783      be used as the attribute name by default.  In other cases, the
9784      attribute must be given an explicit name.  So this example is
9785      valid:
9786 <screen>
9787 CREATE TABLE test (a xml, b xml);
9788 SELECT xmlelement(name test, xmlattributes(a, b)) FROM test;
9789 </screen>
9790      But these are not:
9791 <screen>
9792 SELECT xmlelement(name test, xmlattributes('constant'), a, b) FROM test;
9793 SELECT xmlelement(name test, xmlattributes(func(a, b))) FROM test;
9794 </screen>
9795     </para>
9796
9797     <para>
9798      Element content, if specified, will be formatted according to
9799      its data type.  If the content is itself of type <type>xml</type>,
9800      complex XML documents can be constructed.  For example:
9801 <screen><![CDATA[
9802 SELECT xmlelement(name foo, xmlattributes('xyz' as bar),
9803                             xmlelement(name abc),
9804                             xmlcomment('test'),
9805                             xmlelement(name xyz));
9806
9807                   xmlelement
9808 ----------------------------------------------
9809  <foo bar="xyz"><abc/><!--test--><xyz/></foo>
9810 ]]></screen>
9811
9812      Content of other types will be formatted into valid XML character
9813      data.  This means in particular that the characters &lt;, &gt;,
9814      and &amp; will be converted to entities.  Binary data (data type
9815      <type>bytea</type>) will be represented in base64 or hex
9816      encoding, depending on the setting of the configuration parameter
9817      <xref linkend="guc-xmlbinary">.  The particular behavior for
9818      individual data types is expected to evolve in order to align the
9819      SQL and PostgreSQL data types with the XML Schema specification,
9820      at which point a more precise description will appear.
9821     </para>
9822    </sect3>
9823
9824    <sect3>
9825     <title><literal>xmlforest</literal></title>
9826
9827    <indexterm>
9828     <primary>xmlforest</primary>
9829    </indexterm>
9830
9831 <synopsis>
9832 <function>xmlforest</function>(<replaceable>content</replaceable> <optional>AS <replaceable>name</replaceable></optional> <optional>, ...</optional>)
9833 </synopsis>
9834
9835     <para>
9836      The <function>xmlforest</function> expression produces an XML
9837      forest (sequence) of elements using the given names and content.
9838     </para>
9839
9840     <para>
9841      Examples:
9842 <screen><![CDATA[
9843 SELECT xmlforest('abc' AS foo, 123 AS bar);
9844
9845           xmlforest
9846 ------------------------------
9847  <foo>abc</foo><bar>123</bar>
9848
9849
9850 SELECT xmlforest(table_name, column_name)
9851 FROM information_schema.columns
9852 WHERE table_schema = 'pg_catalog';
9853
9854                                          xmlforest
9855 -------------------------------------------------------------------------------------------
9856  <table_name>pg_authid</table_name><column_name>rolname</column_name>
9857  <table_name>pg_authid</table_name><column_name>rolsuper</column_name>
9858  ...
9859 ]]></screen>
9860
9861      As seen in the second example, the element name can be omitted if
9862      the content value is a column reference, in which case the column
9863      name is used by default.  Otherwise, a name must be specified.
9864     </para>
9865
9866     <para>
9867      Element names that are not valid XML names are escaped as shown
9868      for <function>xmlelement</function> above.  Similarly, content
9869      data is escaped to make valid XML content, unless it is already
9870      of type <type>xml</type>.
9871     </para>
9872
9873     <para>
9874      Note that XML forests are not valid XML documents if they consist
9875      of more than one element, so it might be useful to wrap
9876      <function>xmlforest</function> expressions in
9877      <function>xmlelement</function>.
9878     </para>
9879    </sect3>
9880
9881    <sect3>
9882     <title><literal>xmlpi</literal></title>
9883
9884    <indexterm>
9885     <primary>xmlpi</primary>
9886    </indexterm>
9887
9888 <synopsis>
9889 <function>xmlpi</function>(name <replaceable>target</replaceable> <optional>, <replaceable>content</replaceable></optional>)
9890 </synopsis>
9891
9892     <para>
9893      The <function>xmlpi</function> expression creates an XML
9894      processing instruction.  The content, if present, must not
9895      contain the character sequence <literal>?&gt;</literal>.
9896     </para>
9897
9898     <para>
9899      Example:
9900 <screen><![CDATA[
9901 SELECT xmlpi(name php, 'echo "hello world";');
9902
9903             xmlpi
9904 -----------------------------
9905  <?php echo "hello world";?>
9906 ]]></screen>
9907     </para>
9908    </sect3>
9909
9910    <sect3>
9911     <title><literal>xmlroot</literal></title>
9912
9913    <indexterm>
9914     <primary>xmlroot</primary>
9915    </indexterm>
9916
9917 <synopsis>
9918 <function>xmlroot</function>(<replaceable>xml</replaceable>, version <replaceable>text</replaceable> | no value <optional>, standalone yes|no|no value</optional>)
9919 </synopsis>
9920
9921     <para>
9922      The <function>xmlroot</function> expression alters the properties
9923      of the root node of an XML value.  If a version is specified,
9924      it replaces the value in the root node's version declaration; if a
9925      standalone setting is specified, it replaces the value in the
9926      root node's standalone declaration.
9927     </para>
9928
9929     <para>
9930 <screen><![CDATA[
9931 SELECT xmlroot(xmlparse(document '<?xml version="1.1"?><content>abc</content>'),
9932                version '1.0', standalone yes);
9933
9934                 xmlroot
9935 ----------------------------------------
9936  <?xml version="1.0" standalone="yes"?>
9937  <content>abc</content>
9938 ]]></screen>
9939     </para>
9940    </sect3>
9941
9942    <sect3 id="functions-xml-xmlagg">
9943     <title><literal>xmlagg</literal></title>
9944
9945     <indexterm>
9946      <primary>xmlagg</primary>
9947     </indexterm>
9948
9949 <synopsis>
9950 <function>xmlagg</function>(<replaceable>xml</replaceable>)
9951 </synopsis>
9952
9953     <para>
9954      The function <function>xmlagg</function> is, unlike the other
9955      functions described here, an aggregate function.  It concatenates the
9956      input values to the aggregate function call,
9957      much like <function>xmlconcat</function> does, except that concatenation
9958      occurs across rows rather than across expressions in a single row.
9959      See <xref linkend="functions-aggregate"> for additional information
9960      about aggregate functions.
9961     </para>
9962
9963     <para>
9964      Example:
9965 <screen><![CDATA[
9966 CREATE TABLE test (y int, x xml);
9967 INSERT INTO test VALUES (1, '<foo>abc</foo>');
9968 INSERT INTO test VALUES (2, '<bar/>');
9969 SELECT xmlagg(x) FROM test;
9970         xmlagg
9971 ----------------------
9972  <foo>abc</foo><bar/>
9973 ]]></screen>
9974     </para>
9975
9976     <para>
9977      To determine the order of the concatenation, an <literal>ORDER BY</>
9978      clause may be added to the aggregate call as described in
9979      <xref linkend="syntax-aggregates">. For example:
9980
9981 <screen><![CDATA[
9982 SELECT xmlagg(x ORDER BY y DESC) FROM test;
9983         xmlagg
9984 ----------------------
9985  <bar/><foo>abc</foo>
9986 ]]></screen>
9987     </para>
9988
9989     <para>
9990      The following non-standard approach used to be recommended
9991      in previous versions, and may still be useful in specific
9992      cases:
9993
9994 <screen><![CDATA[
9995 SELECT xmlagg(x) FROM (SELECT * FROM test ORDER BY y DESC) AS tab;
9996         xmlagg
9997 ----------------------
9998  <bar/><foo>abc</foo>
9999 ]]></screen>
10000     </para>
10001    </sect3>
10002    </sect2>
10003
10004    <sect2 id="functions-xml-predicates">
10005     <title>XML Predicates</title>
10006
10007     <para>
10008      The expressions described in this section check properties
10009      of <type>xml</type> values.
10010     </para>
10011
10012    <sect3>
10013     <title><literal>IS DOCUMENT</literal></title>
10014
10015     <indexterm>
10016      <primary>IS DOCUMENT</primary>
10017     </indexterm>
10018
10019 <synopsis>
10020 <replaceable>xml</replaceable> IS DOCUMENT
10021 </synopsis>
10022
10023     <para>
10024      The expression <literal>IS DOCUMENT</literal> returns true if the
10025      argument XML value is a proper XML document, false if it is not
10026      (that is, it is a content fragment), or null if the argument is
10027      null.  See <xref linkend="datatype-xml"> about the difference
10028      between documents and content fragments.
10029     </para>
10030    </sect3>
10031
10032    <sect3 id="xml-exists">
10033     <title><literal>XMLEXISTS</literal></title>
10034
10035     <indexterm>
10036      <primary>XMLEXISTS</primary>
10037     </indexterm>
10038
10039 <synopsis>
10040 <function>XMLEXISTS</function>(<replaceable>text</replaceable> PASSING <optional>BY REF</optional> <replaceable>xml</replaceable> <optional>BY REF</optional>)
10041 </synopsis>
10042
10043     <para>
10044      The function <function>xmlexists</function> returns true if the
10045      XPath expression in the first argument returns any nodes, and
10046      false otherwise.  (If either argument is null, the result is
10047      null.)
10048     </para>
10049
10050     <para>
10051      Example:
10052      <screen><![CDATA[
10053 SELECT xmlexists('//town[text() = ''Toronto'']' PASSING BY REF '<towns><town>Toronto</town><town>Ottawa</town></towns>');
10054
10055  xmlexists
10056 ------------
10057  t
10058 (1 row)
10059 ]]></screen>
10060     </para>
10061
10062     <para>
10063      The <literal>BY REF</literal> clauses have no effect in
10064      PostgreSQL, but are allowed for SQL conformance and compatibility
10065      with other implementations.  Per SQL standard, the
10066      first <literal>BY REF</literal> is required, the second is
10067      optional.  Also note that the SQL standard specifies
10068      the <function>xmlexists</function> construct to take an XQuery
10069      expression as first argument, but PostgreSQL currently only
10070      supports XPath, which is a subset of XQuery.
10071     </para>
10072    </sect3>
10073
10074    <sect3 id="xml-is-well-formed">
10075     <title><literal>xml_is_well_formed</literal></title>
10076
10077     <indexterm>
10078      <primary>xml_is_well_formed</primary>
10079     </indexterm>
10080
10081     <indexterm>
10082      <primary>xml_is_well_formed_document</primary>
10083     </indexterm>
10084
10085     <indexterm>
10086      <primary>xml_is_well_formed_content</primary>
10087     </indexterm>
10088
10089 <synopsis>
10090 <function>xml_is_well_formed</function>(<replaceable>text</replaceable>)
10091 <function>xml_is_well_formed_document</function>(<replaceable>text</replaceable>)
10092 <function>xml_is_well_formed_content</function>(<replaceable>text</replaceable>)
10093 </synopsis>
10094
10095     <para>
10096      These functions check whether a <type>text</> string is well-formed XML,
10097      returning a Boolean result.
10098      <function>xml_is_well_formed_document</function> checks for a well-formed
10099      document, while <function>xml_is_well_formed_content</function> checks
10100      for well-formed content.  <function>xml_is_well_formed</function> does
10101      the former if the <xref linkend="guc-xmloption"> configuration
10102      parameter is set to <literal>DOCUMENT</>, or the latter if it is set to
10103      <literal>CONTENT</>.  This means that
10104      <function>xml_is_well_formed</function> is useful for seeing whether
10105      a simple cast to type <type>xml</> will succeed, whereas the other two
10106      functions are useful for seeing whether the corresponding variants of
10107      <function>XMLPARSE</> will succeed.
10108     </para>
10109
10110     <para>
10111      Examples:
10112
10113 <screen><![CDATA[
10114 SET xmloption TO DOCUMENT;
10115 SELECT xml_is_well_formed('<>');
10116  xml_is_well_formed 
10117 --------------------
10118  f
10119 (1 row)
10120
10121 SELECT xml_is_well_formed('<abc/>');
10122  xml_is_well_formed 
10123 --------------------
10124  t
10125 (1 row)
10126
10127 SET xmloption TO CONTENT;
10128 SELECT xml_is_well_formed('abc');
10129  xml_is_well_formed 
10130 --------------------
10131  t
10132 (1 row)
10133
10134 SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</pg:foo>');
10135  xml_is_well_formed_document 
10136 -----------------------------
10137  t
10138 (1 row)
10139
10140 SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</my:foo>');
10141  xml_is_well_formed_document 
10142 -----------------------------
10143  f
10144 (1 row)
10145 ]]></screen>
10146
10147      The last example shows that the checks include whether
10148      namespaces are correctly matched.
10149     </para>
10150    </sect3>
10151   </sect2>
10152
10153   <sect2 id="functions-xml-processing">
10154    <title>Processing XML</title>
10155
10156    <indexterm>
10157     <primary>XPath</primary>
10158    </indexterm>
10159
10160    <para>
10161     To process values of data type <type>xml</type>, PostgreSQL offers
10162     the functions <function>xpath</function> and
10163     <function>xpath_exists</function>, which evaluate XPath 1.0
10164     expressions.
10165    </para>
10166
10167 <synopsis>
10168 <function>xpath</function>(<replaceable>xpath</replaceable>, <replaceable>xml</replaceable> <optional>, <replaceable>nsarray</replaceable></optional>)
10169 </synopsis>
10170
10171    <para>
10172     The function <function>xpath</function> evaluates the XPath
10173     expression <replaceable>xpath</replaceable> (a <type>text</> value)
10174     against the XML value
10175     <replaceable>xml</replaceable>.  It returns an array of XML values
10176     corresponding to the node set produced by the XPath expression.
10177     If the XPath expression returns a scalar value rather than a node set,
10178     a single-element array is returned.
10179    </para>
10180
10181   <para>
10182     The second argument must be a well formed XML document. In particular,
10183     it must have a single root node element.
10184   </para>
10185
10186    <para>
10187     The optional third argument of the function is an array of namespace
10188     mappings.  This array should be a two-dimensional <type>text</> array with
10189     the length of the second axis being equal to 2 (i.e., it should be an
10190     array of arrays, each of which consists of exactly 2 elements).
10191     The first element of each array entry is the namespace name (alias), the
10192     second the namespace URI. It is not required that aliases provided in
10193     this array be the same as those being used in the XML document itself (in
10194     other words, both in the XML document and in the <function>xpath</function>
10195     function context, aliases are <emphasis>local</>).
10196    </para>
10197
10198    <para>
10199     Example:
10200 <screen><![CDATA[
10201 SELECT xpath('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
10202              ARRAY[ARRAY['my', 'http://example.com']]);
10203
10204  xpath  
10205 --------
10206  {test}
10207 (1 row)
10208 ]]></screen>
10209    </para>
10210
10211    <para>
10212     To deal with default (anonymous) namespaces, do something like this:
10213 <screen><![CDATA[
10214 SELECT xpath('//mydefns:b/text()', '<a xmlns="http://example.com"><b>test</b></a>',
10215              ARRAY[ARRAY['mydefns', 'http://example.com']]);
10216
10217  xpath
10218 --------
10219  {test}
10220 (1 row)
10221 ]]></screen>
10222    </para>
10223
10224    <indexterm>
10225     <primary>xpath_exists</primary>
10226    </indexterm>
10227
10228 <synopsis>
10229 <function>xpath_exists</function>(<replaceable>xpath</replaceable>, <replaceable>xml</replaceable> <optional>, <replaceable>nsarray</replaceable></optional>)
10230 </synopsis>
10231
10232    <para>
10233     The function <function>xpath_exists</function> is a specialized form
10234     of the <function>xpath</function> function.  Instead of returning the
10235     individual XML values that satisfy the XPath, this function returns a
10236     Boolean indicating whether the query was satisfied or not.  This
10237     function is equivalent to the standard <literal>XMLEXISTS</> predicate,
10238     except that it also offers support for a namespace mapping argument.
10239    </para>
10240
10241    <para>
10242     Example:
10243 <screen><![CDATA[
10244 SELECT xpath_exists('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
10245                      ARRAY[ARRAY['my', 'http://example.com']]);
10246
10247  xpath_exists  
10248 --------------
10249  t
10250 (1 row)
10251 ]]></screen>
10252    </para>
10253   </sect2>
10254
10255   <sect2 id="functions-xml-mapping">
10256    <title>Mapping Tables to XML</title>
10257
10258    <indexterm zone="functions-xml-mapping">
10259     <primary>XML export</primary>
10260    </indexterm>
10261
10262    <para>
10263     The following functions map the contents of relational tables to
10264     XML values.  They can be thought of as XML export functionality:
10265 <synopsis>
10266 table_to_xml(tbl regclass, nulls boolean, tableforest boolean, targetns text)
10267 query_to_xml(query text, nulls boolean, tableforest boolean, targetns text)
10268 cursor_to_xml(cursor refcursor, count int, nulls boolean,
10269               tableforest boolean, targetns text)
10270 </synopsis>
10271     The return type of each function is <type>xml</type>.
10272    </para>
10273
10274    <para>
10275     <function>table_to_xml</function> maps the content of the named
10276     table, passed as parameter <parameter>tbl</parameter>.  The
10277     <type>regclass</type> type accepts strings identifying tables using the
10278     usual notation, including optional schema qualifications and
10279     double quotes.  <function>query_to_xml</function> executes the
10280     query whose text is passed as parameter
10281     <parameter>query</parameter> and maps the result set.
10282     <function>cursor_to_xml</function> fetches the indicated number of
10283     rows from the cursor specified by the parameter
10284     <parameter>cursor</parameter>.  This variant is recommended if
10285     large tables have to be mapped, because the result value is built
10286     up in memory by each function.
10287    </para>
10288
10289    <para>
10290     If <parameter>tableforest</parameter> is false, then the resulting
10291     XML document looks like this:
10292 <screen><![CDATA[
10293 <tablename>
10294   <row>
10295     <columnname1>data</columnname1>
10296     <columnname2>data</columnname2>
10297   </row>
10298
10299   <row>
10300     ...
10301   </row>
10302
10303   ...
10304 </tablename>
10305 ]]></screen>
10306
10307     If <parameter>tableforest</parameter> is true, the result is an
10308     XML content fragment that looks like this:
10309 <screen><![CDATA[
10310 <tablename>
10311   <columnname1>data</columnname1>
10312   <columnname2>data</columnname2>
10313 </tablename>
10314
10315 <tablename>
10316   ...
10317 </tablename>
10318
10319 ...
10320 ]]></screen>
10321
10322     If no table name is available, that is, when mapping a query or a
10323     cursor, the string <literal>table</literal> is used in the first
10324     format, <literal>row</literal> in the second format.
10325    </para>
10326
10327    <para>
10328     The choice between these formats is up to the user.  The first
10329     format is a proper XML document, which will be important in many
10330     applications.  The second format tends to be more useful in the
10331     <function>cursor_to_xml</function> function if the result values are to be
10332     reassembled into one document later on.  The functions for
10333     producing XML content discussed above, in particular
10334     <function>xmlelement</function>, can be used to alter the results
10335     to taste.
10336    </para>
10337
10338    <para>
10339     The data values are mapped in the same way as described for the
10340     function <function>xmlelement</function> above.
10341    </para>
10342
10343    <para>
10344     The parameter <parameter>nulls</parameter> determines whether null
10345     values should be included in the output.  If true, null values in
10346     columns are represented as:
10347 <screen><![CDATA[
10348 <columnname xsi:nil="true"/>
10349 ]]></screen>
10350     where <literal>xsi</literal> is the XML namespace prefix for XML
10351     Schema Instance.  An appropriate namespace declaration will be
10352     added to the result value.  If false, columns containing null
10353     values are simply omitted from the output.
10354    </para>
10355
10356    <para>
10357     The parameter <parameter>targetns</parameter> specifies the
10358     desired XML namespace of the result.  If no particular namespace
10359     is wanted, an empty string should be passed.
10360    </para>
10361
10362    <para>
10363     The following functions return XML Schema documents describing the
10364     mappings performed by the corresponding functions above:
10365 <synopsis>
10366 table_to_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text)
10367 query_to_xmlschema(query text, nulls boolean, tableforest boolean, targetns text)
10368 cursor_to_xmlschema(cursor refcursor, nulls boolean, tableforest boolean, targetns text)
10369 </synopsis>
10370     It is essential that the same parameters are passed in order to
10371     obtain matching XML data mappings and XML Schema documents.
10372    </para>
10373
10374    <para>
10375     The following functions produce XML data mappings and the
10376     corresponding XML Schema in one document (or forest), linked
10377     together.  They can be useful where self-contained and
10378     self-describing results are wanted:
10379 <synopsis>
10380 table_to_xml_and_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text)
10381 query_to_xml_and_xmlschema(query text, nulls boolean, tableforest boolean, targetns text)
10382 </synopsis>
10383    </para>
10384
10385    <para>
10386     In addition, the following functions are available to produce
10387     analogous mappings of entire schemas or the entire current
10388     database:
10389 <synopsis>
10390 schema_to_xml(schema name, nulls boolean, tableforest boolean, targetns text)
10391 schema_to_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text)
10392 schema_to_xml_and_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text)
10393
10394 database_to_xml(nulls boolean, tableforest boolean, targetns text)
10395 database_to_xmlschema(nulls boolean, tableforest boolean, targetns text)
10396 database_to_xml_and_xmlschema(nulls boolean, tableforest boolean, targetns text)
10397 </synopsis>
10398
10399     Note that these potentially produce a lot of data, which needs to
10400     be built up in memory.  When requesting content mappings of large
10401     schemas or databases, it might be worthwhile to consider mapping the
10402     tables separately instead, possibly even through a cursor.
10403    </para>
10404
10405    <para>
10406     The result of a schema content mapping looks like this:
10407
10408 <screen><![CDATA[
10409 <schemaname>
10410
10411 table1-mapping
10412
10413 table2-mapping
10414
10415 ...
10416
10417 </schemaname>]]></screen>
10418
10419     where the format of a table mapping depends on the
10420     <parameter>tableforest</parameter> parameter as explained above.
10421    </para>
10422
10423    <para>
10424     The result of a database content mapping looks like this:
10425
10426 <screen><![CDATA[
10427 <dbname>
10428
10429 <schema1name>
10430   ...
10431 </schema1name>
10432
10433 <schema2name>
10434   ...
10435 </schema2name>
10436
10437 ...
10438
10439 </dbname>]]></screen>
10440
10441     where the schema mapping is as above.
10442    </para>
10443
10444    <para>
10445     As an example of using the output produced by these functions,
10446     <xref linkend="xslt-xml-html"> shows an XSLT stylesheet that
10447     converts the output of
10448     <function>table_to_xml_and_xmlschema</function> to an HTML
10449     document containing a tabular rendition of the table data.  In a
10450     similar manner, the results from these functions can be
10451     converted into other XML-based formats.
10452    </para>
10453
10454    <figure id="xslt-xml-html">
10455     <title>XSLT Stylesheet for Converting SQL/XML Output to HTML</title>
10456 <programlisting><![CDATA[
10457 <?xml version="1.0"?>
10458 <xsl:stylesheet version="1.0"
10459     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
10460     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
10461     xmlns="http://www.w3.org/1999/xhtml"
10462 >
10463
10464   <xsl:output method="xml"
10465       doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
10466       doctype-public="-//W3C/DTD XHTML 1.0 Strict//EN"
10467       indent="yes"/>
10468
10469   <xsl:template match="/*">
10470     <xsl:variable name="schema" select="//xsd:schema"/>
10471     <xsl:variable name="tabletypename"
10472                   select="$schema/xsd:element[@name=name(current())]/@type"/>
10473     <xsl:variable name="rowtypename"
10474                   select="$schema/xsd:complexType[@name=$tabletypename]/xsd:sequence/xsd:element[@name='row']/@type"/>
10475
10476     <html>
10477       <head>
10478         <title><xsl:value-of select="name(current())"/></title>
10479       </head>
10480       <body>
10481         <table>
10482           <tr>
10483             <xsl:for-each select="$schema/xsd:complexType[@name=$rowtypename]/xsd:sequence/xsd:element/@name">
10484               <th><xsl:value-of select="."/></th>
10485             </xsl:for-each>
10486           </tr>
10487
10488           <xsl:for-each select="row">
10489             <tr>
10490               <xsl:for-each select="*">
10491                 <td><xsl:value-of select="."/></td>
10492               </xsl:for-each>
10493             </tr>
10494           </xsl:for-each>
10495         </table>
10496       </body>
10497     </html>
10498   </xsl:template>
10499
10500 </xsl:stylesheet>
10501 ]]></programlisting>
10502    </figure>
10503   </sect2>
10504  </sect1>
10505
10506  <sect1 id="functions-json">
10507   <title>JSON Functions and Operators</title>
10508
10509   <indexterm zone="functions-json">
10510     <primary>JSON</primary>
10511     <secondary>functions and operators</secondary>
10512   </indexterm>
10513
10514    <para>
10515    <xref linkend="functions-json-op-table"> shows the operators that
10516    are available for use with the two JSON data types (see <xref
10517    linkend="datatype-json">).
10518   </para>
10519
10520   <table id="functions-json-op-table">
10521      <title><type>json</> and <type>jsonb</> Operators</title>
10522      <tgroup cols="5">
10523       <thead>
10524        <row>
10525         <entry>Operator</entry>
10526         <entry>Right Operand Type</entry>
10527         <entry>Description</entry>
10528         <entry>Example</entry>
10529         <entry>Example Result</entry>
10530        </row>
10531       </thead>
10532       <tbody>
10533        <row>
10534         <entry><literal>-&gt;</literal></entry>
10535         <entry><type>int</type></entry>
10536         <entry>Get JSON array element (indexed from zero, negative
10537         integers count from the end)</entry>
10538         <entry><literal>'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json-&gt;2</literal></entry>
10539         <entry><literal>{"c":"baz"}</literal></entry>
10540        </row>
10541        <row>
10542         <entry><literal>-&gt;</literal></entry>
10543         <entry><type>text</type></entry>
10544         <entry>Get JSON object field by key</entry>
10545         <entry><literal>'{"a": {"b":"foo"}}'::json-&gt;'a'</literal></entry>
10546         <entry><literal>{"b":"foo"}</literal></entry>
10547        </row>
10548         <row>
10549         <entry><literal>-&gt;&gt;</literal></entry>
10550         <entry><type>int</type></entry>
10551         <entry>Get JSON array element as <type>text</></entry>
10552         <entry><literal>'[1,2,3]'::json-&gt;&gt;2</literal></entry>
10553         <entry><literal>3</literal></entry>
10554        </row>
10555        <row>
10556         <entry><literal>-&gt;&gt;</literal></entry>
10557         <entry><type>text</type></entry>
10558         <entry>Get JSON object field as <type>text</></entry>
10559         <entry><literal>'{"a":1,"b":2}'::json-&gt;&gt;'b'</literal></entry>
10560         <entry><literal>2</literal></entry>
10561        </row>
10562        <row>
10563         <entry><literal>#&gt;</literal></entry>
10564         <entry><type>text[]</type></entry>
10565         <entry>Get JSON object at specified path</entry>
10566         <entry><literal>'{"a": {"b":{"c": "foo"}}}'::json#&gt;'{a,b}'</literal></entry>
10567         <entry><literal>{"c": "foo"}</literal></entry>
10568        </row>
10569        <row>
10570         <entry><literal>#&gt;&gt;</literal></entry>
10571         <entry><type>text[]</type></entry>
10572         <entry>Get JSON object at specified path as <type>text</></entry>
10573         <entry><literal>'{"a":[1,2,3],"b":[4,5,6]}'::json#&gt;&gt;'{a,2}'</literal></entry>
10574         <entry><literal>3</literal></entry>
10575        </row>
10576       </tbody>
10577      </tgroup>
10578    </table>
10579
10580   <note>
10581    <para>
10582     There are parallel variants of these operators for both the
10583     <type>json</type> and <type>jsonb</type> types.
10584     The field/element/path extraction operators
10585     return the same type as their left-hand input (either <type>json</type>
10586     or <type>jsonb</type>), except for those specified as
10587     returning <type>text</>, which coerce the value to text.
10588     The field/element/path extraction operators return NULL, rather than
10589     failing, if the JSON input does not have the right structure to match
10590     the request; for example if no such element exists.  The
10591     field/element/path extraction operators that accept integer JSON
10592     array subscripts all support negative subscripting from the end of
10593     arrays.
10594    </para>
10595   </note>
10596   <para>
10597    The standard comparison operators shown in  <xref
10598    linkend="functions-comparison-op-table"> are available for
10599    <type>jsonb</type>, but not for <type>json</type>. They follow the
10600    ordering rules for B-tree operations outlined at <xref
10601    linkend="json-indexing">.
10602   </para>
10603   <para>
10604    Some further operators also exist only for <type>jsonb</type>, as shown
10605    in <xref linkend="functions-jsonb-op-table">.
10606    Many of these operators can be indexed by
10607    <type>jsonb</> operator classes.  For a full description of
10608    <type>jsonb</> containment and existence semantics, see <xref
10609    linkend="json-containment">.  <xref linkend="json-indexing">
10610    describes how these operators can be used to effectively index
10611    <type>jsonb</> data.
10612   </para>
10613   <table id="functions-jsonb-op-table">
10614      <title>Additional <type>jsonb</> Operators</title>
10615      <tgroup cols="4">
10616       <thead>
10617        <row>
10618         <entry>Operator</entry>
10619         <entry>Right Operand Type</entry>
10620         <entry>Description</entry>
10621         <entry>Example</entry>
10622        </row>
10623       </thead>
10624       <tbody>
10625        <row>
10626         <entry><literal>@&gt;</literal></entry>
10627         <entry><type>jsonb</type></entry>
10628         <entry>Does the left JSON value contain the right JSON
10629         path/value entries at the top level?</entry>
10630         <entry><literal>'{"a":1, "b":2}'::jsonb &#64;&gt; '{"b":2}'::jsonb</literal></entry>
10631        </row>
10632        <row>
10633         <entry><literal>&lt;@</literal></entry>
10634         <entry><type>jsonb</type></entry>
10635         <entry>Are the left JSON path/value entries contained at the top level within
10636         the right JSON value?</entry>
10637         <entry><literal>'{"b":2}'::jsonb &lt;@ '{"a":1, "b":2}'::jsonb</literal></entry>
10638        </row>
10639        <row>
10640         <entry><literal>?</literal></entry>
10641         <entry><type>text</type></entry>
10642         <entry>Does the <emphasis>string</emphasis> exist as a top-level
10643         key within the JSON value?</entry>
10644         <entry><literal>'{"a":1, "b":2}'::jsonb ? 'b'</literal></entry>
10645        </row>
10646        <row>
10647         <entry><literal>?|</literal></entry>
10648         <entry><type>text[]</type></entry>
10649         <entry>Do any of these array <emphasis>strings</emphasis>
10650         exist as top-level keys?</entry>
10651         <entry><literal>'{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']</literal></entry>
10652        </row>
10653        <row>
10654         <entry><literal>?&amp;</literal></entry>
10655         <entry><type>text[]</type></entry>
10656         <entry>Do all of these array <emphasis>strings</emphasis> exist
10657         as top-level keys?</entry>
10658         <entry><literal>'["a", "b"]'::jsonb ?&amp; array['a', 'b']</literal></entry>
10659        </row>
10660        <row>
10661         <entry><literal>||</literal></entry>
10662         <entry><type>jsonb</type></entry>
10663         <entry>Concatenate two <type>jsonb</type> values into a new <type>jsonb</type> value</entry>
10664         <entry><literal>'["a", "b"]'::jsonb || '["c", "d"]'::jsonb</literal></entry>
10665        </row>
10666        <row>
10667         <entry><literal>-</literal></entry>
10668         <entry><type>text</type></entry>
10669         <entry>Delete key/value pair or <emphasis>string</emphasis>
10670         element from left operand.  Key/value pairs are matched based
10671         on their key value.</entry>
10672         <entry><literal>'{"a": "b"}'::jsonb - 'a' </literal></entry>
10673        </row>
10674        <row>
10675         <entry><literal>-</literal></entry>
10676         <entry><type>integer</type></entry>
10677         <entry>Delete the array element with specified index (Negative
10678         integers count from the end).  Throws an error if top level
10679         container is not an array.</entry>
10680         <entry><literal>'["a", "b"]'::jsonb - 1 </literal></entry>
10681        </row>
10682        <row>
10683         <entry><literal>#-</literal></entry>
10684         <entry><type>text[]</type></entry>
10685         <entry>Delete the field or element with specified path (for
10686         JSON arrays, negative integers count from the end)</entry>
10687         <entry><literal>'["a", {"b":1}]'::jsonb #- '{1,b}'</literal></entry>
10688        </row>
10689       </tbody>
10690      </tgroup>
10691    </table>
10692
10693   <note>
10694    <para>
10695     The <literal>||</> operator concatenates the elements at the top level of
10696     each of its operands. It does not operate recursively. For example, if
10697     both operands are objects with a common key field name, the value of the
10698     field in the result will just be the value from the right hand operand.
10699    </para>
10700   </note>
10701
10702   <para>
10703    <xref linkend="functions-json-creation-table"> shows the functions that are
10704    available for creating <type>json</type> and <type>jsonb</type> values.
10705    (There are no equivalent functions for <type>jsonb</>, of the <literal>row_to_json</>
10706    and <literal>array_to_json</> functions. However, the <literal>to_jsonb</>
10707    function supplies much the same functionality as these functions would.)
10708   </para>
10709
10710   <indexterm>
10711    <primary>to_json</primary>
10712   </indexterm>
10713   <indexterm>
10714    <primary>array_to_json</primary>
10715   </indexterm>
10716   <indexterm>
10717    <primary>row_to_json</primary>
10718   </indexterm>
10719   <indexterm>
10720    <primary>json_build_array</primary>
10721   </indexterm>
10722   <indexterm>
10723    <primary>json_build_object</primary>
10724   </indexterm>
10725   <indexterm>
10726    <primary>json_object</primary>
10727   </indexterm>
10728   <indexterm>
10729    <primary>to_jsonb</primary>
10730   </indexterm>
10731   <indexterm>
10732    <primary>jsonb_build_array</primary>
10733   </indexterm>
10734   <indexterm>
10735    <primary>jsonb_build_object</primary>
10736   </indexterm>
10737   <indexterm>
10738    <primary>jsonb_object</primary>
10739   </indexterm>
10740
10741   <table id="functions-json-creation-table">
10742     <title>JSON Creation Functions</title>
10743     <tgroup cols="4">
10744      <thead>
10745       <row>
10746        <entry>Function</entry>
10747        <entry>Description</entry>
10748        <entry>Example</entry>
10749        <entry>Example Result</entry>
10750       </row>
10751      </thead>
10752      <tbody>
10753       <row>
10754        <entry><para><literal>to_json(anyelement)</literal>
10755           </para><para><literal>to_jsonb(anyelement)</literal>
10756        </para></entry>
10757        <entry>
10758          Returns the value as <type>json</> or <type>jsonb</>.
10759          Arrays and composites are converted
10760          (recursively) to arrays and objects; otherwise, if there is a cast
10761          from the type to <type>json</type>, the cast function will be used to
10762          perform the conversion; otherwise, a scalar value is produced.
10763          For any scalar type other than a number, a Boolean, or a null value,
10764          the text representation will be used, in such a fashion that it is a
10765          valid <type>json</> or <type>jsonb</> value.
10766        </entry>
10767        <entry><literal>to_json('Fred said "Hi."'::text)</literal></entry>
10768        <entry><literal>"Fred said \"Hi.\""</literal></entry>
10769       </row>
10770       <row>
10771        <entry>
10772          <literal>array_to_json(anyarray [, pretty_bool])</literal>
10773        </entry>
10774        <entry>
10775          Returns the array as a JSON array. A PostgreSQL multidimensional array
10776          becomes a JSON array of arrays. Line feeds will be added between
10777          dimension-1 elements if <parameter>pretty_bool</parameter> is true.
10778        </entry>
10779        <entry><literal>array_to_json('{{1,5},{99,100}}'::int[])</literal></entry>
10780        <entry><literal>[[1,5],[99,100]]</literal></entry>
10781       </row>
10782       <row>
10783        <entry>
10784          <literal>row_to_json(record [, pretty_bool])</literal>
10785        </entry>
10786        <entry>
10787          Returns the row as a JSON object. Line feeds will be added between
10788          level-1 elements if <parameter>pretty_bool</parameter> is true.
10789        </entry>
10790        <entry><literal>row_to_json(row(1,'foo'))</literal></entry>
10791        <entry><literal>{"f1":1,"f2":"foo"}</literal></entry>
10792       </row>
10793       <row>
10794        <entry><para><literal>json_build_array(VARIADIC "any")</literal>
10795           </para><para><literal>jsonb_build_array(VARIADIC "any")</literal>
10796        </para></entry>
10797        <entry>
10798          Builds a possibly-heterogeneously-typed JSON array out of a variadic
10799          argument list.
10800        </entry>
10801        <entry><literal>json_build_array(1,2,'3',4,5)</literal></entry>
10802        <entry><literal>[1, 2, "3", 4, 5]</literal></entry>
10803       </row>
10804       <row>
10805        <entry><para><literal>json_build_object(VARIADIC "any")</literal>
10806           </para><para><literal>jsonb_build_object(VARIADIC "any")</literal>
10807        </para></entry>
10808        <entry>
10809          Builds a JSON object out of a variadic argument list.  By
10810          convention, the argument list consists of alternating
10811          keys and values.
10812        </entry>
10813        <entry><literal>json_build_object('foo',1,'bar',2)</literal></entry>
10814        <entry><literal>{"foo": 1, "bar": 2}</literal></entry>
10815       </row>
10816       <row>
10817        <entry><para><literal>json_object(text[])</literal>
10818           </para><para><literal>jsonb_object(text[])</literal>
10819        </para></entry>
10820        <entry>
10821          Builds a JSON object out of a text array.  The array must have either
10822          exactly one dimension with an even number of members, in which case
10823          they are taken as alternating key/value pairs, or two dimensions
10824          such that each inner array has exactly two elements, which
10825          are taken as a key/value pair.
10826        </entry>
10827        <entry><para><literal>json_object('{a, 1, b, "def", c, 3.5}')</></para>
10828         <para><literal>json_object('{{a, 1},{b, "def"},{c, 3.5}}')</></para></entry>
10829        <entry><literal>{"a": "1", "b": "def", "c": "3.5"}</literal></entry>
10830       </row>
10831       <row>
10832        <entry><para><literal>json_object(keys text[], values text[])</literal>
10833           </para><para><literal>jsonb_object(keys text[], values text[])</literal>
10834        </para></entry>
10835        <entry>
10836          This form of <function>json_object</> takes keys and values pairwise from two separate
10837          arrays. In all other respects it is identical to the one-argument form.
10838        </entry>
10839        <entry><literal>json_object('{a, b}', '{1,2}')</literal></entry>
10840        <entry><literal>{"a": "1", "b": "2"}</literal></entry>
10841       </row>
10842      </tbody>
10843     </tgroup>
10844    </table>
10845
10846   <note>
10847     <para>
10848      <function>array_to_json</> and <function>row_to_json</> have the same
10849      behavior as <function>to_json</> except for offering a pretty-printing
10850      option.  The behavior described for <function>to_json</> likewise applies
10851      to each individual value converted by the other JSON creation functions.
10852     </para>
10853   </note>
10854
10855   <note>
10856     <para>
10857      The <xref linkend="hstore"> extension has a cast
10858      from <type>hstore</type> to <type>json</type>, so that
10859      <type>hstore</type> values converted via the JSON creation functions
10860      will be represented as JSON objects, not as primitive string values.
10861     </para>
10862   </note>
10863
10864   <para>
10865    <xref linkend="functions-json-processing-table"> shows the functions that
10866    are available for processing <type>json</type> and <type>jsonb</type> values.
10867   </para>
10868
10869   <indexterm>
10870    <primary>json_array_length</primary>
10871   </indexterm>
10872   <indexterm>
10873    <primary>jsonb_array_length</primary>
10874   </indexterm>
10875   <indexterm>
10876    <primary>json_each</primary>
10877   </indexterm>
10878   <indexterm>
10879    <primary>jsonb_each</primary>
10880   </indexterm>
10881   <indexterm>
10882    <primary>json_each_text</primary>
10883   </indexterm>
10884   <indexterm>
10885    <primary>jsonb_each_text</primary>
10886   </indexterm>
10887   <indexterm>
10888    <primary>json_extract_path</primary>
10889   </indexterm>
10890   <indexterm>
10891    <primary>jsonb_extract_path</primary>
10892   </indexterm>
10893   <indexterm>
10894    <primary>json_extract_path_text</primary>
10895   </indexterm>
10896   <indexterm>
10897    <primary>jsonb_extract_path_text</primary>
10898   </indexterm>
10899   <indexterm>
10900    <primary>json_object_keys</primary>
10901   </indexterm>
10902   <indexterm>
10903    <primary>jsonb_object_keys</primary>
10904   </indexterm>
10905   <indexterm>
10906    <primary>json_populate_record</primary>
10907   </indexterm>
10908   <indexterm>
10909    <primary>jsonb_populate_record</primary>
10910   </indexterm>
10911   <indexterm>
10912    <primary>json_populate_recordset</primary>
10913   </indexterm>
10914   <indexterm>
10915    <primary>jsonb_populate_recordset</primary>
10916   </indexterm>
10917   <indexterm>
10918    <primary>json_array_elements</primary>
10919   </indexterm>
10920   <indexterm>
10921    <primary>jsonb_array_elements</primary>
10922   </indexterm>
10923   <indexterm>
10924    <primary>json_array_elements_text</primary>
10925   </indexterm>
10926   <indexterm>
10927    <primary>jsonb_array_elements_text</primary>
10928   </indexterm>
10929   <indexterm>
10930    <primary>json_typeof</primary>
10931   </indexterm>
10932   <indexterm>
10933    <primary>jsonb_typeof</primary>
10934   </indexterm>
10935   <indexterm>
10936    <primary>json_to_record</primary>
10937   </indexterm>
10938   <indexterm>
10939    <primary>jsonb_to_record</primary>
10940   </indexterm>
10941   <indexterm>
10942    <primary>json_to_recordset</primary>
10943   </indexterm>
10944   <indexterm>
10945    <primary>jsonb_to_recordset</primary>
10946   </indexterm>
10947   <indexterm>
10948    <primary>json_strip_nulls</primary>
10949   </indexterm>
10950   <indexterm>
10951    <primary>jsonb_strip_nulls</primary>
10952   </indexterm>
10953   <indexterm>
10954    <primary>jsonb_set</primary>
10955   </indexterm>
10956   <indexterm>
10957    <primary>jsonb_insert</primary>
10958   </indexterm>
10959   <indexterm>
10960    <primary>jsonb_pretty</primary>
10961   </indexterm>
10962
10963   <table id="functions-json-processing-table">
10964     <title>JSON Processing Functions</title>
10965     <tgroup cols="5">
10966      <thead>
10967       <row>
10968        <entry>Function</entry>
10969        <entry>Return Type</entry>
10970        <entry>Description</entry>
10971        <entry>Example</entry>
10972        <entry>Example Result</entry>
10973       </row>
10974      </thead>
10975      <tbody>
10976       <row>
10977        <entry><para><literal>json_array_length(json)</literal>
10978          </para><para><literal>jsonb_array_length(jsonb)</literal>
10979        </para></entry>
10980        <entry><type>int</type></entry>
10981        <entry>
10982          Returns the number of elements in the outermost JSON array.
10983        </entry>
10984        <entry><literal>json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]')</literal></entry>
10985        <entry><literal>5</literal></entry>
10986       </row>
10987       <row>
10988        <entry><para><literal>json_each(json)</literal>
10989          </para><para><literal>jsonb_each(jsonb)</literal>
10990        </para></entry>
10991        <entry><para><literal>setof key text, value json</literal>
10992          </para><para><literal>setof key text, value jsonb</literal>
10993        </para></entry>
10994        <entry>
10995          Expands the outermost JSON object into a set of key/value pairs.
10996        </entry>
10997        <entry><literal>select * from json_each('{"a":"foo", "b":"bar"}')</literal></entry>
10998        <entry>
10999 <programlisting>
11000  key | value
11001 -----+-------
11002  a   | "foo"
11003  b   | "bar"
11004 </programlisting>
11005        </entry>
11006       </row>
11007       <row>
11008        <entry><para><literal>json_each_text(json)</literal>
11009          </para><para><literal>jsonb_each_text(jsonb)</literal>
11010        </para></entry>
11011        <entry><type>setof key text, value text</type></entry>
11012        <entry>
11013          Expands the outermost JSON object into a set of key/value pairs. The
11014          returned values will be of type <type>text</>.
11015        </entry>
11016        <entry><literal>select * from json_each_text('{"a":"foo", "b":"bar"}')</literal></entry>
11017        <entry>
11018 <programlisting>
11019  key | value
11020 -----+-------
11021  a   | foo
11022  b   | bar
11023 </programlisting>
11024        </entry>
11025       </row>
11026       <row>
11027        <entry><para><literal>json_extract_path(from_json json, VARIADIC path_elems text[])</literal>
11028         </para><para><literal>jsonb_extract_path(from_json jsonb, VARIADIC path_elems text[])</literal>
11029        </para></entry>
11030        <entry><para><type>json</type></para><para><type>jsonb</type>
11031        </para></entry>
11032        <entry>
11033          Returns JSON value pointed to by <replaceable>path_elems</replaceable>
11034          (equivalent to <literal>#&gt;</literal> operator).
11035        </entry>
11036        <entry><literal>json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4')</literal></entry>
11037        <entry><literal>{"f5":99,"f6":"foo"}</literal></entry>
11038       </row>
11039       <row>
11040        <entry><para><literal>json_extract_path_text(from_json json, VARIADIC path_elems text[])</literal>
11041          </para><para><literal>jsonb_extract_path_text(from_json jsonb, VARIADIC path_elems text[])</literal>
11042        </para></entry>
11043        <entry><type>text</type></entry>
11044        <entry>
11045          Returns JSON value pointed to by <replaceable>path_elems</replaceable>
11046          as <type>text</>
11047          (equivalent to <literal>#&gt;&gt;</literal> operator).
11048        </entry>
11049        <entry><literal>json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4', 'f6')</literal></entry>
11050        <entry><literal>foo</literal></entry>
11051       </row>
11052       <row>
11053        <entry><para><literal>json_object_keys(json)</literal>
11054          </para><para><literal>jsonb_object_keys(jsonb)</literal>
11055        </para></entry>
11056        <entry><type>setof text</type></entry>
11057        <entry>
11058           Returns set of keys in the outermost JSON object.
11059        </entry>
11060        <entry><literal>json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')</literal></entry>
11061        <entry>
11062 <programlisting>
11063  json_object_keys
11064 ------------------
11065  f1
11066  f2
11067 </programlisting>
11068        </entry>
11069       </row>
11070       <row>
11071        <entry><para><literal>json_populate_record(base anyelement, from_json json)</literal>
11072          </para><para><literal>jsonb_populate_record(base anyelement, from_json jsonb)</literal>
11073        </para></entry>
11074        <entry><type>anyelement</type></entry>
11075        <entry>
11076          Expands the object in <replaceable>from_json</replaceable> to a row
11077          whose columns match the record type defined by <replaceable>base</>
11078          (see note below).
11079        </entry>
11080        <entry><literal>select * from json_populate_record(null::myrowtype, '{"a":1,"b":2}')</literal></entry>
11081        <entry>
11082 <programlisting>
11083  a | b
11084 ---+---
11085  1 | 2
11086 </programlisting>
11087        </entry>
11088       </row>
11089       <row>
11090        <entry><para><literal>json_populate_recordset(base anyelement, from_json json)</literal>
11091          </para><para><literal>jsonb_populate_recordset(base anyelement, from_json jsonb)</literal>
11092        </para></entry>
11093        <entry><type>setof anyelement</type></entry>
11094        <entry>
11095          Expands the outermost array of objects
11096          in <replaceable>from_json</replaceable> to a set of rows whose
11097          columns match the record type defined by <replaceable>base</> (see
11098          note below).
11099        </entry>
11100        <entry><literal>select * from json_populate_recordset(null::myrowtype, '[{"a":1,"b":2},{"a":3,"b":4}]')</literal></entry>
11101        <entry>
11102 <programlisting>
11103  a | b
11104 ---+---
11105  1 | 2
11106  3 | 4
11107 </programlisting>
11108        </entry>
11109       </row>
11110       <row>
11111        <entry><para><literal>json_array_elements(json)</literal>
11112          </para><para><literal>jsonb_array_elements(jsonb)</literal>
11113        </para></entry>
11114        <entry><para><type>setof json</type>
11115          </para><para><type>setof jsonb</type>
11116        </para></entry>
11117        <entry>
11118          Expands a JSON array to a set of JSON values.
11119        </entry>
11120        <entry><literal>select * from json_array_elements('[1,true, [2,false]]')</literal></entry>
11121        <entry>
11122 <programlisting>
11123    value
11124 -----------
11125  1
11126  true
11127  [2,false]
11128 </programlisting>
11129        </entry>
11130       </row>
11131       <row>
11132        <entry><para><literal>json_array_elements_text(json)</literal>
11133          </para><para><literal>jsonb_array_elements_text(jsonb)</literal>
11134        </para></entry>
11135        <entry><type>setof text</type></entry>
11136        <entry>
11137          Expands a JSON array to a set of <type>text</> values.
11138        </entry>
11139        <entry><literal>select * from json_array_elements_text('["foo", "bar"]')</literal></entry>
11140        <entry>
11141 <programlisting>
11142    value
11143 -----------
11144  foo
11145  bar
11146 </programlisting>
11147        </entry>
11148       </row>
11149       <row>
11150        <entry><para><literal>json_typeof(json)</literal>
11151          </para><para><literal>jsonb_typeof(jsonb)</literal>
11152        </para></entry>
11153        <entry><type>text</type></entry>
11154        <entry>
11155          Returns the type of the outermost JSON value as a text string.
11156          Possible types are
11157          <literal>object</>, <literal>array</>, <literal>string</>, <literal>number</>,
11158          <literal>boolean</>, and <literal>null</>.
11159        </entry>
11160        <entry><literal>json_typeof('-123.4')</literal></entry>
11161        <entry><literal>number</literal></entry>
11162       </row>
11163       <row>
11164        <entry><para><literal>json_to_record(json)</literal>
11165           </para><para><literal>jsonb_to_record(jsonb)</literal>
11166        </para></entry>
11167        <entry><type>record</type></entry>
11168        <entry>
11169          Builds an arbitrary record from a JSON object (see note below).  As
11170          with all functions returning <type>record</>, the caller must
11171          explicitly define the structure of the record with an <literal>AS</>
11172          clause.
11173        </entry>
11174        <entry><literal>select * from json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}') as x(a int, b text, d text) </literal></entry>
11175        <entry>
11176 <programlisting>
11177  a |    b    | d
11178 ---+---------+---
11179  1 | [1,2,3] |
11180 </programlisting>
11181        </entry>
11182       </row>
11183       <row>
11184        <entry><para><literal>json_to_recordset(json)</literal>
11185          </para><para><literal>jsonb_to_recordset(jsonb)</literal>
11186        </para></entry>
11187        <entry><type>setof record</type></entry>
11188        <entry>
11189          Builds an arbitrary set of records from a JSON array of objects (see
11190          note below).  As with all functions returning <type>record</>, the
11191          caller must explicitly define the structure of the record with
11192          an <literal>AS</> clause.
11193        </entry>
11194        <entry><literal>select * from json_to_recordset('[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]') as x(a int, b text);</literal></entry>
11195        <entry>
11196 <programlisting>
11197  a |  b
11198 ---+-----
11199  1 | foo
11200  2 |
11201 </programlisting>
11202        </entry>
11203       </row>
11204       <row>
11205        <entry><para><literal>json_strip_nulls(from_json json)</literal>
11206          </para><para><literal>jsonb_strip_nulls(from_json jsonb)</literal>
11207        </para></entry>
11208        <entry><para><type>json</type></para><para><type>jsonb</type></para></entry>
11209        <entry>
11210          Returns <replaceable>from_json</replaceable>
11211          with all object fields that have null values omitted. Other null values
11212          are untouched.
11213        </entry>
11214        <entry><literal>json_strip_nulls('[{"f1":1,"f2":null},2,null,3]')</literal></entry>
11215        <entry><literal>[{"f1":1},2,null,3]</literal></entry>
11216        </row>
11217       <row>
11218        <entry><para><literal>jsonb_set(target jsonb, path text[], new_value jsonb<optional>, <parameter>create_missing</parameter> <type>boolean</type></optional>)</literal>
11219          </para></entry>
11220        <entry><para><type>jsonb</type></para></entry>
11221        <entry>
11222          Returns <replaceable>target</replaceable>
11223          with the section designated by <replaceable>path</replaceable>
11224          replaced by <replaceable>new_value</replaceable>, or with
11225          <replaceable>new_value</replaceable> added if
11226          <replaceable>create_missing</replaceable> is true ( default is
11227          <literal>true</>) and the item
11228          designated by <replaceable>path</replaceable> does not exist.
11229          As with the path orientated operators, negative integers that
11230          appear in <replaceable>path</replaceable> count from the end
11231          of JSON arrays.
11232        </entry>
11233        <entry><para><literal>jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}','[2,3,4]', false)</literal>
11234          </para><para><literal>jsonb_set('[{"f1":1,"f2":null},2]', '{0,f3}','[2,3,4]')</literal>
11235          </para></entry>
11236        <entry><para><literal>[{"f1":[2,3,4],"f2":null},2,null,3]</literal>
11237          </para><para><literal>[{"f1": 1, "f2": null, "f3": [2, 3, 4]}, 2]</literal>
11238         </para></entry>
11239        </row>
11240       <row>
11241        <entry>
11242            <para><literal>
11243            jsonb_insert(target jsonb, path text[], new_value jsonb, <optional><parameter>insert_after</parameter> <type>boolean</type></optional>)
11244            </literal></para>
11245        </entry>
11246        <entry><para><type>jsonb</type></para></entry>
11247        <entry>
11248          Returns <replaceable>target</replaceable> with
11249          <replaceable>new_value</replaceable> inserted. If
11250          <replaceable>target</replaceable> section designated by
11251          <replaceable>path</replaceable> is in a JSONB array,
11252          <replaceable>new_value</replaceable> will be inserted before target or
11253          after if <replaceable>insert_after</replaceable> is true (default is
11254          <literal>false</>). If <replaceable>target</replaceable> section
11255          designated by <replaceable>path</replaceable> is in JSONB object,
11256          <replaceable>new_value</replaceable> will be inserted only if
11257          <replaceable>target</replaceable> does not exist. As with the path
11258          orientated operators, negative integers that appear in
11259          <replaceable>path</replaceable> count from the end of JSON arrays.
11260        </entry>
11261        <entry>
11262            <para><literal>
11263                jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"')
11264            </literal></para>
11265            <para><literal>
11266                jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"', true)
11267            </literal></para>
11268        </entry>
11269        <entry><para><literal>{"a": [0, "new_value", 1, 2]}</literal>
11270          </para><para><literal>{"a": [0, 1, "new_value", 2]}</literal>
11271         </para></entry>
11272        </row>
11273       <row>
11274        <entry><para><literal>jsonb_pretty(from_json jsonb)</literal>
11275          </para></entry>
11276        <entry><para><type>text</type></para></entry>
11277        <entry>
11278          Returns <replaceable>from_json</replaceable>
11279          as indented JSON text.
11280        </entry>
11281        <entry><literal>jsonb_pretty('[{"f1":1,"f2":null},2,null,3]')</literal></entry>
11282        <entry>
11283 <programlisting>
11284 [
11285     {
11286         "f1": 1,
11287         "f2": null
11288     },
11289     2,
11290     null,
11291     3
11292 ]
11293 </programlisting>
11294         </entry>
11295        </row>
11296      </tbody>
11297     </tgroup>
11298    </table>
11299
11300   <note>
11301     <para>
11302       Many of these functions and operators will convert Unicode escapes in
11303       JSON strings to the appropriate single character.  This is a non-issue
11304       if the input is type <type>jsonb</>, because the conversion was already
11305       done; but for <type>json</> input, this may result in throwing an error,
11306       as noted in <xref linkend="datatype-json">.
11307     </para>
11308   </note>
11309
11310   <note>
11311     <para>
11312       In <function>json_populate_record</>, <function>json_populate_recordset</>,
11313       <function>json_to_record</> and <function>json_to_recordset</>,
11314       type coercion from the JSON is <quote>best effort</> and may not result
11315       in desired values for some types.  JSON keys are matched to
11316       identical column names in the target row type.  JSON fields that do not
11317       appear in the target row type will be omitted from the output, and
11318       target columns that do not match any JSON field will simply be NULL.
11319     </para>
11320   </note>
11321
11322   <note>
11323     <para>
11324       All the items of the <literal>path</> parameter of <literal>jsonb_set</>
11325       as well as <literal>jsonb_insert</> except the last item must be present
11326       in the <literal>target</>. If <literal>create_missing</> is false, all
11327       items of the <literal>path</> parameter of <literal>jsonb_set</> must be
11328       present. If these conditions are not met the <literal>target</> is
11329       returned unchanged.
11330     </para>
11331     <para>
11332       If the last path item is an object key, it will be created if it
11333       is absent and given the new value. If the last path item is an array
11334       index, if it is positive the item to set is found by counting from
11335       the left, and if negative by counting from the right - <literal>-1</>
11336       designates the rightmost element, and so on.
11337       If the item is out of the range -array_length .. array_length -1,
11338       and create_missing is true, the new value is added at the beginning
11339       of the array if the item is negative, and at the end of the array if
11340       it is positive.
11341     </para>
11342   </note>
11343
11344   <note>
11345     <para>
11346       The <literal>json_typeof</> function's <literal>null</> return value
11347       should not be confused with a SQL NULL.  While
11348       calling <literal>json_typeof('null'::json)</> will
11349       return <literal>null</>, calling <literal>json_typeof(NULL::json)</>
11350       will return a SQL NULL.
11351     </para>
11352   </note>
11353
11354   <note>
11355     <para>
11356       If the argument to <literal>json_strip_nulls</> contains duplicate
11357       field names in any object, the result could be semantically somewhat
11358       different, depending on the order in which they occur. This is not an
11359       issue for <literal>jsonb_strip_nulls</> since <type>jsonb</type> values never have
11360       duplicate object field names.
11361     </para>
11362   </note>
11363
11364   <para>
11365     See also <xref linkend="functions-aggregate"> for the aggregate
11366     function <function>json_agg</function> which aggregates record
11367     values as JSON, and the aggregate function
11368     <function>json_object_agg</function> which aggregates pairs of values
11369     into a JSON object, and their <type>jsonb</type> equivalents,
11370     <function>jsonb_agg</> and <function>jsonb_object_agg</>.
11371   </para>
11372
11373  </sect1>
11374
11375  <sect1 id="functions-sequence">
11376   <title>Sequence Manipulation Functions</title>
11377
11378   <indexterm>
11379    <primary>sequence</primary>
11380   </indexterm>
11381   <indexterm>
11382    <primary>nextval</primary>
11383   </indexterm>
11384   <indexterm>
11385    <primary>currval</primary>
11386   </indexterm>
11387   <indexterm>
11388    <primary>lastval</primary>
11389   </indexterm>
11390   <indexterm>
11391    <primary>setval</primary>
11392   </indexterm>
11393
11394   <para>
11395    This section describes functions for operating on <firstterm>sequence
11396    objects</firstterm>, also called sequence generators or just sequences.
11397    Sequence objects are special single-row tables created with <xref
11398    linkend="sql-createsequence">.
11399    Sequence objects are commonly used to generate unique identifiers
11400    for rows of a table.  The sequence functions, listed in <xref
11401    linkend="functions-sequence-table">, provide simple, multiuser-safe
11402    methods for obtaining successive sequence values from sequence
11403    objects.
11404   </para>
11405
11406    <table id="functions-sequence-table">
11407     <title>Sequence Functions</title>
11408     <tgroup cols="3">
11409      <thead>
11410       <row><entry>Function</entry> <entry>Return Type</entry> <entry>Description</entry></row>
11411      </thead>
11412
11413      <tbody>
11414       <row>
11415         <entry><literal><function>currval(<type>regclass</type>)</function></literal></entry>
11416         <entry><type>bigint</type></entry>
11417         <entry>Return value most recently obtained with
11418         <function>nextval</function> for specified sequence</entry>
11419       </row>
11420       <row>
11421         <entry><literal><function>lastval()</function></literal></entry>
11422         <entry><type>bigint</type></entry>
11423         <entry>Return value most recently obtained with
11424         <function>nextval</function> for any sequence</entry>
11425       </row>
11426       <row>
11427         <entry><literal><function>nextval(<type>regclass</type>)</function></literal></entry>
11428         <entry><type>bigint</type></entry>
11429         <entry>Advance sequence and return new value</entry>
11430       </row>
11431       <row>
11432         <entry><literal><function>setval(<type>regclass</type>, <type>bigint</type>)</function></literal></entry>
11433         <entry><type>bigint</type></entry>
11434         <entry>Set sequence's current value</entry>
11435       </row>
11436       <row>
11437         <entry><literal><function>setval(<type>regclass</type>, <type>bigint</type>, <type>boolean</type>)</function></literal></entry>
11438         <entry><type>bigint</type></entry>
11439         <entry>Set sequence's current value and <literal>is_called</literal> flag</entry>
11440       </row>
11441      </tbody>
11442     </tgroup>
11443    </table>
11444
11445   <para>
11446    The sequence to be operated on by a sequence function is specified by
11447    a <type>regclass</> argument, which is simply the OID of the sequence in the
11448    <structname>pg_class</> system catalog.  You do not have to look up the
11449    OID by hand, however, since the <type>regclass</> data type's input
11450    converter will do the work for you.  Just write the sequence name enclosed
11451    in single quotes so that it looks like a literal constant.  For
11452    compatibility with the handling of ordinary
11453    <acronym>SQL</acronym> names, the string will be converted to lower case
11454    unless it contains double quotes around the sequence name.  Thus:
11455 <programlisting>
11456 nextval('foo')      <lineannotation>operates on sequence <literal>foo</literal></>
11457 nextval('FOO')      <lineannotation>operates on sequence <literal>foo</literal></>
11458 nextval('"Foo"')    <lineannotation>operates on sequence <literal>Foo</literal></>
11459 </programlisting>
11460    The sequence name can be schema-qualified if necessary:
11461 <programlisting>
11462 nextval('myschema.foo')     <lineannotation>operates on <literal>myschema.foo</literal></>
11463 nextval('"myschema".foo')   <lineannotation>same as above</lineannotation>
11464 nextval('foo')              <lineannotation>searches search path for <literal>foo</literal></>
11465 </programlisting>
11466    See <xref linkend="datatype-oid"> for more information about
11467    <type>regclass</>.
11468   </para>
11469
11470   <note>
11471    <para>
11472     Before <productname>PostgreSQL</productname> 8.1, the arguments of the
11473     sequence functions were of type <type>text</>, not <type>regclass</>, and
11474     the above-described conversion from a text string to an OID value would
11475     happen at run time during each call.  For backward compatibility, this
11476     facility still exists, but internally it is now handled as an implicit
11477     coercion from <type>text</> to <type>regclass</> before the function is
11478     invoked.
11479    </para>
11480
11481    <para>
11482     When you write the argument of a sequence function as an unadorned
11483     literal string, it becomes a constant of type <type>regclass</>.
11484     Since this is really just an OID, it will track the originally
11485     identified sequence despite later renaming, schema reassignment,
11486     etc.  This <quote>early binding</> behavior is usually desirable for
11487     sequence references in column defaults and views.  But sometimes you might
11488     want <quote>late binding</> where the sequence reference is resolved
11489     at run time.  To get late-binding behavior, force the constant to be
11490     stored as a <type>text</> constant instead of <type>regclass</>:
11491 <programlisting>
11492 nextval('foo'::text)      <lineannotation><literal>foo</literal> is looked up at runtime</>
11493 </programlisting>
11494     Note that late binding was the only behavior supported in
11495     <productname>PostgreSQL</productname> releases before 8.1, so you
11496     might need to do this to preserve the semantics of old applications.
11497    </para>
11498
11499    <para>
11500     Of course, the argument of a sequence function can be an expression
11501     as well as a constant.  If it is a text expression then the implicit
11502     coercion will result in a run-time lookup.
11503    </para>
11504   </note>
11505
11506   <para>
11507    The available sequence functions are:
11508
11509     <variablelist>
11510      <varlistentry>
11511       <term><function>nextval</function></term>
11512       <listitem>
11513        <para>
11514         Advance the sequence object to its next value and return that
11515         value.  This is done atomically: even if multiple sessions
11516         execute <function>nextval</function> concurrently, each will safely receive
11517         a distinct sequence value.
11518        </para>
11519
11520        <para>
11521         If a sequence object has been created with default parameters,
11522         successive <function>nextval</function> calls will return successive
11523         values beginning with 1.  Other behaviors can be obtained by using
11524         special parameters in the <xref linkend="sql-createsequence"> command;
11525         see its command reference page for more information.
11526        </para>
11527
11528        <important>
11529         <para>
11530          To avoid blocking concurrent transactions that obtain numbers from
11531          the same sequence, a <function>nextval</function> operation is never
11532          rolled back; that is, once a value has been fetched it is considered
11533          used and will not be returned again.  This is true even if the
11534          surrounding transaction later aborts, or if the calling query ends
11535          up not using the value.  For example an <command>INSERT</> with
11536          an <literal>ON CONFLICT</> clause will compute the to-be-inserted
11537          tuple, including doing any required <function>nextval</function>
11538          calls, before detecting any conflict that would cause it to follow
11539          the <literal>ON CONFLICT</> rule instead.  Such cases will leave
11540          unused <quote>holes</quote> in the sequence of assigned values.
11541          Thus, <productname>PostgreSQL</> sequence objects <emphasis>cannot
11542          be used to obtain <quote>gapless</> sequences</emphasis>.
11543         </para>
11544        </important>
11545
11546       </listitem>
11547      </varlistentry>
11548
11549      <varlistentry>
11550       <term><function>currval</function></term>
11551       <listitem>
11552        <para>
11553         Return the value most recently obtained by <function>nextval</function>
11554         for this sequence in the current session.  (An error is
11555         reported if <function>nextval</function> has never been called for this
11556         sequence in this session.)  Because this is returning
11557         a session-local value, it gives a predictable answer whether or not
11558         other sessions have executed <function>nextval</function> since the
11559         current session did.
11560        </para>
11561       </listitem>
11562      </varlistentry>
11563
11564      <varlistentry>
11565       <term><function>lastval</function></term>
11566       <listitem>
11567        <para>
11568         Return the value most recently returned by
11569         <function>nextval</> in the current session. This function is
11570         identical to <function>currval</function>, except that instead
11571         of taking the sequence name as an argument it refers to whichever
11572         sequence <function>nextval</function> was most recently applied to
11573         in the current session. It is an error to call
11574         <function>lastval</function> if <function>nextval</function>
11575         has not yet been called in the current session.
11576        </para>
11577       </listitem>
11578      </varlistentry>
11579
11580      <varlistentry>
11581       <term><function>setval</function></term>
11582       <listitem>
11583        <para>
11584         Reset the sequence object's counter value.  The two-parameter
11585         form sets the sequence's <literal>last_value</literal> field to the
11586         specified value and sets its <literal>is_called</literal> field to
11587         <literal>true</literal>, meaning that the next
11588         <function>nextval</function> will advance the sequence before
11589         returning a value.  The value reported by <function>currval</> is
11590         also set to the specified value.  In the three-parameter form,
11591         <literal>is_called</literal> can be set to either <literal>true</literal>
11592         or <literal>false</literal>.  <literal>true</> has the same effect as
11593         the two-parameter form. If it is set to <literal>false</literal>, the
11594         next <function>nextval</function> will return exactly the specified
11595         value, and sequence advancement commences with the following
11596         <function>nextval</function>.  Furthermore, the value reported by
11597         <function>currval</> is not changed in this case.  For example,
11598
11599 <screen>
11600 SELECT setval('foo', 42);           <lineannotation>Next <function>nextval</> will return 43</lineannotation>
11601 SELECT setval('foo', 42, true);     <lineannotation>Same as above</lineannotation>
11602 SELECT setval('foo', 42, false);    <lineannotation>Next <function>nextval</> will return 42</lineannotation>
11603 </screen>
11604
11605         The result returned by <function>setval</function> is just the value of its
11606         second argument.
11607        </para>
11608        <important>
11609         <para>
11610          Because sequences are non-transactional, changes made by
11611          <function>setval</function> are not undone if the transaction rolls
11612          back.
11613         </para>
11614        </important>
11615       </listitem>
11616      </varlistentry>
11617     </variablelist>
11618   </para>
11619
11620  </sect1>
11621
11622
11623  <sect1 id="functions-conditional">
11624   <title>Conditional Expressions</title>
11625
11626   <indexterm>
11627    <primary>CASE</primary>
11628   </indexterm>
11629
11630   <indexterm>
11631    <primary>conditional expression</primary>
11632   </indexterm>
11633
11634   <para>
11635    This section describes the <acronym>SQL</acronym>-compliant conditional expressions
11636    available in <productname>PostgreSQL</productname>.
11637   </para>
11638
11639   <tip>
11640    <para>
11641     If your needs go beyond the capabilities of these conditional
11642     expressions, you might want to consider writing a stored procedure
11643     in a more expressive programming language.
11644    </para>
11645   </tip>
11646
11647   <sect2 id="functions-case">
11648    <title><literal>CASE</></title>
11649
11650   <para>
11651    The <acronym>SQL</acronym> <token>CASE</token> expression is a
11652    generic conditional expression, similar to if/else statements in
11653    other programming languages:
11654
11655 <synopsis>
11656 CASE WHEN <replaceable>condition</replaceable> THEN <replaceable>result</replaceable>
11657      <optional>WHEN ...</optional>
11658      <optional>ELSE <replaceable>result</replaceable></optional>
11659 END
11660 </synopsis>
11661
11662    <token>CASE</token> clauses can be used wherever
11663    an expression is valid.  Each <replaceable>condition</replaceable> is an
11664    expression that returns a <type>boolean</type> result.  If the condition's
11665    result is true, the value of the <token>CASE</token> expression is the
11666    <replaceable>result</replaceable> that follows the condition, and the
11667    remainder of the <token>CASE</token> expression is not processed.  If the
11668    condition's result is not true, any subsequent <token>WHEN</token> clauses
11669    are examined in the same manner.  If no <token>WHEN</token>
11670    <replaceable>condition</replaceable> yields true, the value of the
11671    <token>CASE</> expression is the <replaceable>result</replaceable> of the
11672    <token>ELSE</token> clause.  If the <token>ELSE</token> clause is
11673    omitted and no condition is true, the result is null.
11674   </para>
11675
11676    <para>
11677     An example:
11678 <screen>
11679 SELECT * FROM test;
11680
11681  a
11682 ---
11683  1
11684  2
11685  3
11686
11687
11688 SELECT a,
11689        CASE WHEN a=1 THEN 'one'
11690             WHEN a=2 THEN 'two'
11691             ELSE 'other'
11692        END
11693     FROM test;
11694
11695  a | case
11696 ---+-------
11697  1 | one
11698  2 | two
11699  3 | other
11700 </screen>
11701    </para>
11702
11703   <para>
11704    The data types of all the <replaceable>result</replaceable>
11705    expressions must be convertible to a single output type.
11706    See <xref linkend="typeconv-union-case"> for more details.
11707   </para>
11708
11709   <para>
11710    There is a <quote>simple</> form of <token>CASE</token> expression
11711    that is a variant of the general form above:
11712
11713 <synopsis>
11714 CASE <replaceable>expression</replaceable>
11715     WHEN <replaceable>value</replaceable> THEN <replaceable>result</replaceable>
11716     <optional>WHEN ...</optional>
11717     <optional>ELSE <replaceable>result</replaceable></optional>
11718 END
11719 </synopsis>
11720
11721    The first
11722    <replaceable>expression</replaceable> is computed, then compared to
11723    each of the <replaceable>value</replaceable> expressions in the
11724    <token>WHEN</token> clauses until one is found that is equal to it.  If
11725    no match is found, the <replaceable>result</replaceable> of the
11726    <token>ELSE</token> clause (or a null value) is returned.  This is similar
11727    to the <function>switch</function> statement in C.
11728   </para>
11729
11730    <para>
11731     The example above can be written using the simple
11732     <token>CASE</token> syntax:
11733 <screen>
11734 SELECT a,
11735        CASE a WHEN 1 THEN 'one'
11736               WHEN 2 THEN 'two'
11737               ELSE 'other'
11738        END
11739     FROM test;
11740
11741  a | case
11742 ---+-------
11743  1 | one
11744  2 | two
11745  3 | other
11746 </screen>
11747    </para>
11748
11749    <para>
11750     A <token>CASE</token> expression does not evaluate any subexpressions
11751     that are not needed to determine the result.  For example, this is a
11752     possible way of avoiding a division-by-zero failure:
11753 <programlisting>
11754 SELECT ... WHERE CASE WHEN x &lt;&gt; 0 THEN y/x &gt; 1.5 ELSE false END;
11755 </programlisting>
11756    </para>
11757
11758    <note>
11759     <para>
11760      As described in <xref linkend="syntax-express-eval">, there are various
11761      situations in which subexpressions of an expression are evaluated at
11762      different times, so that the principle that <quote><token>CASE</token>
11763      evaluates only necessary subexpressions</quote> is not ironclad.  For
11764      example a constant <literal>1/0</> subexpression will usually result in
11765      a division-by-zero failure at planning time, even if it's within
11766      a <token>CASE</token> arm that would never be entered at run time.
11767     </para>
11768    </note>
11769   </sect2>
11770
11771   <sect2 id="functions-coalesce-nvl-ifnull">
11772    <title><literal>COALESCE</></title>
11773
11774   <indexterm>
11775    <primary>COALESCE</primary>
11776   </indexterm>
11777
11778   <indexterm>
11779    <primary>NVL</primary>
11780   </indexterm>
11781
11782   <indexterm>
11783    <primary>IFNULL</primary>
11784   </indexterm>
11785
11786 <synopsis>
11787 <function>COALESCE</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
11788 </synopsis>
11789
11790   <para>
11791    The <function>COALESCE</function> function returns the first of its
11792    arguments that is not null.  Null is returned only if all arguments
11793    are null.  It is often used to substitute a default value for
11794    null values when data is retrieved for display, for example:
11795 <programlisting>
11796 SELECT COALESCE(description, short_description, '(none)') ...
11797 </programlisting>
11798    This returns <varname>description</> if it is not null, otherwise
11799    <varname>short_description</> if it is not null, otherwise <literal>(none)</>.
11800   </para>
11801
11802    <para>
11803     Like a <token>CASE</token> expression, <function>COALESCE</function> only
11804     evaluates the arguments that are needed to determine the result;
11805     that is, arguments to the right of the first non-null argument are
11806     not evaluated.  This SQL-standard function provides capabilities similar
11807     to <function>NVL</> and <function>IFNULL</>, which are used in some other
11808     database systems.
11809    </para>
11810   </sect2>
11811
11812   <sect2 id="functions-nullif">
11813    <title><literal>NULLIF</></title>
11814
11815   <indexterm>
11816    <primary>NULLIF</primary>
11817   </indexterm>
11818
11819 <synopsis>
11820 <function>NULLIF</function>(<replaceable>value1</replaceable>, <replaceable>value2</replaceable>)
11821 </synopsis>
11822
11823   <para>
11824    The <function>NULLIF</function> function returns a null value if
11825    <replaceable>value1</replaceable> equals <replaceable>value2</replaceable>;
11826    otherwise it returns <replaceable>value1</replaceable>.
11827    This can be used to perform the inverse operation of the
11828    <function>COALESCE</function> example given above:
11829 <programlisting>
11830 SELECT NULLIF(value, '(none)') ...
11831 </programlisting>
11832   </para>
11833   <para>
11834    In this example, if <literal>value</literal> is <literal>(none)</>,
11835    null is returned, otherwise the value of <literal>value</literal>
11836    is returned.
11837   </para>
11838
11839   </sect2>
11840
11841   <sect2 id="functions-greatest-least">
11842    <title><literal>GREATEST</literal> and <literal>LEAST</literal></title>
11843
11844   <indexterm>
11845    <primary>GREATEST</primary>
11846   </indexterm>
11847   <indexterm>
11848    <primary>LEAST</primary>
11849   </indexterm>
11850
11851 <synopsis>
11852 <function>GREATEST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
11853 </synopsis>
11854 <synopsis>
11855 <function>LEAST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
11856 </synopsis>
11857
11858    <para>
11859     The <function>GREATEST</> and <function>LEAST</> functions select the
11860     largest or smallest value from a list of any number of expressions.
11861     The expressions must all be convertible to a common data type, which
11862     will be the type of the result
11863     (see <xref linkend="typeconv-union-case"> for details).  NULL values
11864     in the list are ignored.  The result will be NULL only if all the
11865     expressions evaluate to NULL.
11866    </para>
11867
11868    <para>
11869     Note that <function>GREATEST</> and <function>LEAST</> are not in
11870     the SQL standard, but are a common extension.  Some other databases
11871     make them return NULL if any argument is NULL, rather than only when
11872     all are NULL.
11873    </para>
11874   </sect2>
11875  </sect1>
11876
11877  <sect1 id="functions-array">
11878   <title>Array Functions and Operators</title>
11879
11880   <para>
11881    <xref linkend="array-operators-table"> shows the operators
11882    available for array types.
11883   </para>
11884
11885     <table id="array-operators-table">
11886      <title>Array Operators</title>
11887      <tgroup cols="4">
11888       <thead>
11889        <row>
11890         <entry>Operator</entry>
11891         <entry>Description</entry>
11892         <entry>Example</entry>
11893         <entry>Result</entry>
11894        </row>
11895       </thead>
11896       <tbody>
11897        <row>
11898         <entry> <literal>=</literal> </entry>
11899         <entry>equal</entry>
11900         <entry><literal>ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3]</literal></entry>
11901         <entry><literal>t</literal></entry>
11902        </row>
11903
11904        <row>
11905         <entry> <literal>&lt;&gt;</literal> </entry>
11906         <entry>not equal</entry>
11907         <entry><literal>ARRAY[1,2,3] &lt;&gt; ARRAY[1,2,4]</literal></entry>
11908         <entry><literal>t</literal></entry>
11909        </row>
11910
11911        <row>
11912         <entry> <literal>&lt;</literal> </entry>
11913         <entry>less than</entry>
11914         <entry><literal>ARRAY[1,2,3] &lt; ARRAY[1,2,4]</literal></entry>
11915         <entry><literal>t</literal></entry>
11916        </row>
11917
11918        <row>
11919         <entry> <literal>&gt;</literal> </entry>
11920         <entry>greater than</entry>
11921         <entry><literal>ARRAY[1,4,3] &gt; ARRAY[1,2,4]</literal></entry>
11922         <entry><literal>t</literal></entry>
11923        </row>
11924
11925        <row>
11926         <entry> <literal>&lt;=</literal> </entry>
11927         <entry>less than or equal</entry>
11928         <entry><literal>ARRAY[1,2,3] &lt;= ARRAY[1,2,3]</literal></entry>
11929         <entry><literal>t</literal></entry>
11930        </row>
11931
11932        <row>
11933         <entry> <literal>&gt;=</literal> </entry>
11934         <entry>greater than or equal</entry>
11935         <entry><literal>ARRAY[1,4,3] &gt;= ARRAY[1,4,3]</literal></entry>
11936         <entry><literal>t</literal></entry>
11937        </row>
11938
11939        <row>
11940         <entry> <literal>@&gt;</literal> </entry>
11941         <entry>contains</entry>
11942         <entry><literal>ARRAY[1,4,3] @&gt; ARRAY[3,1]</literal></entry>
11943         <entry><literal>t</literal></entry>
11944        </row>
11945
11946        <row>
11947         <entry> <literal>&lt;@</literal> </entry>
11948         <entry>is contained by</entry>
11949         <entry><literal>ARRAY[2,7] &lt;@ ARRAY[1,7,4,2,6]</literal></entry>
11950         <entry><literal>t</literal></entry>
11951        </row>
11952
11953        <row>
11954         <entry> <literal>&amp;&amp;</literal> </entry>
11955         <entry>overlap (have elements in common)</entry>
11956         <entry><literal>ARRAY[1,4,3] &amp;&amp; ARRAY[2,1]</literal></entry>
11957         <entry><literal>t</literal></entry>
11958        </row>
11959
11960        <row>
11961         <entry> <literal>||</literal> </entry>
11962         <entry>array-to-array concatenation</entry>
11963         <entry><literal>ARRAY[1,2,3] || ARRAY[4,5,6]</literal></entry>
11964         <entry><literal>{1,2,3,4,5,6}</literal></entry>
11965        </row>
11966
11967        <row>
11968         <entry> <literal>||</literal> </entry>
11969         <entry>array-to-array concatenation</entry>
11970         <entry><literal>ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9]]</literal></entry>
11971         <entry><literal>{{1,2,3},{4,5,6},{7,8,9}}</literal></entry>
11972        </row>
11973
11974        <row>
11975         <entry> <literal>||</literal> </entry>
11976         <entry>element-to-array concatenation</entry>
11977         <entry><literal>3 || ARRAY[4,5,6]</literal></entry>
11978         <entry><literal>{3,4,5,6}</literal></entry>
11979        </row>
11980
11981        <row>
11982         <entry> <literal>||</literal> </entry>
11983         <entry>array-to-element concatenation</entry>
11984         <entry><literal>ARRAY[4,5,6] || 7</literal></entry>
11985         <entry><literal>{4,5,6,7}</literal></entry>
11986        </row>
11987       </tbody>
11988      </tgroup>
11989     </table>
11990
11991   <para>
11992    Array comparisons compare the array contents element-by-element,
11993    using the default B-tree comparison function for the element data type.
11994    In multidimensional arrays the elements are visited in row-major order
11995    (last subscript varies most rapidly).
11996    If the contents of two arrays are equal but the dimensionality is
11997    different, the first difference in the dimensionality information
11998    determines the sort order.  (This is a change from versions of
11999    <productname>PostgreSQL</> prior to 8.2: older versions would claim
12000    that two arrays with the same contents were equal, even if the
12001    number of dimensions or subscript ranges were different.)
12002   </para>
12003
12004   <para>
12005    See <xref linkend="arrays"> for more details about array operator
12006    behavior.  See <xref linkend="indexes-types"> for more details about
12007    which operators support indexed operations.
12008   </para>
12009
12010   <para>
12011    <xref linkend="array-functions-table"> shows the functions
12012    available for use with array types. See <xref linkend="arrays">
12013    for more information  and examples of the use of these functions.
12014   </para>
12015
12016   <indexterm>
12017     <primary>array_append</primary>
12018   </indexterm>
12019   <indexterm>
12020     <primary>array_cat</primary>
12021   </indexterm>
12022   <indexterm>
12023     <primary>array_ndims</primary>
12024   </indexterm>
12025   <indexterm>
12026     <primary>array_dims</primary>
12027   </indexterm>
12028   <indexterm>
12029     <primary>array_fill</primary>
12030   </indexterm>
12031   <indexterm>
12032     <primary>array_length</primary>
12033   </indexterm>
12034   <indexterm>
12035     <primary>array_lower</primary>
12036   </indexterm>
12037   <indexterm>
12038     <primary>array_position</primary>
12039   </indexterm>
12040   <indexterm>
12041     <primary>array_positions</primary>
12042   </indexterm>
12043   <indexterm>
12044     <primary>array_prepend</primary>
12045   </indexterm>
12046   <indexterm>
12047     <primary>array_remove</primary>
12048   </indexterm>
12049   <indexterm>
12050     <primary>array_replace</primary>
12051   </indexterm>
12052   <indexterm>
12053     <primary>array_to_string</primary>
12054   </indexterm>
12055  <indexterm>
12056     <primary>array_upper</primary>
12057   </indexterm>
12058   <indexterm>
12059     <primary>cardinality</primary>
12060   </indexterm>
12061   <indexterm>
12062     <primary>string_to_array</primary>
12063   </indexterm>
12064   <indexterm>
12065     <primary>unnest</primary>
12066   </indexterm>
12067
12068     <table id="array-functions-table">
12069      <title>Array Functions</title>
12070      <tgroup cols="5">
12071       <thead>
12072        <row>
12073         <entry>Function</entry>
12074         <entry>Return Type</entry>
12075         <entry>Description</entry>
12076         <entry>Example</entry>
12077         <entry>Result</entry>
12078        </row>
12079       </thead>
12080       <tbody>
12081        <row>
12082         <entry>
12083          <literal>
12084           <function>array_append</function>(<type>anyarray</type>, <type>anyelement</type>)
12085          </literal>
12086         </entry>
12087         <entry><type>anyarray</type></entry>
12088         <entry>append an element to the end of an array</entry>
12089         <entry><literal>array_append(ARRAY[1,2], 3)</literal></entry>
12090         <entry><literal>{1,2,3}</literal></entry>
12091        </row>
12092        <row>
12093         <entry>
12094          <literal>
12095           <function>array_cat</function>(<type>anyarray</type>, <type>anyarray</type>)
12096          </literal>
12097         </entry>
12098         <entry><type>anyarray</type></entry>
12099         <entry>concatenate two arrays</entry>
12100         <entry><literal>array_cat(ARRAY[1,2,3], ARRAY[4,5])</literal></entry>
12101         <entry><literal>{1,2,3,4,5}</literal></entry>
12102        </row>
12103        <row>
12104         <entry>
12105          <literal>
12106           <function>array_ndims</function>(<type>anyarray</type>)
12107          </literal>
12108         </entry>
12109         <entry><type>int</type></entry>
12110         <entry>returns the number of dimensions of the array</entry>
12111         <entry><literal>array_ndims(ARRAY[[1,2,3], [4,5,6]])</literal></entry>
12112         <entry><literal>2</literal></entry>
12113        </row>
12114        <row>
12115         <entry>
12116          <literal>
12117           <function>array_dims</function>(<type>anyarray</type>)
12118          </literal>
12119         </entry>
12120         <entry><type>text</type></entry>
12121         <entry>returns a text representation of array's dimensions</entry>
12122         <entry><literal>array_dims(ARRAY[[1,2,3], [4,5,6]])</literal></entry>
12123         <entry><literal>[1:2][1:3]</literal></entry>
12124        </row>
12125        <row>
12126         <entry>
12127          <literal>
12128           <function>array_fill</function>(<type>anyelement</type>, <type>int[]</type>,
12129           <optional>, <type>int[]</type></optional>)
12130          </literal>
12131         </entry>
12132         <entry><type>anyarray</type></entry>
12133         <entry>returns an array initialized with supplied value and
12134          dimensions, optionally with lower bounds other than 1</entry>
12135         <entry><literal>array_fill(7, ARRAY[3], ARRAY[2])</literal></entry>
12136         <entry><literal>[2:4]={7,7,7}</literal></entry>
12137        </row>
12138        <row>
12139         <entry>
12140          <literal>
12141           <function>array_length</function>(<type>anyarray</type>, <type>int</type>)
12142          </literal>
12143         </entry>
12144         <entry><type>int</type></entry>
12145         <entry>returns the length of the requested array dimension</entry>
12146         <entry><literal>array_length(array[1,2,3], 1)</literal></entry>
12147         <entry><literal>3</literal></entry>
12148        </row>
12149        <row>
12150         <entry>
12151          <literal>
12152           <function>array_lower</function>(<type>anyarray</type>, <type>int</type>)
12153          </literal>
12154         </entry>
12155         <entry><type>int</type></entry>
12156         <entry>returns lower bound of the requested array dimension</entry>
12157         <entry><literal>array_lower('[0:2]={1,2,3}'::int[], 1)</literal></entry>
12158         <entry><literal>0</literal></entry>
12159        </row>
12160        <row>
12161         <entry>
12162          <literal>
12163           <function>array_position</function>(<type>anyarray</type>, <type>anyelement</type> <optional>, <type>int</type></optional>)
12164          </literal>
12165         </entry>
12166         <entry><type>int</type></entry>
12167         <entry>returns the subscript of the first occurrence of the second
12168         argument in the array, starting at the element indicated by the third
12169         argument or at the first element (array must be one-dimensional)</entry>
12170         <entry><literal>array_position(ARRAY['sun','mon','tue','wed','thu','fri','sat'], 'mon')</literal></entry>
12171         <entry><literal>2</literal></entry>
12172        </row>
12173        <row>
12174         <entry>
12175          <literal>
12176           <function>array_positions</function>(<type>anyarray</type>, <type>anyelement</type>)
12177          </literal>
12178         </entry>
12179         <entry><type>int[]</type></entry>
12180         <entry>returns an array of subscripts of all occurrences of the second
12181         argument in the array given as first argument (array must be
12182         one-dimensional)</entry>
12183         <entry><literal>array_positions(ARRAY['A','A','B','A'], 'A')</literal></entry>
12184         <entry><literal>{1,2,4}</literal></entry>
12185        </row>
12186        <row>
12187         <entry>
12188          <literal>
12189           <function>array_prepend</function>(<type>anyelement</type>, <type>anyarray</type>)
12190          </literal>
12191         </entry>
12192         <entry><type>anyarray</type></entry>
12193         <entry>append an element to the beginning of an array</entry>
12194         <entry><literal>array_prepend(1, ARRAY[2,3])</literal></entry>
12195         <entry><literal>{1,2,3}</literal></entry>
12196        </row>
12197        <row>
12198         <entry>
12199          <literal>
12200           <function>array_remove</function>(<type>anyarray</type>, <type>anyelement</type>)
12201          </literal>
12202         </entry>
12203         <entry><type>anyarray</type></entry>
12204         <entry>remove all elements equal to the given value from the array
12205          (array must be one-dimensional)</entry>
12206         <entry><literal>array_remove(ARRAY[1,2,3,2], 2)</literal></entry>
12207         <entry><literal>{1,3}</literal></entry>
12208        </row>
12209        <row>
12210         <entry>
12211          <literal>
12212           <function>array_replace</function>(<type>anyarray</type>, <type>anyelement</type>, <type>anyelement</type>)
12213          </literal>
12214         </entry>
12215         <entry><type>anyarray</type></entry>
12216         <entry>replace each array element equal to the given value with a new value</entry>
12217         <entry><literal>array_replace(ARRAY[1,2,5,4], 5, 3)</literal></entry>
12218         <entry><literal>{1,2,3,4}</literal></entry>
12219        </row>
12220        <row>
12221         <entry>
12222          <literal>
12223           <function>array_to_string</function>(<type>anyarray</type>, <type>text</type> <optional>, <type>text</type></optional>)
12224          </literal>
12225         </entry>
12226         <entry><type>text</type></entry>
12227         <entry>concatenates array elements using supplied delimiter and
12228          optional null string</entry>
12229         <entry><literal>array_to_string(ARRAY[1, 2, 3, NULL, 5], ',', '*')</literal></entry>
12230         <entry><literal>1,2,3,*,5</literal></entry>
12231        </row>
12232        <row>
12233         <entry>
12234          <literal>
12235           <function>array_upper</function>(<type>anyarray</type>, <type>int</type>)
12236          </literal>
12237         </entry>
12238         <entry><type>int</type></entry>
12239         <entry>returns upper bound of the requested array dimension</entry>
12240         <entry><literal>array_upper(ARRAY[1,8,3,7], 1)</literal></entry>
12241         <entry><literal>4</literal></entry>
12242        </row>
12243        <row>
12244         <entry>
12245          <literal>
12246           <function>cardinality</function>(<type>anyarray</type>)
12247          </literal>
12248         </entry>
12249         <entry><type>int</type></entry>
12250         <entry>returns the total number of elements in the array, or 0 if the array is empty</entry>
12251         <entry><literal>cardinality(ARRAY[[1,2],[3,4]])</literal></entry>
12252         <entry><literal>4</literal></entry>
12253        </row>
12254        <row>
12255         <entry>
12256          <literal>
12257           <function>string_to_array</function>(<type>text</type>, <type>text</type> <optional>, <type>text</type></optional>)
12258          </literal>
12259         </entry>
12260         <entry><type>text[]</type></entry>
12261         <entry>splits string into array elements using supplied delimiter and
12262          optional null string</entry>
12263         <entry><literal>string_to_array('xx~^~yy~^~zz', '~^~', 'yy')</literal></entry>
12264         <entry><literal>{xx,NULL,zz}</literal></entry>
12265        </row>
12266        <row>
12267         <entry>
12268          <literal>
12269           <function>unnest</function>(<type>anyarray</type>)
12270          </literal>
12271         </entry>
12272         <entry><type>setof anyelement</type></entry>
12273         <entry>expand an array to a set of rows</entry>
12274         <entry><literal>unnest(ARRAY[1,2])</literal></entry>
12275         <entry><literallayout class="monospaced">1
12276 2</literallayout>(2 rows)</entry>
12277        </row>
12278        <row>
12279         <entry>
12280          <literal>
12281           <function>unnest</function>(<type>anyarray</type>, <type>anyarray</type> [, ...])
12282          </literal>
12283         </entry>
12284         <entry><type>setof anyelement, anyelement [, ...]</type></entry>
12285         <entry>expand multiple arrays (possibly of different types) to a set
12286          of rows.  This is only allowed in the FROM clause; see
12287          <xref linkend="queries-tablefunctions"></entry>
12288         <entry><literal>unnest(ARRAY[1,2],ARRAY['foo','bar','baz'])</literal></entry>
12289         <entry><literallayout class="monospaced">1    foo
12290 2    bar
12291 NULL baz</literallayout>(3 rows)</entry>
12292        </row>
12293       </tbody>
12294      </tgroup>
12295     </table>
12296
12297    <para>
12298     In <function>array_position</function> and <function>array_positions</>,
12299     each array element is compared to the searched value using
12300     <literal>IS NOT DISTINCT FROM</literal> semantics.
12301    </para>
12302
12303    <para>
12304     In <function>array_position</function>, <literal>NULL</literal> is returned
12305     if the value is not found.
12306    </para>
12307
12308    <para>
12309     In <function>array_positions</function>, <literal>NULL</literal> is returned
12310     only if the array is <literal>NULL</literal>; if the value is not found in
12311     the array, an empty array is returned instead.
12312    </para>
12313
12314    <para>
12315     In <function>string_to_array</function>, if the delimiter parameter is
12316     NULL, each character in the input string will become a separate element in
12317     the resulting array.  If the delimiter is an empty string, then the entire
12318     input string is returned as a one-element array.  Otherwise the input
12319     string is split at each occurrence of the delimiter string.
12320    </para>
12321
12322    <para>
12323     In <function>string_to_array</function>, if the null-string parameter
12324     is omitted or NULL, none of the substrings of the input will be replaced
12325     by NULL.
12326     In <function>array_to_string</function>, if the null-string parameter
12327     is omitted or NULL, any null elements in the array are simply skipped
12328     and not represented in the output string.
12329    </para>
12330
12331    <note>
12332     <para>
12333      There are two differences in the behavior of <function>string_to_array</>
12334      from pre-9.1 versions of <productname>PostgreSQL</>.
12335      First, it will return an empty (zero-element) array rather than NULL when
12336      the input string is of zero length.  Second, if the delimiter string is
12337      NULL, the function splits the input into individual characters, rather
12338      than returning NULL as before.
12339     </para>
12340    </note>
12341
12342    <para>
12343     See also <xref linkend="functions-aggregate"> about the aggregate
12344     function <function>array_agg</function> for use with arrays.
12345    </para>
12346   </sect1>
12347
12348  <sect1 id="functions-range">
12349   <title>Range Functions and Operators</title>
12350
12351   <para>
12352    See <xref linkend="rangetypes"> for an overview of range types.
12353   </para>
12354
12355   <para>
12356    <xref linkend="range-operators-table"> shows the operators
12357    available for range types.
12358   </para>
12359
12360     <table id="range-operators-table">
12361      <title>Range Operators</title>
12362      <tgroup cols="4">
12363       <thead>
12364        <row>
12365         <entry>Operator</entry>
12366         <entry>Description</entry>
12367         <entry>Example</entry>
12368         <entry>Result</entry>
12369        </row>
12370       </thead>
12371       <tbody>
12372        <row>
12373         <entry> <literal>=</literal> </entry>
12374         <entry>equal</entry>
12375         <entry><literal>int4range(1,5) = '[1,4]'::int4range</literal></entry>
12376         <entry><literal>t</literal></entry>
12377        </row>
12378
12379        <row>
12380         <entry> <literal>&lt;&gt;</literal> </entry>
12381         <entry>not equal</entry>
12382         <entry><literal>numrange(1.1,2.2) &lt;&gt; numrange(1.1,2.3)</literal></entry>
12383         <entry><literal>t</literal></entry>
12384        </row>
12385
12386        <row>
12387         <entry> <literal>&lt;</literal> </entry>
12388         <entry>less than</entry>
12389         <entry><literal>int4range(1,10) &lt; int4range(2,3)</literal></entry>
12390         <entry><literal>t</literal></entry>
12391        </row>
12392
12393        <row>
12394         <entry> <literal>&gt;</literal> </entry>
12395         <entry>greater than</entry>
12396         <entry><literal>int4range(1,10) &gt; int4range(1,5)</literal></entry>
12397         <entry><literal>t</literal></entry>
12398        </row>
12399
12400        <row>
12401         <entry> <literal>&lt;=</literal> </entry>
12402         <entry>less than or equal</entry>
12403         <entry><literal>numrange(1.1,2.2) &lt;= numrange(1.1,2.2)</literal></entry>
12404         <entry><literal>t</literal></entry>
12405        </row>
12406
12407        <row>
12408         <entry> <literal>&gt;=</literal> </entry>
12409         <entry>greater than or equal</entry>
12410         <entry><literal>numrange(1.1,2.2) &gt;= numrange(1.1,2.0)</literal></entry>
12411         <entry><literal>t</literal></entry>
12412        </row>
12413
12414        <row>
12415         <entry> <literal>@&gt;</literal> </entry>
12416         <entry>contains range</entry>
12417         <entry><literal>int4range(2,4) @&gt; int4range(2,3)</literal></entry>
12418         <entry><literal>t</literal></entry>
12419        </row>
12420
12421        <row>
12422         <entry> <literal>@&gt;</literal> </entry>
12423         <entry>contains element</entry>
12424         <entry><literal>'[2011-01-01,2011-03-01)'::tsrange @&gt; '2011-01-10'::timestamp</literal></entry>
12425         <entry><literal>t</literal></entry>
12426        </row>
12427
12428        <row>
12429         <entry> <literal>&lt;@</literal> </entry>
12430         <entry>range is contained by</entry>
12431         <entry><literal>int4range(2,4) &lt;@ int4range(1,7)</literal></entry>
12432         <entry><literal>t</literal></entry>
12433        </row>
12434
12435        <row>
12436         <entry> <literal>&lt;@</literal> </entry>
12437         <entry>element is contained by</entry>
12438         <entry><literal>42 &lt;@ int4range(1,7)</literal></entry>
12439         <entry><literal>f</literal></entry>
12440        </row>
12441
12442        <row>
12443         <entry> <literal>&amp;&amp;</literal> </entry>
12444         <entry>overlap (have points in common)</entry>
12445         <entry><literal>int8range(3,7) &amp;&amp; int8range(4,12)</literal></entry>
12446         <entry><literal>t</literal></entry>
12447        </row>
12448
12449        <row>
12450         <entry> <literal>&lt;&lt;</literal> </entry>
12451         <entry>strictly left of</entry>
12452         <entry><literal>int8range(1,10) &lt;&lt; int8range(100,110)</literal></entry>
12453         <entry><literal>t</literal></entry>
12454        </row>
12455
12456        <row>
12457         <entry> <literal>&gt;&gt;</literal> </entry>
12458         <entry>strictly right of</entry>
12459         <entry><literal>int8range(50,60) &gt;&gt; int8range(20,30)</literal></entry>
12460         <entry><literal>t</literal></entry>
12461        </row>
12462
12463        <row>
12464         <entry> <literal>&amp;&lt;</literal> </entry>
12465         <entry>does not extend to the right of</entry>
12466         <entry><literal>int8range(1,20) &amp;&lt; int8range(18,20)</literal></entry>
12467         <entry><literal>t</literal></entry>
12468        </row>
12469
12470        <row>
12471         <entry> <literal>&amp;&gt;</literal> </entry>
12472         <entry>does not extend to the left of</entry>
12473         <entry><literal>int8range(7,20) &amp;&gt; int8range(5,10)</literal></entry>
12474         <entry><literal>t</literal></entry>
12475        </row>
12476
12477        <row>
12478         <entry> <literal>-|-</literal> </entry>
12479         <entry>is adjacent to</entry>
12480         <entry><literal>numrange(1.1,2.2) -|- numrange(2.2,3.3)</literal></entry>
12481         <entry><literal>t</literal></entry>
12482        </row>
12483
12484        <row>
12485         <entry> <literal>+</literal> </entry>
12486         <entry>union</entry>
12487         <entry><literal>numrange(5,15) + numrange(10,20)</literal></entry>
12488         <entry><literal>[5,20)</literal></entry>
12489        </row>
12490
12491        <row>
12492         <entry> <literal>*</literal> </entry>
12493         <entry>intersection</entry>
12494         <entry><literal>int8range(5,15) * int8range(10,20)</literal></entry>
12495         <entry><literal>[10,15)</literal></entry>
12496        </row>
12497
12498        <row>
12499         <entry> <literal>-</literal> </entry>
12500         <entry>difference</entry>
12501         <entry><literal>int8range(5,15) - int8range(10,20)</literal></entry>
12502         <entry><literal>[5,10)</literal></entry>
12503        </row>
12504
12505       </tbody>
12506      </tgroup>
12507     </table>
12508
12509   <para>
12510    The simple comparison operators <literal>&lt;</literal>,
12511    <literal>&gt;</literal>, <literal>&lt;=</literal>, and
12512    <literal>&gt;=</literal> compare the lower bounds first, and only if those
12513    are equal, compare the upper bounds.  These comparisons are not usually
12514    very useful for ranges, but are provided to allow B-tree indexes to be
12515    constructed on ranges.
12516   </para>
12517
12518   <para>
12519    The left-of/right-of/adjacent operators always return false when an empty
12520    range is involved; that is, an empty range is not considered to be either
12521    before or after any other range.
12522   </para>
12523
12524   <para>
12525    The union and difference operators will fail if the resulting range would
12526    need to contain two disjoint sub-ranges, as such a range cannot be
12527    represented.
12528   </para>
12529
12530   <para>
12531    <xref linkend="range-functions-table"> shows the functions
12532    available for use with range types.
12533   </para>
12534
12535   <indexterm>
12536     <primary>lower</primary>
12537   </indexterm>
12538   <indexterm>
12539     <primary>upper</primary>
12540   </indexterm>
12541   <indexterm>
12542     <primary>isempty</primary>
12543   </indexterm>
12544   <indexterm>
12545     <primary>lower_inc</primary>
12546   </indexterm>
12547   <indexterm>
12548     <primary>upper_inc</primary>
12549   </indexterm>
12550   <indexterm>
12551     <primary>lower_inf</primary>
12552   </indexterm>
12553   <indexterm>
12554     <primary>upper_inf</primary>
12555   </indexterm>
12556
12557     <table id="range-functions-table">
12558      <title>Range Functions</title>
12559      <tgroup cols="5">
12560       <thead>
12561        <row>
12562         <entry>Function</entry>
12563         <entry>Return Type</entry>
12564         <entry>Description</entry>
12565         <entry>Example</entry>
12566         <entry>Result</entry>
12567        </row>
12568       </thead>
12569       <tbody>
12570        <row>
12571         <entry>
12572          <literal>
12573           <function>lower</function>(<type>anyrange</type>)
12574          </literal>
12575         </entry>
12576         <entry>range's element type</entry>
12577         <entry>lower bound of range</entry>
12578         <entry><literal>lower(numrange(1.1,2.2))</literal></entry>
12579         <entry><literal>1.1</literal></entry>
12580        </row>
12581        <row>
12582         <entry>
12583          <literal>
12584           <function>upper</function>(<type>anyrange</type>)
12585          </literal>
12586         </entry>
12587         <entry>range's element type</entry>
12588         <entry>upper bound of range</entry>
12589         <entry><literal>upper(numrange(1.1,2.2))</literal></entry>
12590         <entry><literal>2.2</literal></entry>
12591        </row>
12592        <row>
12593         <entry>
12594          <literal>
12595           <function>isempty</function>(<type>anyrange</type>)
12596          </literal>
12597         </entry>
12598         <entry><type>boolean</type></entry>
12599         <entry>is the range empty?</entry>
12600         <entry><literal>isempty(numrange(1.1,2.2))</literal></entry>
12601         <entry><literal>false</literal></entry>
12602        </row>
12603        <row>
12604         <entry>
12605          <literal>
12606           <function>lower_inc</function>(<type>anyrange</type>)
12607          </literal>
12608         </entry>
12609         <entry><type>boolean</type></entry>
12610         <entry>is the lower bound inclusive?</entry>
12611         <entry><literal>lower_inc(numrange(1.1,2.2))</literal></entry>
12612         <entry><literal>true</literal></entry>
12613        </row>
12614        <row>
12615         <entry>
12616          <literal>
12617           <function>upper_inc</function>(<type>anyrange</type>)
12618          </literal>
12619         </entry>
12620         <entry><type>boolean</type></entry>
12621         <entry>is the upper bound inclusive?</entry>
12622         <entry><literal>upper_inc(numrange(1.1,2.2))</literal></entry>
12623         <entry><literal>false</literal></entry>
12624        </row>
12625        <row>
12626         <entry>
12627          <literal>
12628           <function>lower_inf</function>(<type>anyrange</type>)
12629          </literal>
12630         </entry>
12631         <entry><type>boolean</type></entry>
12632         <entry>is the lower bound infinite?</entry>
12633         <entry><literal>lower_inf('(,)'::daterange)</literal></entry>
12634         <entry><literal>true</literal></entry>
12635        </row>
12636        <row>
12637         <entry>
12638          <literal>
12639           <function>upper_inf</function>(<type>anyrange</type>)
12640          </literal>
12641         </entry>
12642         <entry><type>boolean</type></entry>
12643         <entry>is the upper bound infinite?</entry>
12644         <entry><literal>upper_inf('(,)'::daterange)</literal></entry>
12645         <entry><literal>true</literal></entry>
12646        </row>
12647        <row>
12648         <entry>
12649          <literal>
12650           <function>range_merge</function>(<type>anyrange</type>, <type>anyrange</type>)
12651          </literal>
12652         </entry>
12653         <entry><type>anyrange</type></entry>
12654         <entry>the smallest range which includes both of the given ranges</entry>
12655         <entry><literal>range_merge('[1,2)'::int4range, '[3,4)'::int4range)</literal></entry>
12656         <entry><literal>[1,4)</literal></entry>
12657        </row>
12658       </tbody>
12659      </tgroup>
12660     </table>
12661
12662   <para>
12663    The <function>lower</> and  <function>upper</> functions return null
12664    if the range is empty or the requested bound is infinite.
12665    The <function>lower_inc</function>, <function>upper_inc</function>,
12666    <function>lower_inf</function>, and <function>upper_inf</function>
12667    functions all return false for an empty range.
12668   </para>
12669   </sect1>
12670
12671  <sect1 id="functions-aggregate">
12672   <title>Aggregate Functions</title>
12673
12674   <indexterm zone="functions-aggregate">
12675    <primary>aggregate function</primary>
12676    <secondary>built-in</secondary>
12677   </indexterm>
12678
12679   <para>
12680    <firstterm>Aggregate functions</firstterm> compute a single result
12681    from a set of input values.  The built-in normal aggregate functions
12682    are listed in
12683    <xref linkend="functions-aggregate-table"> and
12684    <xref linkend="functions-aggregate-statistics-table">.
12685    The built-in ordered-set aggregate functions
12686    are listed in <xref linkend="functions-orderedset-table"> and
12687    <xref linkend="functions-hypothetical-table">.  Grouping operations,
12688    which are closely related to aggregate functions, are listed in
12689    <xref linkend="functions-grouping-table">.
12690    The special syntax considerations for aggregate
12691    functions are explained in <xref linkend="syntax-aggregates">.
12692    Consult <xref linkend="tutorial-agg"> for additional introductory
12693    information.
12694   </para>
12695
12696   <table id="functions-aggregate-table">
12697    <title>General-Purpose Aggregate Functions</title>
12698
12699    <tgroup cols="5">
12700     <thead>
12701      <row>
12702       <entry>Function</entry>
12703       <entry>Argument Type(s)</entry>
12704       <entry>Return Type</entry>
12705       <entry>Partial Mode</entry>
12706       <entry>Description</entry>
12707      </row>
12708     </thead>
12709
12710     <tbody>
12711      <row>
12712       <entry>
12713        <indexterm>
12714         <primary>array_agg</primary>
12715        </indexterm>
12716        <function>array_agg(<replaceable class="parameter">expression</replaceable>)</function>
12717       </entry>
12718       <entry>
12719        any non-array type
12720       </entry>
12721       <entry>
12722        array of the argument type
12723       </entry>
12724       <entry>No</entry>
12725       <entry>input values, including nulls, concatenated into an array</entry>
12726      </row>
12727
12728      <row>
12729       <entry>
12730        <function>array_agg(<replaceable class="parameter">expression</replaceable>)</function>
12731       </entry>
12732       <entry>
12733        any array type
12734       </entry>
12735       <entry>
12736        same as argument data type
12737       </entry>
12738       <entry>No</entry>
12739       <entry>input arrays concatenated into array of one higher dimension
12740        (inputs must all have same dimensionality,
12741         and cannot be empty or NULL)</entry>
12742      </row>
12743
12744      <row>
12745       <entry>
12746        <indexterm>
12747         <primary>average</primary>
12748        </indexterm>
12749        <indexterm>
12750         <primary>avg</primary>
12751        </indexterm>
12752        <function>avg(<replaceable class="parameter">expression</replaceable>)</function>
12753       </entry>
12754       <entry>
12755        <type>smallint</type>, <type>int</type>,
12756        <type>bigint</type>, <type>real</type>, <type>double
12757        precision</type>, <type>numeric</type>, or <type>interval</type>
12758       </entry>
12759       <entry>
12760        <type>numeric</type> for any integer-type argument,
12761        <type>double precision</type> for a floating-point argument,
12762        otherwise the same as the argument data type
12763       </entry>
12764       <entry>Yes</entry>
12765       <entry>the average (arithmetic mean) of all input values</entry>
12766      </row>
12767
12768      <row>
12769       <entry>
12770        <indexterm>
12771         <primary>bit_and</primary>
12772        </indexterm>
12773        <function>bit_and(<replaceable class="parameter">expression</replaceable>)</function>
12774       </entry>
12775       <entry>
12776        <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
12777        <type>bit</type>
12778       </entry>
12779       <entry>
12780         same as argument data type
12781       </entry>
12782       <entry>Yes</entry>
12783       <entry>the bitwise AND of all non-null input values, or null if none</entry>
12784      </row>
12785
12786      <row>
12787       <entry>
12788        <indexterm>
12789         <primary>bit_or</primary>
12790        </indexterm>
12791        <function>bit_or(<replaceable class="parameter">expression</replaceable>)</function>
12792       </entry>
12793       <entry>
12794        <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
12795        <type>bit</type>
12796       </entry>
12797       <entry>
12798         same as argument data type
12799       </entry>
12800       <entry>Yes</entry>
12801       <entry>the bitwise OR of all non-null input values, or null if none</entry>
12802      </row>
12803
12804      <row>
12805       <entry>
12806        <indexterm>
12807         <primary>bool_and</primary>
12808        </indexterm>
12809        <function>bool_and(<replaceable class="parameter">expression</replaceable>)</function>
12810       </entry>
12811       <entry>
12812        <type>bool</type>
12813       </entry>
12814       <entry>
12815        <type>bool</type>
12816       </entry>
12817       <entry>Yes</entry>
12818       <entry>true if all input values are true, otherwise false</entry>
12819      </row>
12820
12821      <row>
12822       <entry>
12823        <indexterm>
12824         <primary>bool_or</primary>
12825        </indexterm>
12826        <function>bool_or(<replaceable class="parameter">expression</replaceable>)</function>
12827       </entry>
12828       <entry>
12829        <type>bool</type>
12830       </entry>
12831       <entry>
12832        <type>bool</type>
12833       </entry>
12834       <entry>Yes</entry>
12835       <entry>true if at least one input value is true, otherwise false</entry>
12836      </row>
12837
12838      <row>
12839       <entry>
12840        <indexterm>
12841         <primary>count</primary>
12842        </indexterm>
12843        <function>count(*)</function>
12844       </entry>
12845       <entry></entry>
12846       <entry><type>bigint</type></entry>
12847       <entry>Yes</entry>
12848       <entry>number of input rows</entry>
12849      </row>
12850
12851      <row>
12852       <entry><function>count(<replaceable class="parameter">expression</replaceable>)</function></entry>
12853       <entry>any</entry>
12854       <entry><type>bigint</type></entry>
12855       <entry>Yes</entry>
12856       <entry>
12857        number of input rows for which the value of <replaceable
12858        class="parameter">expression</replaceable> is not null
12859       </entry>
12860      </row>
12861
12862      <row>
12863       <entry>
12864        <indexterm>
12865         <primary>every</primary>
12866        </indexterm>
12867        <function>every(<replaceable class="parameter">expression</replaceable>)</function>
12868       </entry>
12869       <entry>
12870        <type>bool</type>
12871       </entry>
12872       <entry>
12873        <type>bool</type>
12874       </entry>
12875       <entry>Yes</entry>
12876       <entry>equivalent to <function>bool_and</function></entry>
12877      </row>
12878
12879      <row>
12880       <entry>
12881        <indexterm>
12882         <primary>json_agg</primary>
12883        </indexterm>
12884        <function>json_agg(<replaceable class="parameter">expression</replaceable>)</function>
12885       </entry>
12886       <entry>
12887        <type>any</type>
12888       </entry>
12889       <entry>
12890        <type>json</type>
12891       </entry>
12892       <entry>No</entry>
12893       <entry>aggregates values as a JSON array</entry>
12894      </row>
12895
12896      <row>
12897       <entry>
12898        <indexterm>
12899         <primary>jsonb_agg</primary>
12900        </indexterm>
12901        <function>jsonb_agg(<replaceable class="parameter">expression</replaceable>)</function>
12902       </entry>
12903       <entry>
12904        <type>any</type>
12905       </entry>
12906       <entry>
12907        <type>jsonb</type>
12908       </entry>
12909       <entry>No</entry>
12910       <entry>aggregates values as a JSON array</entry>
12911      </row>
12912
12913      <row>
12914       <entry>
12915        <indexterm>
12916         <primary>json_object_agg</primary>
12917        </indexterm>
12918        <function>json_object_agg(<replaceable class="parameter">name</replaceable>, <replaceable class="parameter">value</replaceable>)</function>
12919       </entry>
12920       <entry>
12921        <type>(any, any)</type>
12922       </entry>
12923       <entry>
12924        <type>json</type>
12925       </entry>
12926       <entry>No</entry>
12927       <entry>aggregates name/value pairs as a JSON object</entry>
12928      </row>
12929
12930      <row>
12931       <entry>
12932        <indexterm>
12933         <primary>jsonb_object_agg</primary>
12934        </indexterm>
12935        <function>jsonb_object_agg(<replaceable class="parameter">name</replaceable>, <replaceable class="parameter">value</replaceable>)</function>
12936       </entry>
12937       <entry>
12938        <type>(any, any)</type>
12939       </entry>
12940       <entry>
12941        <type>jsonb</type>
12942       </entry>
12943       <entry>No</entry>
12944       <entry>aggregates name/value pairs as a JSON object</entry>
12945      </row>
12946
12947      <row>
12948       <entry>
12949        <indexterm>
12950         <primary>max</primary>
12951        </indexterm>
12952        <function>max(<replaceable class="parameter">expression</replaceable>)</function>
12953       </entry>
12954       <entry>any numeric, string, date/time, network, or enum type,
12955              or arrays of these types</entry>
12956       <entry>same as argument type</entry>
12957       <entry>Yes</entry>
12958       <entry>
12959        maximum value of <replaceable
12960        class="parameter">expression</replaceable> across all input
12961        values
12962       </entry>
12963      </row>
12964
12965      <row>
12966       <entry>
12967        <indexterm>
12968         <primary>min</primary>
12969        </indexterm>
12970        <function>min(<replaceable class="parameter">expression</replaceable>)</function>
12971       </entry>
12972       <entry>any numeric, string, date/time, network, or enum type,
12973              or arrays of these types</entry>
12974       <entry>same as argument type</entry>
12975       <entry>Yes</entry>
12976       <entry>
12977        minimum value of <replaceable
12978        class="parameter">expression</replaceable> across all input
12979        values
12980       </entry>
12981      </row>
12982
12983      <row>
12984       <entry>
12985        <indexterm>
12986         <primary>string_agg</primary>
12987        </indexterm>
12988        <function>
12989          string_agg(<replaceable class="parameter">expression</replaceable>,
12990                     <replaceable class="parameter">delimiter</replaceable>)
12991        </function>
12992       </entry>
12993       <entry>
12994        (<type>text</type>, <type>text</type>) or (<type>bytea</type>, <type>bytea</type>)
12995       </entry>
12996       <entry>
12997        same as argument types
12998       </entry>
12999       <entry>No</entry>
13000       <entry>input values concatenated into a string, separated by delimiter</entry>
13001      </row>
13002
13003      <row>
13004       <entry>
13005        <indexterm>
13006         <primary>sum</primary>
13007        </indexterm>
13008        <function>sum(<replaceable class="parameter">expression</replaceable>)</function>
13009       </entry>
13010       <entry>
13011        <type>smallint</type>, <type>int</type>,
13012        <type>bigint</type>, <type>real</type>, <type>double
13013        precision</type>, <type>numeric</type>,
13014        <type>interval</type>, or <type>money</>
13015       </entry>
13016       <entry>
13017        <type>bigint</type> for <type>smallint</type> or
13018        <type>int</type> arguments, <type>numeric</type> for
13019        <type>bigint</type> arguments, otherwise the same as the
13020        argument data type
13021       </entry>
13022       <entry>Yes</entry>
13023       <entry>sum of <replaceable class="parameter">expression</replaceable> across all input values</entry>
13024      </row>
13025
13026      <row>
13027       <entry>
13028        <indexterm>
13029         <primary>xmlagg</primary>
13030        </indexterm>
13031        <function>xmlagg(<replaceable class="parameter">expression</replaceable>)</function>
13032       </entry>
13033       <entry>
13034        <type>xml</type>
13035       </entry>
13036       <entry>
13037        <type>xml</type>
13038       </entry>
13039       <entry>No</entry>
13040       <entry>concatenation of XML values (see also <xref linkend="functions-xml-xmlagg">)</entry>
13041      </row>
13042     </tbody>
13043    </tgroup>
13044   </table>
13045
13046   <para>
13047    It should be noted that except for <function>count</function>,
13048    these functions return a null value when no rows are selected.  In
13049    particular, <function>sum</function> of no rows returns null, not
13050    zero as one might expect, and <function>array_agg</function>
13051    returns null rather than an empty array when there are no input
13052    rows.  The <function>coalesce</function> function can be used to
13053    substitute zero or an empty array for null when necessary.
13054   </para>
13055
13056   <para>
13057    Aggregate functions which support <firstterm>Partial Mode</firstterm>
13058    are eligible to participate in various optimizations, such as parallel
13059    aggregation.
13060   </para>
13061
13062   <note>
13063     <indexterm>
13064       <primary>ANY</primary>
13065     </indexterm>
13066     <indexterm>
13067       <primary>SOME</primary>
13068     </indexterm>
13069     <para>
13070       Boolean aggregates <function>bool_and</function> and
13071       <function>bool_or</function> correspond to standard SQL aggregates
13072       <function>every</function> and <function>any</function> or
13073       <function>some</function>.
13074       As for <function>any</function> and <function>some</function>,
13075       it seems that there is an ambiguity built into the standard syntax:
13076 <programlisting>
13077 SELECT b1 = ANY((SELECT b2 FROM t2 ...)) FROM t1 ...;
13078 </programlisting>
13079       Here <function>ANY</function> can be considered either as introducing
13080       a subquery, or as being an aggregate function, if the subquery
13081       returns one row with a Boolean value.
13082       Thus the standard name cannot be given to these aggregates.
13083     </para>
13084   </note>
13085
13086   <note>
13087    <para>
13088     Users accustomed to working with other SQL database management
13089     systems might be disappointed by the performance of the
13090     <function>count</function> aggregate when it is applied to the
13091     entire table. A query like:
13092 <programlisting>
13093 SELECT count(*) FROM sometable;
13094 </programlisting>
13095     will require effort proportional to the size of the table:
13096     <productname>PostgreSQL</productname> will need to scan either the
13097     entire table or the entirety of an index which includes all rows in
13098     the table.
13099    </para>
13100   </note>
13101
13102   <para>
13103    The aggregate functions <function>array_agg</function>,
13104    <function>json_agg</function>, <function>jsonb_agg</function>,
13105    <function>json_object_agg</function>, <function>jsonb_object_agg</function>,
13106    <function>string_agg</function>,
13107    and <function>xmlagg</function>, as well as similar user-defined
13108    aggregate functions, produce meaningfully different result values
13109    depending on the order of the input values.  This ordering is
13110    unspecified by default, but can be controlled by writing an
13111    <literal>ORDER BY</> clause within the aggregate call, as shown in
13112    <xref linkend="syntax-aggregates">.
13113    Alternatively, supplying the input values from a sorted subquery
13114    will usually work.  For example:
13115
13116 <screen><![CDATA[
13117 SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;
13118 ]]></screen>
13119
13120    Beware that this approach can fail if the outer query level contains
13121    additional processing, such as a join, because that might cause the
13122    subquery's output to be reordered before the aggregate is computed.
13123   </para>
13124
13125   <para>
13126    <xref linkend="functions-aggregate-statistics-table"> shows
13127    aggregate functions typically used in statistical analysis.
13128    (These are separated out merely to avoid cluttering the listing
13129    of more-commonly-used aggregates.)  Where the description mentions
13130    <replaceable class="parameter">N</replaceable>, it means the
13131    number of input rows for which all the input expressions are non-null.
13132    In all cases, null is returned if the computation is meaningless,
13133    for example when <replaceable class="parameter">N</replaceable> is zero.
13134   </para>
13135
13136   <indexterm>
13137    <primary>statistics</primary>
13138   </indexterm>
13139   <indexterm>
13140    <primary>linear regression</primary>
13141   </indexterm>
13142
13143   <table id="functions-aggregate-statistics-table">
13144    <title>Aggregate Functions for Statistics</title>
13145
13146    <tgroup cols="5">
13147     <thead>
13148      <row>
13149       <entry>Function</entry>
13150       <entry>Argument Type</entry>
13151       <entry>Return Type</entry>
13152       <entry>Partial Mode</entry>
13153       <entry>Description</entry>
13154      </row>
13155     </thead>
13156
13157     <tbody>
13158
13159      <row>
13160       <entry>
13161        <indexterm>
13162         <primary>correlation</primary>
13163        </indexterm>
13164        <indexterm>
13165         <primary>corr</primary>
13166        </indexterm>
13167        <function>corr(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13168       </entry>
13169       <entry>
13170        <type>double precision</type>
13171       </entry>
13172       <entry>
13173        <type>double precision</type>
13174       </entry>
13175       <entry>Yes</entry>
13176       <entry>correlation coefficient</entry>
13177      </row>
13178
13179      <row>
13180       <entry>
13181        <indexterm>
13182         <primary>covariance</primary>
13183         <secondary>population</secondary>
13184        </indexterm>
13185        <indexterm>
13186         <primary>covar_pop</primary>
13187        </indexterm>
13188        <function>covar_pop(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13189       </entry>
13190       <entry>
13191        <type>double precision</type>
13192       </entry>
13193       <entry>
13194        <type>double precision</type>
13195       </entry>
13196       <entry>Yes</entry>
13197       <entry>population covariance</entry>
13198      </row>
13199
13200      <row>
13201       <entry>
13202        <indexterm>
13203         <primary>covariance</primary>
13204         <secondary>sample</secondary>
13205        </indexterm>
13206        <indexterm>
13207         <primary>covar_samp</primary>
13208        </indexterm>
13209        <function>covar_samp(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13210       </entry>
13211       <entry>
13212        <type>double precision</type>
13213       </entry>
13214       <entry>
13215        <type>double precision</type>
13216       </entry>
13217       <entry>Yes</entry>
13218       <entry>sample covariance</entry>
13219      </row>
13220
13221      <row>
13222       <entry>
13223        <indexterm>
13224         <primary>regr_avgx</primary>
13225        </indexterm>
13226        <function>regr_avgx(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13227       </entry>
13228       <entry>
13229        <type>double precision</type>
13230       </entry>
13231       <entry>
13232        <type>double precision</type>
13233       </entry>
13234       <entry>Yes</entry>
13235       <entry>average of the independent variable
13236       (<literal>sum(<replaceable class="parameter">X</replaceable>)/<replaceable class="parameter">N</replaceable></literal>)</entry>
13237      </row>
13238
13239      <row>
13240       <entry>
13241        <indexterm>
13242         <primary>regr_avgy</primary>
13243        </indexterm>
13244        <function>regr_avgy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13245       </entry>
13246       <entry>
13247        <type>double precision</type>
13248       </entry>
13249       <entry>
13250        <type>double precision</type>
13251       </entry>
13252       <entry>Yes</entry>
13253       <entry>average of the dependent variable
13254       (<literal>sum(<replaceable class="parameter">Y</replaceable>)/<replaceable class="parameter">N</replaceable></literal>)</entry>
13255      </row>
13256
13257      <row>
13258       <entry>
13259        <indexterm>
13260         <primary>regr_count</primary>
13261        </indexterm>
13262        <function>regr_count(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13263       </entry>
13264       <entry>
13265        <type>double precision</type>
13266       </entry>
13267       <entry>
13268        <type>bigint</type>
13269       </entry>
13270       <entry>Yes</entry>
13271       <entry>number of input rows in which both expressions are nonnull</entry>
13272      </row>
13273
13274      <row>
13275       <entry>
13276        <indexterm>
13277         <primary>regression intercept</primary>
13278        </indexterm>
13279        <indexterm>
13280         <primary>regr_intercept</primary>
13281        </indexterm>
13282        <function>regr_intercept(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13283       </entry>
13284       <entry>
13285        <type>double precision</type>
13286       </entry>
13287       <entry>
13288        <type>double precision</type>
13289       </entry>
13290       <entry>Yes</entry>
13291       <entry>y-intercept of the least-squares-fit linear equation
13292       determined by the (<replaceable
13293       class="parameter">X</replaceable>, <replaceable
13294       class="parameter">Y</replaceable>) pairs</entry>
13295      </row>
13296
13297      <row>
13298       <entry>
13299        <indexterm>
13300         <primary>regr_r2</primary>
13301        </indexterm>
13302        <function>regr_r2(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13303       </entry>
13304       <entry>
13305        <type>double precision</type>
13306       </entry>
13307       <entry>
13308        <type>double precision</type>
13309       </entry>
13310       <entry>Yes</entry>
13311       <entry>square of the correlation coefficient</entry>
13312      </row>
13313
13314      <row>
13315       <entry>
13316        <indexterm>
13317         <primary>regression slope</primary>
13318        </indexterm>
13319        <indexterm>
13320         <primary>regr_slope</primary>
13321        </indexterm>
13322        <function>regr_slope(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13323       </entry>
13324       <entry>
13325        <type>double precision</type>
13326       </entry>
13327       <entry>
13328        <type>double precision</type>
13329       </entry>
13330       <entry>Yes</entry>
13331       <entry>slope of the least-squares-fit linear equation determined
13332       by the (<replaceable class="parameter">X</replaceable>,
13333       <replaceable class="parameter">Y</replaceable>) pairs</entry>
13334      </row>
13335
13336      <row>
13337       <entry>
13338        <indexterm>
13339         <primary>regr_sxx</primary>
13340        </indexterm>
13341        <function>regr_sxx(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13342       </entry>
13343       <entry>
13344        <type>double precision</type>
13345       </entry>
13346       <entry>
13347        <type>double precision</type>
13348       </entry>
13349       <entry>Yes</entry>
13350       <entry><literal>sum(<replaceable
13351       class="parameter">X</replaceable>^2) - sum(<replaceable
13352       class="parameter">X</replaceable>)^2/<replaceable
13353       class="parameter">N</replaceable></literal> (<quote>sum of
13354       squares</quote> of the independent variable)</entry>
13355      </row>
13356
13357      <row>
13358       <entry>
13359        <indexterm>
13360         <primary>regr_sxy</primary>
13361        </indexterm>
13362        <function>regr_sxy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13363       </entry>
13364       <entry>
13365        <type>double precision</type>
13366       </entry>
13367       <entry>
13368        <type>double precision</type>
13369       </entry>
13370       <entry>Yes</entry>
13371       <entry><literal>sum(<replaceable
13372       class="parameter">X</replaceable>*<replaceable
13373       class="parameter">Y</replaceable>) - sum(<replaceable
13374       class="parameter">X</replaceable>) * sum(<replaceable
13375       class="parameter">Y</replaceable>)/<replaceable
13376       class="parameter">N</replaceable></literal> (<quote>sum of
13377       products</quote> of independent times dependent
13378       variable)</entry>
13379      </row>
13380
13381      <row>
13382       <entry>
13383        <indexterm>
13384         <primary>regr_syy</primary>
13385        </indexterm>
13386        <function>regr_syy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
13387       </entry>
13388       <entry>
13389        <type>double precision</type>
13390       </entry>
13391       <entry>
13392        <type>double precision</type>
13393       </entry>
13394       <entry>Yes</entry>
13395       <entry><literal>sum(<replaceable
13396       class="parameter">Y</replaceable>^2) - sum(<replaceable
13397       class="parameter">Y</replaceable>)^2/<replaceable
13398       class="parameter">N</replaceable></literal> (<quote>sum of
13399       squares</quote> of the dependent variable)</entry>
13400      </row>
13401
13402      <row>
13403       <entry>
13404        <indexterm>
13405         <primary>standard deviation</primary>
13406        </indexterm>
13407        <indexterm>
13408         <primary>stddev</primary>
13409        </indexterm>
13410        <function>stddev(<replaceable class="parameter">expression</replaceable>)</function>
13411       </entry>
13412       <entry>
13413        <type>smallint</type>, <type>int</type>,
13414        <type>bigint</type>, <type>real</type>, <type>double
13415        precision</type>, or <type>numeric</type>
13416       </entry>
13417       <entry>
13418        <type>double precision</type> for floating-point arguments,
13419        otherwise <type>numeric</type>
13420       </entry>
13421       <entry>Yes</entry>
13422       <entry>historical alias for <function>stddev_samp</function></entry>
13423      </row>
13424
13425      <row>
13426       <entry>
13427        <indexterm>
13428         <primary>standard deviation</primary>
13429         <secondary>population</secondary>
13430        </indexterm>
13431        <indexterm>
13432         <primary>stddev_pop</primary>
13433        </indexterm>
13434        <function>stddev_pop(<replaceable class="parameter">expression</replaceable>)</function>
13435       </entry>
13436       <entry>
13437        <type>smallint</type>, <type>int</type>,
13438        <type>bigint</type>, <type>real</type>, <type>double
13439        precision</type>, or <type>numeric</type>
13440       </entry>
13441       <entry>
13442        <type>double precision</type> for floating-point arguments,
13443        otherwise <type>numeric</type>
13444       </entry>
13445       <entry>Yes</entry>
13446       <entry>population standard deviation of the input values</entry>
13447      </row>
13448
13449      <row>
13450       <entry>
13451        <indexterm>
13452         <primary>standard deviation</primary>
13453         <secondary>sample</secondary>
13454        </indexterm>
13455        <indexterm>
13456         <primary>stddev_samp</primary>
13457        </indexterm>
13458        <function>stddev_samp(<replaceable class="parameter">expression</replaceable>)</function>
13459       </entry>
13460       <entry>
13461        <type>smallint</type>, <type>int</type>,
13462        <type>bigint</type>, <type>real</type>, <type>double
13463        precision</type>, or <type>numeric</type>
13464       </entry>
13465       <entry>
13466        <type>double precision</type> for floating-point arguments,
13467        otherwise <type>numeric</type>
13468       </entry>
13469       <entry>Yes</entry>
13470       <entry>sample standard deviation of the input values</entry>
13471      </row>
13472
13473      <row>
13474       <entry>
13475        <indexterm>
13476         <primary>variance</primary>
13477        </indexterm>
13478        <function>variance</function>(<replaceable class="parameter">expression</replaceable>)
13479       </entry>
13480       <entry>
13481        <type>smallint</type>, <type>int</type>,
13482        <type>bigint</type>, <type>real</type>, <type>double
13483        precision</type>, or <type>numeric</type>
13484       </entry>
13485       <entry>
13486        <type>double precision</type> for floating-point arguments,
13487        otherwise <type>numeric</type>
13488       </entry>
13489       <entry>Yes</entry>
13490       <entry>historical alias for <function>var_samp</function></entry>
13491      </row>
13492
13493      <row>
13494       <entry>
13495        <indexterm>
13496         <primary>variance</primary>
13497         <secondary>population</secondary>
13498        </indexterm>
13499        <indexterm>
13500         <primary>var_pop</primary>
13501        </indexterm>
13502        <function>var_pop</function>(<replaceable class="parameter">expression</replaceable>)
13503       </entry>
13504       <entry>
13505        <type>smallint</type>, <type>int</type>,
13506        <type>bigint</type>, <type>real</type>, <type>double
13507        precision</type>, or <type>numeric</type>
13508       </entry>
13509       <entry>
13510        <type>double precision</type> for floating-point arguments,
13511        otherwise <type>numeric</type>
13512       </entry>
13513       <entry>Yes</entry>
13514       <entry>population variance of the input values (square of the population standard deviation)</entry>
13515      </row>
13516
13517      <row>
13518       <entry>
13519        <indexterm>
13520         <primary>variance</primary>
13521         <secondary>sample</secondary>
13522        </indexterm>
13523        <indexterm>
13524         <primary>var_samp</primary>
13525        </indexterm>
13526        <function>var_samp</function>(<replaceable class="parameter">expression</replaceable>)
13527       </entry>
13528       <entry>
13529        <type>smallint</type>, <type>int</type>,
13530        <type>bigint</type>, <type>real</type>, <type>double
13531        precision</type>, or <type>numeric</type>
13532       </entry>
13533       <entry>
13534        <type>double precision</type> for floating-point arguments,
13535        otherwise <type>numeric</type>
13536       </entry>
13537       <entry>Yes</entry>
13538       <entry>sample variance of the input values (square of the sample standard deviation)</entry>
13539      </row>
13540     </tbody>
13541    </tgroup>
13542   </table>
13543
13544   <para>
13545    <xref linkend="functions-orderedset-table"> shows some
13546    aggregate functions that use the <firstterm>ordered-set aggregate</>
13547    syntax.  These functions are sometimes referred to as <quote>inverse
13548    distribution</> functions.
13549   </para>
13550
13551   <indexterm>
13552    <primary>ordered-set aggregate</primary>
13553    <secondary>built-in</secondary>
13554   </indexterm>
13555   <indexterm>
13556    <primary>inverse distribution</primary>
13557   </indexterm>
13558
13559   <table id="functions-orderedset-table">
13560    <title>Ordered-Set Aggregate Functions</title>
13561
13562    <tgroup cols="6">
13563     <thead>
13564      <row>
13565       <entry>Function</entry>
13566       <entry>Direct Argument Type(s)</entry>
13567       <entry>Aggregated Argument Type(s)</entry>
13568       <entry>Return Type</entry>
13569       <entry>Partial Mode</entry>
13570       <entry>Description</entry>
13571      </row>
13572     </thead>
13573
13574     <tbody>
13575
13576      <row>
13577       <entry>
13578        <indexterm>
13579         <primary>mode</primary>
13580         <secondary>statistical</secondary>
13581        </indexterm>
13582        <function>mode() WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13583       </entry>
13584       <entry>
13585       </entry>
13586       <entry>
13587        any sortable type
13588       </entry>
13589       <entry>
13590        same as sort expression
13591       </entry>
13592       <entry>No</entry>
13593       <entry>
13594        returns the most frequent input value (arbitrarily choosing the first
13595        one if there are multiple equally-frequent results)
13596       </entry>
13597      </row>
13598
13599      <row>
13600       <entry>
13601        <indexterm>
13602         <primary>percentile</primary>
13603         <secondary>continuous</secondary>
13604        </indexterm>
13605        <indexterm>
13606         <primary>median</primary>
13607        </indexterm>
13608        <function>percentile_cont(<replaceable class="parameter">fraction</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13609       </entry>
13610       <entry>
13611        <type>double precision</type>
13612       </entry>
13613       <entry>
13614        <type>double precision</type> or <type>interval</type>
13615       </entry>
13616       <entry>
13617        same as sort expression
13618       </entry>
13619       <entry>No</entry>
13620       <entry>
13621        continuous percentile: returns a value corresponding to the specified
13622        fraction in the ordering, interpolating between adjacent input items if
13623        needed
13624       </entry>
13625      </row>
13626
13627      <row>
13628       <entry>
13629        <function>percentile_cont(<replaceable class="parameter">fractions</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13630       </entry>
13631       <entry>
13632        <type>double precision[]</type>
13633       </entry>
13634       <entry>
13635        <type>double precision</type> or <type>interval</type>
13636       </entry>
13637       <entry>
13638        array of sort expression's type
13639       </entry>
13640       <entry>No</entry>
13641       <entry>
13642        multiple continuous percentile: returns an array of results matching
13643        the shape of the <literal>fractions</literal> parameter, with each
13644        non-null element replaced by the value corresponding to that percentile
13645       </entry>
13646      </row>
13647
13648      <row>
13649       <entry>
13650        <indexterm>
13651         <primary>percentile</primary>
13652         <secondary>discrete</secondary>
13653        </indexterm>
13654        <function>percentile_disc(<replaceable class="parameter">fraction</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13655       </entry>
13656       <entry>
13657        <type>double precision</type>
13658       </entry>
13659       <entry>
13660        any sortable type
13661       </entry>
13662       <entry>
13663        same as sort expression
13664       </entry>
13665       <entry>No</entry>
13666       <entry>
13667        discrete percentile: returns the first input value whose position in
13668        the ordering equals or exceeds the specified fraction
13669       </entry>
13670      </row>
13671
13672      <row>
13673       <entry>
13674        <function>percentile_disc(<replaceable class="parameter">fractions</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sort_expression</replaceable>)</function>
13675       </entry>
13676       <entry>
13677        <type>double precision[]</type>
13678       </entry>
13679       <entry>
13680        any sortable type
13681       </entry>
13682       <entry>
13683        array of sort expression's type
13684       </entry>
13685       <entry>No</entry>
13686       <entry>
13687        multiple discrete percentile: returns an array of results matching the
13688        shape of the <literal>fractions</literal> parameter, with each non-null
13689        element replaced by the input value corresponding to that percentile
13690       </entry>
13691      </row>
13692
13693     </tbody>
13694    </tgroup>
13695   </table>
13696
13697   <para>
13698    All the aggregates listed in <xref linkend="functions-orderedset-table">
13699    ignore null values in their sorted input.  For those that take
13700    a <replaceable>fraction</replaceable> parameter, the fraction value must be
13701    between 0 and 1; an error is thrown if not.  However, a null fraction value
13702    simply produces a null result.
13703   </para>
13704
13705   <indexterm>
13706    <primary>hypothetical-set aggregate</primary>
13707    <secondary>built-in</secondary>
13708   </indexterm>
13709
13710   <para>
13711    Each of the aggregates listed in
13712    <xref linkend="functions-hypothetical-table"> is associated with a
13713    window function of the same name defined in
13714    <xref linkend="functions-window">.  In each case, the aggregate result
13715    is the value that the associated window function would have
13716    returned for the <quote>hypothetical</> row constructed from
13717    <replaceable>args</replaceable>, if such a row had been added to the sorted
13718    group of rows computed from the <replaceable>sorted_args</replaceable>.
13719   </para>
13720
13721   <table id="functions-hypothetical-table">
13722    <title>Hypothetical-Set Aggregate Functions</title>
13723
13724    <tgroup cols="6">
13725     <thead>
13726      <row>
13727       <entry>Function</entry>
13728       <entry>Direct Argument Type(s)</entry>
13729       <entry>Aggregated Argument Type(s)</entry>
13730       <entry>Return Type</entry>
13731       <entry>Partial Mode</entry>
13732       <entry>Description</entry>
13733      </row>
13734     </thead>
13735
13736     <tbody>
13737
13738      <row>
13739       <entry>
13740        <indexterm>
13741         <primary>rank</primary>
13742         <secondary>hypothetical</secondary>
13743        </indexterm>
13744        <function>rank(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
13745       </entry>
13746       <entry>
13747        <literal>VARIADIC</> <type>"any"</type>
13748       </entry>
13749       <entry>
13750        <literal>VARIADIC</> <type>"any"</type>
13751       </entry>
13752       <entry>
13753        <type>bigint</type>
13754       </entry>
13755       <entry>No</entry>
13756       <entry>
13757        rank of the hypothetical row, with gaps for duplicate rows
13758       </entry>
13759      </row>
13760
13761      <row>
13762       <entry>
13763        <indexterm>
13764         <primary>dense_rank</primary>
13765         <secondary>hypothetical</secondary>
13766        </indexterm>
13767        <function>dense_rank(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
13768       </entry>
13769       <entry>
13770        <literal>VARIADIC</> <type>"any"</type>
13771       </entry>
13772       <entry>
13773        <literal>VARIADIC</> <type>"any"</type>
13774       </entry>
13775       <entry>
13776        <type>bigint</type>
13777       </entry>
13778       <entry>No</entry>
13779       <entry>
13780        rank of the hypothetical row, without gaps
13781       </entry>
13782      </row>
13783
13784      <row>
13785       <entry>
13786        <indexterm>
13787         <primary>percent_rank</primary>
13788         <secondary>hypothetical</secondary>
13789        </indexterm>
13790        <function>percent_rank(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
13791       </entry>
13792       <entry>
13793        <literal>VARIADIC</> <type>"any"</type>
13794       </entry>
13795       <entry>
13796        <literal>VARIADIC</> <type>"any"</type>
13797       </entry>
13798       <entry>
13799        <type>double precision</type>
13800       </entry>
13801       <entry>No</entry>
13802       <entry>
13803        relative rank of the hypothetical row, ranging from 0 to 1
13804       </entry>
13805      </row>
13806
13807      <row>
13808       <entry>
13809        <indexterm>
13810         <primary>cume_dist</primary>
13811         <secondary>hypothetical</secondary>
13812        </indexterm>
13813        <function>cume_dist(<replaceable class="parameter">args</replaceable>) WITHIN GROUP (ORDER BY <replaceable class="parameter">sorted_args</replaceable>)</function>
13814       </entry>
13815       <entry>
13816        <literal>VARIADIC</> <type>"any"</type>
13817       </entry>
13818       <entry>
13819        <literal>VARIADIC</> <type>"any"</type>
13820       </entry>
13821       <entry>
13822        <type>double precision</type>
13823       </entry>
13824       <entry>No</entry>
13825       <entry>
13826        relative rank of the hypothetical row, ranging from
13827        1/<replaceable>N</> to 1
13828       </entry>
13829      </row>
13830
13831     </tbody>
13832    </tgroup>
13833   </table>
13834
13835   <para>
13836    For each of these hypothetical-set aggregates, the list of direct arguments
13837    given in <replaceable>args</replaceable> must match the number and types of
13838    the aggregated arguments given in <replaceable>sorted_args</replaceable>.
13839    Unlike most built-in aggregates, these aggregates are not strict, that is
13840    they do not drop input rows containing nulls.  Null values sort according
13841    to the rule specified in the <literal>ORDER BY</> clause.
13842   </para>
13843
13844   <table id="functions-grouping-table">
13845    <title>Grouping Operations</title>
13846
13847    <tgroup cols="3">
13848     <thead>
13849      <row>
13850       <entry>Function</entry>
13851       <entry>Return Type</entry>
13852       <entry>Description</entry>
13853      </row>
13854     </thead>
13855
13856     <tbody>
13857
13858      <row>
13859       <entry>
13860        <indexterm>
13861         <primary>GROUPING</primary>
13862        </indexterm>
13863        <function>GROUPING(<replaceable class="parameter">args...</replaceable>)</function>
13864       </entry>
13865       <entry>
13866        <type>integer</type>
13867       </entry>
13868       <entry>
13869        Integer bit mask indicating which arguments are not being included in the current
13870        grouping set
13871       </entry>
13872      </row>
13873     </tbody>
13874    </tgroup>
13875   </table>
13876
13877    <para>
13878     Grouping operations are used in conjunction with grouping sets (see
13879     <xref linkend="queries-grouping-sets">) to distinguish result rows.  The
13880     arguments to the <literal>GROUPING</> operation are not actually evaluated,
13881     but they must match exactly expressions given in the <literal>GROUP BY</>
13882     clause of the associated query level.  Bits are assigned with the rightmost
13883     argument being the least-significant bit; each bit is 0 if the corresponding
13884     expression is included in the grouping criteria of the grouping set generating
13885     the result row, and 1 if it is not.  For example:
13886 <screen>
13887 <prompt>=&gt;</> <userinput>SELECT * FROM items_sold;</>
13888  make  | model | sales
13889 -------+-------+-------
13890  Foo   | GT    |  10
13891  Foo   | Tour  |  20
13892  Bar   | City  |  15
13893  Bar   | Sport |  5
13894 (4 rows)
13895
13896 <prompt>=&gt;</> <userinput>SELECT make, model, GROUPING(make,model), sum(sales) FROM items_sold GROUP BY ROLLUP(make,model);</>
13897  make  | model | grouping | sum
13898 -------+-------+----------+-----
13899  Foo   | GT    |        0 | 10
13900  Foo   | Tour  |        0 | 20
13901  Bar   | City  |        0 | 15
13902  Bar   | Sport |        0 | 5
13903  Foo   |       |        1 | 30
13904  Bar   |       |        1 | 20
13905        |       |        3 | 50
13906 (7 rows)
13907 </screen>
13908    </para>
13909
13910  </sect1>
13911
13912  <sect1 id="functions-window">
13913   <title>Window Functions</title>
13914
13915   <indexterm zone="functions-window">
13916    <primary>window function</primary>
13917    <secondary>built-in</secondary>
13918   </indexterm>
13919
13920   <para>
13921    <firstterm>Window functions</firstterm> provide the ability to perform
13922    calculations across sets of rows that are related to the current query
13923    row.  See <xref linkend="tutorial-window"> for an introduction to this
13924    feature, and <xref linkend="syntax-window-functions"> for syntax
13925    details.
13926   </para>
13927
13928   <para>
13929    The built-in window functions are listed in
13930    <xref linkend="functions-window-table">.  Note that these functions
13931    <emphasis>must</> be invoked using window function syntax; that is an
13932    <literal>OVER</> clause is required.
13933   </para>
13934
13935   <para>
13936    In addition to these functions, any built-in or user-defined normal
13937    aggregate function (but not ordered-set or hypothetical-set aggregates)
13938    can be used as a window function; see
13939    <xref linkend="functions-aggregate"> for a list of the built-in aggregates.
13940    Aggregate functions act as window functions only when an <literal>OVER</>
13941    clause follows the call; otherwise they act as regular aggregates.
13942   </para>
13943
13944   <table id="functions-window-table">
13945    <title>General-Purpose Window Functions</title>
13946
13947    <tgroup cols="3">
13948     <thead>
13949      <row>
13950       <entry>Function</entry>
13951       <entry>Return Type</entry>
13952       <entry>Description</entry>
13953      </row>
13954     </thead>
13955
13956     <tbody>
13957      <row>
13958       <entry>
13959        <indexterm>
13960         <primary>row_number</primary>
13961        </indexterm>
13962        <function>row_number()</function>
13963       </entry>
13964       <entry>
13965        <type>bigint</type>
13966       </entry>
13967       <entry>number of the current row within its partition, counting from 1</entry>
13968      </row>
13969
13970      <row>
13971       <entry>
13972        <indexterm>
13973         <primary>rank</primary>
13974        </indexterm>
13975        <function>rank()</function>
13976       </entry>
13977       <entry>
13978        <type>bigint</type>
13979       </entry>
13980       <entry>rank of the current row with gaps; same as <function>row_number</> of its first peer</entry>
13981      </row>
13982
13983      <row>
13984       <entry>
13985        <indexterm>
13986         <primary>dense_rank</primary>
13987        </indexterm>
13988        <function>dense_rank()</function>
13989       </entry>
13990       <entry>
13991        <type>bigint</type>
13992       </entry>
13993       <entry>rank of the current row without gaps; this function counts peer groups</entry>
13994      </row>
13995
13996      <row>
13997       <entry>
13998        <indexterm>
13999         <primary>percent_rank</primary>
14000        </indexterm>
14001        <function>percent_rank()</function>
14002       </entry>
14003       <entry>
14004        <type>double precision</type>
14005       </entry>
14006       <entry>relative rank of the current row: (<function>rank</> - 1) / (total rows - 1)</entry>
14007      </row>
14008
14009      <row>
14010       <entry>
14011        <indexterm>
14012         <primary>cume_dist</primary>
14013        </indexterm>
14014        <function>cume_dist()</function>
14015       </entry>
14016       <entry>
14017        <type>double precision</type>
14018       </entry>
14019       <entry>relative rank of the current row: (number of rows preceding or peer with current row) / (total rows)</entry>
14020      </row>
14021
14022      <row>
14023       <entry>
14024        <indexterm>
14025         <primary>ntile</primary>
14026        </indexterm>
14027        <function>ntile(<replaceable class="parameter">num_buckets</replaceable> <type>integer</>)</function>
14028       </entry>
14029       <entry>
14030        <type>integer</type>
14031       </entry>
14032       <entry>integer ranging from 1 to the argument value, dividing the
14033        partition as equally as possible</entry>
14034      </row>
14035
14036      <row>
14037       <entry>
14038        <indexterm>
14039         <primary>lag</primary>
14040        </indexterm>
14041        <function>
14042          lag(<replaceable class="parameter">value</replaceable> <type>anyelement</>
14043              [, <replaceable class="parameter">offset</replaceable> <type>integer</>
14044              [, <replaceable class="parameter">default</replaceable> <type>anyelement</> ]])
14045        </function>
14046       </entry>
14047       <entry>
14048        <type>same type as <replaceable class="parameter">value</replaceable></type>
14049       </entry>
14050       <entry>
14051        returns <replaceable class="parameter">value</replaceable> evaluated at
14052        the row that is <replaceable class="parameter">offset</replaceable>
14053        rows before the current row within the partition; if there is no such
14054        row, instead return <replaceable class="parameter">default</replaceable>
14055        (which must be of the same type as
14056        <replaceable class="parameter">value</replaceable>).
14057        Both <replaceable class="parameter">offset</replaceable> and
14058        <replaceable class="parameter">default</replaceable> are evaluated
14059        with respect to the current row.  If omitted,
14060        <replaceable class="parameter">offset</replaceable> defaults to 1 and
14061        <replaceable class="parameter">default</replaceable> to null
14062       </entry>
14063      </row>
14064
14065      <row>
14066       <entry>
14067        <indexterm>
14068         <primary>lead</primary>
14069        </indexterm>
14070        <function>
14071          lead(<replaceable class="parameter">value</replaceable> <type>anyelement</>
14072               [, <replaceable class="parameter">offset</replaceable> <type>integer</>
14073               [, <replaceable class="parameter">default</replaceable> <type>anyelement</> ]])
14074        </function>
14075       </entry>
14076       <entry>
14077        <type>same type as <replaceable class="parameter">value</replaceable></type>
14078       </entry>
14079       <entry>
14080        returns <replaceable class="parameter">value</replaceable> evaluated at
14081        the row that is <replaceable class="parameter">offset</replaceable>
14082        rows after the current row within the partition; if there is no such
14083        row, instead return <replaceable class="parameter">default</replaceable>
14084        (which must be of the same type as
14085        <replaceable class="parameter">value</replaceable>).
14086        Both <replaceable class="parameter">offset</replaceable> and
14087        <replaceable class="parameter">default</replaceable> are evaluated
14088        with respect to the current row.  If omitted,
14089        <replaceable class="parameter">offset</replaceable> defaults to 1 and
14090        <replaceable class="parameter">default</replaceable> to null
14091       </entry>
14092      </row>
14093
14094      <row>
14095       <entry>
14096        <indexterm>
14097         <primary>first_value</primary>
14098        </indexterm>
14099        <function>first_value(<replaceable class="parameter">value</replaceable> <type>any</>)</function>
14100       </entry>
14101       <entry>
14102        <type>same type as <replaceable class="parameter">value</replaceable></type>
14103       </entry>
14104       <entry>
14105        returns <replaceable class="parameter">value</replaceable> evaluated
14106        at the row that is the first row of the window frame
14107       </entry>
14108      </row>
14109
14110      <row>
14111       <entry>
14112        <indexterm>
14113         <primary>last_value</primary>
14114        </indexterm>
14115        <function>last_value(<replaceable class="parameter">value</replaceable> <type>any</>)</function>
14116       </entry>
14117       <entry>
14118        <type>same type as <replaceable class="parameter">value</replaceable></type>
14119       </entry>
14120       <entry>
14121        returns <replaceable class="parameter">value</replaceable> evaluated
14122        at the row that is the last row of the window frame
14123       </entry>
14124      </row>
14125
14126      <row>
14127       <entry>
14128        <indexterm>
14129         <primary>nth_value</primary>
14130        </indexterm>
14131        <function>
14132          nth_value(<replaceable class="parameter">value</replaceable> <type>any</>, <replaceable class="parameter">nth</replaceable> <type>integer</>)
14133        </function>
14134       </entry>
14135       <entry>
14136        <type>same type as <replaceable class="parameter">value</replaceable></type>
14137       </entry>
14138       <entry>
14139        returns <replaceable class="parameter">value</replaceable> evaluated
14140        at the row that is the <replaceable class="parameter">nth</replaceable>
14141        row of the window frame (counting from 1); null if no such row
14142       </entry>
14143      </row>
14144     </tbody>
14145    </tgroup>
14146   </table>
14147
14148   <para>
14149    All of the functions listed in
14150    <xref linkend="functions-window-table"> depend on the sort ordering
14151    specified by the <literal>ORDER BY</> clause of the associated window
14152    definition.  Rows that are not distinct in the <literal>ORDER BY</>
14153    ordering are said to be <firstterm>peers</>; the four ranking functions
14154    are defined so that they give the same answer for any two peer rows.
14155   </para>
14156
14157   <para>
14158    Note that <function>first_value</>, <function>last_value</>, and
14159    <function>nth_value</> consider only the rows within the <quote>window
14160    frame</>, which by default contains the rows from the start of the
14161    partition through the last peer of the current row.  This is
14162    likely to give unhelpful results for <function>last_value</> and
14163    sometimes also <function>nth_value</>.  You can redefine the frame by
14164    adding a suitable frame specification (<literal>RANGE</> or
14165    <literal>ROWS</>) to the <literal>OVER</> clause.
14166    See <xref linkend="syntax-window-functions"> for more information
14167    about frame specifications.
14168   </para>
14169
14170   <para>
14171    When an aggregate function is used as a window function, it aggregates
14172    over the rows within the current row's window frame.
14173    An aggregate used with <literal>ORDER BY</> and the default window frame
14174    definition produces a <quote>running sum</> type of behavior, which may or
14175    may not be what's wanted.  To obtain
14176    aggregation over the whole partition, omit <literal>ORDER BY</> or use
14177    <literal>ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING</>.
14178    Other frame specifications can be used to obtain other effects.
14179   </para>
14180
14181   <note>
14182    <para>
14183     The SQL standard defines a <literal>RESPECT NULLS</> or
14184     <literal>IGNORE NULLS</> option for <function>lead</>, <function>lag</>,
14185     <function>first_value</>, <function>last_value</>, and
14186     <function>nth_value</>.  This is not implemented in
14187     <productname>PostgreSQL</productname>: the behavior is always the
14188     same as the standard's default, namely <literal>RESPECT NULLS</>.
14189     Likewise, the standard's <literal>FROM FIRST</> or <literal>FROM LAST</>
14190     option for <function>nth_value</> is not implemented: only the
14191     default <literal>FROM FIRST</> behavior is supported.  (You can achieve
14192     the result of <literal>FROM LAST</> by reversing the <literal>ORDER BY</>
14193     ordering.)
14194    </para>
14195   </note>
14196
14197  </sect1>
14198
14199  <sect1 id="functions-subquery">
14200   <title>Subquery Expressions</title>
14201
14202   <indexterm>
14203    <primary>EXISTS</primary>
14204   </indexterm>
14205
14206   <indexterm>
14207    <primary>IN</primary>
14208   </indexterm>
14209
14210   <indexterm>
14211    <primary>NOT IN</primary>
14212   </indexterm>
14213
14214   <indexterm>
14215    <primary>ANY</primary>
14216   </indexterm>
14217
14218   <indexterm>
14219    <primary>ALL</primary>
14220   </indexterm>
14221
14222   <indexterm>
14223    <primary>SOME</primary>
14224   </indexterm>
14225
14226   <indexterm>
14227    <primary>subquery</primary>
14228   </indexterm>
14229
14230   <para>
14231    This section describes the <acronym>SQL</acronym>-compliant subquery
14232    expressions available in <productname>PostgreSQL</productname>.
14233    All of the expression forms documented in this section return
14234    Boolean (true/false) results.
14235   </para>
14236
14237   <sect2 id="functions-subquery-exists">
14238    <title><literal>EXISTS</literal></title>
14239
14240 <synopsis>
14241 EXISTS (<replaceable>subquery</replaceable>)
14242 </synopsis>
14243
14244   <para>
14245    The argument of <token>EXISTS</token> is an arbitrary <command>SELECT</> statement,
14246    or <firstterm>subquery</firstterm>.  The
14247    subquery is evaluated to determine whether it returns any rows.
14248    If it returns at least one row, the result of <token>EXISTS</token> is
14249    <quote>true</>; if the subquery returns no rows, the result of <token>EXISTS</token>
14250    is <quote>false</>.
14251   </para>
14252
14253   <para>
14254    The subquery can refer to variables from the surrounding query,
14255    which will act as constants during any one evaluation of the subquery.
14256   </para>
14257
14258   <para>
14259    The subquery will generally only be executed long enough to determine
14260    whether at least one row is returned, not all the way to completion.
14261    It is unwise to write a subquery that has side effects (such as
14262    calling sequence functions); whether the side effects occur
14263    might be unpredictable.
14264   </para>
14265
14266   <para>
14267    Since the result depends only on whether any rows are returned,
14268    and not on the contents of those rows, the output list of the
14269    subquery is normally unimportant.  A common coding convention is
14270    to write all <literal>EXISTS</> tests in the form
14271    <literal>EXISTS(SELECT 1 WHERE ...)</literal>.  There are exceptions to
14272    this rule however, such as subqueries that use <token>INTERSECT</token>.
14273   </para>
14274
14275   <para>
14276    This simple example is like an inner join on <literal>col2</>, but
14277    it produces at most one output row for each <literal>tab1</> row,
14278    even if there are several matching <literal>tab2</> rows:
14279 <screen>
14280 SELECT col1
14281 FROM tab1
14282 WHERE EXISTS (SELECT 1 FROM tab2 WHERE col2 = tab1.col2);
14283 </screen>
14284   </para>
14285   </sect2>
14286
14287   <sect2 id="functions-subquery-in">
14288    <title><literal>IN</literal></title>
14289
14290 <synopsis>
14291 <replaceable>expression</replaceable> IN (<replaceable>subquery</replaceable>)
14292 </synopsis>
14293
14294   <para>
14295    The right-hand side is a parenthesized
14296    subquery, which must return exactly one column.  The left-hand expression
14297    is evaluated and compared to each row of the subquery result.
14298    The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
14299    The result is <quote>false</> if no equal row is found (including the
14300    case where the subquery returns no rows).
14301   </para>
14302
14303   <para>
14304    Note that if the left-hand expression yields null, or if there are
14305    no equal right-hand values and at least one right-hand row yields
14306    null, the result of the <token>IN</token> construct will be null, not false.
14307    This is in accordance with SQL's normal rules for Boolean combinations
14308    of null values.
14309   </para>
14310
14311   <para>
14312    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14313    be evaluated completely.
14314   </para>
14315
14316 <synopsis>
14317 <replaceable>row_constructor</replaceable> IN (<replaceable>subquery</replaceable>)
14318 </synopsis>
14319
14320   <para>
14321    The left-hand side of this form of <token>IN</token> is a row constructor,
14322    as described in <xref linkend="sql-syntax-row-constructors">.
14323    The right-hand side is a parenthesized
14324    subquery, which must return exactly as many columns as there are
14325    expressions in the left-hand row.  The left-hand expressions are
14326    evaluated and compared row-wise to each row of the subquery result.
14327    The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
14328    The result is <quote>false</> if no equal row is found (including the
14329    case where the subquery returns no rows).
14330   </para>
14331
14332   <para>
14333    As usual, null values in the rows are combined per
14334    the normal rules of SQL Boolean expressions.  Two rows are considered
14335    equal if all their corresponding members are non-null and equal; the rows
14336    are unequal if any corresponding members are non-null and unequal;
14337    otherwise the result of that row comparison is unknown (null).
14338    If all the per-row results are either unequal or null, with at least one
14339    null, then the result of <token>IN</token> is null.
14340   </para>
14341   </sect2>
14342
14343   <sect2 id="functions-subquery-notin">
14344    <title><literal>NOT IN</literal></title>
14345
14346 <synopsis>
14347 <replaceable>expression</replaceable> NOT IN (<replaceable>subquery</replaceable>)
14348 </synopsis>
14349
14350   <para>
14351    The right-hand side is a parenthesized
14352    subquery, which must return exactly one column.  The left-hand expression
14353    is evaluated and compared to each row of the subquery result.
14354    The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
14355    are found (including the case where the subquery returns no rows).
14356    The result is <quote>false</> if any equal row is found.
14357   </para>
14358
14359   <para>
14360    Note that if the left-hand expression yields null, or if there are
14361    no equal right-hand values and at least one right-hand row yields
14362    null, the result of the <token>NOT IN</token> construct will be null, not true.
14363    This is in accordance with SQL's normal rules for Boolean combinations
14364    of null values.
14365   </para>
14366
14367   <para>
14368    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14369    be evaluated completely.
14370   </para>
14371
14372 <synopsis>
14373 <replaceable>row_constructor</replaceable> NOT IN (<replaceable>subquery</replaceable>)
14374 </synopsis>
14375
14376   <para>
14377    The left-hand side of this form of <token>NOT IN</token> is a row constructor,
14378    as described in <xref linkend="sql-syntax-row-constructors">.
14379    The right-hand side is a parenthesized
14380    subquery, which must return exactly as many columns as there are
14381    expressions in the left-hand row.  The left-hand expressions are
14382    evaluated and compared row-wise to each row of the subquery result.
14383    The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
14384    are found (including the case where the subquery returns no rows).
14385    The result is <quote>false</> if any equal row is found.
14386   </para>
14387
14388   <para>
14389    As usual, null values in the rows are combined per
14390    the normal rules of SQL Boolean expressions.  Two rows are considered
14391    equal if all their corresponding members are non-null and equal; the rows
14392    are unequal if any corresponding members are non-null and unequal;
14393    otherwise the result of that row comparison is unknown (null).
14394    If all the per-row results are either unequal or null, with at least one
14395    null, then the result of <token>NOT IN</token> is null.
14396   </para>
14397   </sect2>
14398
14399   <sect2 id="functions-subquery-any-some">
14400    <title><literal>ANY</literal>/<literal>SOME</literal></title>
14401
14402 <synopsis>
14403 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>subquery</replaceable>)
14404 <replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>subquery</replaceable>)
14405 </synopsis>
14406
14407   <para>
14408    The right-hand side is a parenthesized
14409    subquery, which must return exactly one column.  The left-hand expression
14410    is evaluated and compared to each row of the subquery result using the
14411    given <replaceable>operator</replaceable>, which must yield a Boolean
14412    result.
14413    The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
14414    The result is <quote>false</> if no true result is found (including the
14415    case where the subquery returns no rows).
14416   </para>
14417
14418   <para>
14419    <token>SOME</token> is a synonym for <token>ANY</token>.
14420    <token>IN</token> is equivalent to <literal>= ANY</literal>.
14421   </para>
14422
14423   <para>
14424    Note that if there are no successes and at least one right-hand row yields
14425    null for the operator's result, the result of the <token>ANY</token> construct
14426    will be null, not false.
14427    This is in accordance with SQL's normal rules for Boolean combinations
14428    of null values.
14429   </para>
14430
14431   <para>
14432    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14433    be evaluated completely.
14434   </para>
14435
14436 <synopsis>
14437 <replaceable>row_constructor</replaceable> <replaceable>operator</> ANY (<replaceable>subquery</replaceable>)
14438 <replaceable>row_constructor</replaceable> <replaceable>operator</> SOME (<replaceable>subquery</replaceable>)
14439 </synopsis>
14440
14441   <para>
14442    The left-hand side of this form of <token>ANY</token> is a row constructor,
14443    as described in <xref linkend="sql-syntax-row-constructors">.
14444    The right-hand side is a parenthesized
14445    subquery, which must return exactly as many columns as there are
14446    expressions in the left-hand row.  The left-hand expressions are
14447    evaluated and compared row-wise to each row of the subquery result,
14448    using the given <replaceable>operator</replaceable>.
14449    The result of <token>ANY</token> is <quote>true</> if the comparison
14450    returns true for any subquery row.
14451    The result is <quote>false</> if the comparison returns false for every
14452    subquery row (including the case where the subquery returns no
14453    rows).
14454    The result is NULL if the comparison does not return true for any row,
14455    and it returns NULL for at least one row.
14456   </para>
14457
14458   <para>
14459    See <xref linkend="row-wise-comparison"> for details about the meaning
14460    of a row constructor comparison.
14461   </para>
14462   </sect2>
14463
14464   <sect2 id="functions-subquery-all">
14465    <title><literal>ALL</literal></title>
14466
14467 <synopsis>
14468 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
14469 </synopsis>
14470
14471   <para>
14472    The right-hand side is a parenthesized
14473    subquery, which must return exactly one column.  The left-hand expression
14474    is evaluated and compared to each row of the subquery result using the
14475    given <replaceable>operator</replaceable>, which must yield a Boolean
14476    result.
14477    The result of <token>ALL</token> is <quote>true</> if all rows yield true
14478    (including the case where the subquery returns no rows).
14479    The result is <quote>false</> if any false result is found.
14480    The result is NULL if the comparison does not return false for any row,
14481    and it returns NULL for at least one row.
14482   </para>
14483
14484   <para>
14485    <token>NOT IN</token> is equivalent to <literal>&lt;&gt; ALL</literal>.
14486   </para>
14487
14488   <para>
14489    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
14490    be evaluated completely.
14491   </para>
14492
14493 <synopsis>
14494 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
14495 </synopsis>
14496
14497   <para>
14498    The left-hand side of this form of <token>ALL</token> is a row constructor,
14499    as described in <xref linkend="sql-syntax-row-constructors">.
14500    The right-hand side is a parenthesized
14501    subquery, which must return exactly as many columns as there are
14502    expressions in the left-hand row.  The left-hand expressions are
14503    evaluated and compared row-wise to each row of the subquery result,
14504    using the given <replaceable>operator</replaceable>.
14505    The result of <token>ALL</token> is <quote>true</> if the comparison
14506    returns true for all subquery rows (including the
14507    case where the subquery returns no rows).
14508    The result is <quote>false</> if the comparison returns false for any
14509    subquery row.
14510    The result is NULL if the comparison does not return false for any
14511    subquery row, and it returns NULL for at least one row.
14512   </para>
14513
14514   <para>
14515    See <xref linkend="row-wise-comparison"> for details about the meaning
14516    of a row constructor comparison.
14517   </para>
14518   </sect2>
14519
14520   <sect2>
14521    <title>Single-row Comparison</title>
14522
14523    <indexterm zone="functions-subquery">
14524     <primary>comparison</primary>
14525     <secondary>subquery result row</secondary>
14526    </indexterm>
14527
14528 <synopsis>
14529 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> (<replaceable>subquery</replaceable>)
14530 </synopsis>
14531
14532   <para>
14533    The left-hand side is a row constructor,
14534    as described in <xref linkend="sql-syntax-row-constructors">.
14535    The right-hand side is a parenthesized subquery, which must return exactly
14536    as many columns as there are expressions in the left-hand row. Furthermore,
14537    the subquery cannot return more than one row.  (If it returns zero rows,
14538    the result is taken to be null.)  The left-hand side is evaluated and
14539    compared row-wise to the single subquery result row.
14540   </para>
14541
14542   <para>
14543    See <xref linkend="row-wise-comparison"> for details about the meaning
14544    of a row constructor comparison.
14545   </para>
14546   </sect2>
14547  </sect1>
14548
14549
14550  <sect1 id="functions-comparisons">
14551   <title>Row and Array Comparisons</title>
14552
14553   <indexterm>
14554    <primary>IN</primary>
14555   </indexterm>
14556
14557   <indexterm>
14558    <primary>NOT IN</primary>
14559   </indexterm>
14560
14561   <indexterm>
14562    <primary>ANY</primary>
14563   </indexterm>
14564
14565   <indexterm>
14566    <primary>ALL</primary>
14567   </indexterm>
14568
14569   <indexterm>
14570    <primary>SOME</primary>
14571   </indexterm>
14572
14573   <indexterm>
14574    <primary>composite type</primary>
14575    <secondary>comparison</secondary>
14576   </indexterm>
14577
14578   <indexterm>
14579    <primary>row-wise comparison</primary>
14580   </indexterm>
14581
14582   <indexterm>
14583    <primary>comparison</primary>
14584    <secondary>composite type</secondary>
14585   </indexterm>
14586
14587   <indexterm>
14588    <primary>comparison</primary>
14589    <secondary>row constructor</secondary>
14590   </indexterm>
14591
14592   <indexterm>
14593    <primary>IS DISTINCT FROM</primary>
14594   </indexterm>
14595
14596   <indexterm>
14597    <primary>IS NOT DISTINCT FROM</primary>
14598   </indexterm>
14599
14600   <para>
14601    This section describes several specialized constructs for making
14602    multiple comparisons between groups of values.  These forms are
14603    syntactically related to the subquery forms of the previous section,
14604    but do not involve subqueries.
14605    The forms involving array subexpressions are
14606    <productname>PostgreSQL</productname> extensions; the rest are
14607    <acronym>SQL</acronym>-compliant.
14608    All of the expression forms documented in this section return
14609    Boolean (true/false) results.
14610   </para>
14611
14612   <sect2>
14613    <title><literal>IN</literal></title>
14614
14615 <synopsis>
14616 <replaceable>expression</replaceable> IN (<replaceable>value</replaceable> <optional>, ...</optional>)
14617 </synopsis>
14618
14619   <para>
14620    The right-hand side is a parenthesized list
14621    of scalar expressions.  The result is <quote>true</> if the left-hand expression's
14622    result is equal to any of the right-hand expressions.  This is a shorthand
14623    notation for
14624
14625 <synopsis>
14626 <replaceable>expression</replaceable> = <replaceable>value1</replaceable>
14627 OR
14628 <replaceable>expression</replaceable> = <replaceable>value2</replaceable>
14629 OR
14630 ...
14631 </synopsis>
14632   </para>
14633
14634   <para>
14635    Note that if the left-hand expression yields null, or if there are
14636    no equal right-hand values and at least one right-hand expression yields
14637    null, the result of the <token>IN</token> construct will be null, not false.
14638    This is in accordance with SQL's normal rules for Boolean combinations
14639    of null values.
14640   </para>
14641   </sect2>
14642
14643   <sect2>
14644    <title><literal>NOT IN</literal></title>
14645
14646 <synopsis>
14647 <replaceable>expression</replaceable> NOT IN (<replaceable>value</replaceable> <optional>, ...</optional>)
14648 </synopsis>
14649
14650   <para>
14651    The right-hand side is a parenthesized list
14652    of scalar expressions.  The result is <quote>true</quote> if the left-hand expression's
14653    result is unequal to all of the right-hand expressions.  This is a shorthand
14654    notation for
14655
14656 <synopsis>
14657 <replaceable>expression</replaceable> &lt;&gt; <replaceable>value1</replaceable>
14658 AND
14659 <replaceable>expression</replaceable> &lt;&gt; <replaceable>value2</replaceable>
14660 AND
14661 ...
14662 </synopsis>
14663   </para>
14664
14665   <para>
14666    Note that if the left-hand expression yields null, or if there are
14667    no equal right-hand values and at least one right-hand expression yields
14668    null, the result of the <token>NOT IN</token> construct will be null, not true
14669    as one might naively expect.
14670    This is in accordance with SQL's normal rules for Boolean combinations
14671    of null values.
14672   </para>
14673
14674   <tip>
14675   <para>
14676    <literal>x NOT IN y</literal> is equivalent to <literal>NOT (x IN y)</literal> in all
14677    cases.  However, null values are much more likely to trip up the novice when
14678    working with <token>NOT IN</token> than when working with <token>IN</token>.
14679    It is best to express your condition positively if possible.
14680   </para>
14681   </tip>
14682   </sect2>
14683
14684   <sect2>
14685    <title><literal>ANY</literal>/<literal>SOME</literal> (array)</title>
14686
14687 <synopsis>
14688 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>array expression</replaceable>)
14689 <replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>array expression</replaceable>)
14690 </synopsis>
14691
14692   <para>
14693    The right-hand side is a parenthesized expression, which must yield an
14694    array value.
14695    The left-hand expression
14696    is evaluated and compared to each element of the array using the
14697    given <replaceable>operator</replaceable>, which must yield a Boolean
14698    result.
14699    The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
14700    The result is <quote>false</> if no true result is found (including the
14701    case where the array has zero elements).
14702   </para>
14703
14704   <para>
14705    If the array expression yields a null array, the result of
14706    <token>ANY</token> will be null.  If the left-hand expression yields null,
14707    the result of <token>ANY</token> is ordinarily null (though a non-strict
14708    comparison operator could possibly yield a different result).
14709    Also, if the right-hand array contains any null elements and no true
14710    comparison result is obtained, the result of <token>ANY</token>
14711    will be null, not false (again, assuming a strict comparison operator).
14712    This is in accordance with SQL's normal rules for Boolean combinations
14713    of null values.
14714   </para>
14715
14716   <para>
14717    <token>SOME</token> is a synonym for <token>ANY</token>.
14718   </para>
14719   </sect2>
14720
14721   <sect2>
14722    <title><literal>ALL</literal> (array)</title>
14723
14724 <synopsis>
14725 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>array expression</replaceable>)
14726 </synopsis>
14727
14728   <para>
14729    The right-hand side is a parenthesized expression, which must yield an
14730    array value.
14731    The left-hand expression
14732    is evaluated and compared to each element of the array using the
14733    given <replaceable>operator</replaceable>, which must yield a Boolean
14734    result.
14735    The result of <token>ALL</token> is <quote>true</> if all comparisons yield true
14736    (including the case where the array has zero elements).
14737    The result is <quote>false</> if any false result is found.
14738   </para>
14739
14740   <para>
14741    If the array expression yields a null array, the result of
14742    <token>ALL</token> will be null.  If the left-hand expression yields null,
14743    the result of <token>ALL</token> is ordinarily null (though a non-strict
14744    comparison operator could possibly yield a different result).
14745    Also, if the right-hand array contains any null elements and no false
14746    comparison result is obtained, the result of <token>ALL</token>
14747    will be null, not true (again, assuming a strict comparison operator).
14748    This is in accordance with SQL's normal rules for Boolean combinations
14749    of null values.
14750   </para>
14751   </sect2>
14752
14753   <sect2 id="row-wise-comparison">
14754    <title>Row Constructor Comparison</title>
14755
14756 <synopsis>
14757 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> <replaceable>row_constructor</replaceable>
14758 </synopsis>
14759
14760   <para>
14761    Each side is a row constructor,
14762    as described in <xref linkend="sql-syntax-row-constructors">.
14763    The two row values must have the same number of fields.
14764    Each side is evaluated and they are compared row-wise.  Row constructor
14765    comparisons are allowed when the <replaceable>operator</replaceable> is
14766    <literal>=</>,
14767    <literal>&lt;&gt;</>,
14768    <literal>&lt;</>,
14769    <literal>&lt;=</>,
14770    <literal>&gt;</> or
14771    <literal>&gt;=</>.
14772    Every row element must be of a type which has a default B-tree operator
14773    class or the attempted comparison may generate an error.
14774   </para>
14775
14776   <note>
14777    <para>
14778     Errors related to the number or types of elements might not occur if
14779     the comparison is resolved using earlier columns.
14780    </para>
14781   </note>
14782
14783   <para>
14784    The <literal>=</> and <literal>&lt;&gt;</> cases work slightly differently
14785    from the others.  Two rows are considered
14786    equal if all their corresponding members are non-null and equal; the rows
14787    are unequal if any corresponding members are non-null and unequal;
14788    otherwise the result of the row comparison is unknown (null).
14789   </para>
14790
14791   <para>
14792    For the <literal>&lt;</>, <literal>&lt;=</>, <literal>&gt;</> and
14793    <literal>&gt;=</> cases, the row elements are compared left-to-right,
14794    stopping as soon as an unequal or null pair of elements is found.
14795    If either of this pair of elements is null, the result of the
14796    row comparison is unknown (null); otherwise comparison of this pair
14797    of elements determines the result.  For example,
14798    <literal>ROW(1,2,NULL) &lt; ROW(1,3,0)</>
14799    yields true, not null, because the third pair of elements are not
14800    considered.
14801   </para>
14802
14803   <note>
14804    <para>
14805     Prior to <productname>PostgreSQL</productname> 8.2, the
14806     <literal>&lt;</>, <literal>&lt;=</>, <literal>&gt;</> and <literal>&gt;=</>
14807     cases were not handled per SQL specification.  A comparison like
14808     <literal>ROW(a,b) &lt; ROW(c,d)</>
14809     was implemented as
14810     <literal>a &lt; c AND b &lt; d</>
14811     whereas the correct behavior is equivalent to
14812     <literal>a &lt; c OR (a = c AND b &lt; d)</>.
14813    </para>
14814   </note>
14815
14816 <synopsis>
14817 <replaceable>row_constructor</replaceable> IS DISTINCT FROM <replaceable>row_constructor</replaceable>
14818 </synopsis>
14819
14820   <para>
14821    This construct is similar to a <literal>&lt;&gt;</literal> row comparison,
14822    but it does not yield null for null inputs.  Instead, any null value is
14823    considered unequal to (distinct from) any non-null value, and any two
14824    nulls are considered equal (not distinct).  Thus the result will
14825    either be true or false, never null.
14826   </para>
14827
14828 <synopsis>
14829 <replaceable>row_constructor</replaceable> IS NOT DISTINCT FROM <replaceable>row_constructor</replaceable>
14830 </synopsis>
14831
14832   <para>
14833    This construct is similar to a <literal>=</literal> row comparison,
14834    but it does not yield null for null inputs.  Instead, any null value is
14835    considered unequal to (distinct from) any non-null value, and any two
14836    nulls are considered equal (not distinct).  Thus the result will always
14837    be either true or false, never null.
14838   </para>
14839
14840   </sect2>
14841
14842   <sect2 id="composite-type-comparison">
14843    <title>Composite Type Comparison</title>
14844
14845 <synopsis>
14846 <replaceable>record</replaceable> <replaceable>operator</replaceable> <replaceable>record</replaceable>
14847 </synopsis>
14848
14849   <para>
14850    The SQL specification requires row-wise comparison to return NULL if the
14851    result depends on comparing two NULL values or a NULL and a non-NULL.
14852    <productname>PostgreSQL</productname> does this only when comparing the
14853    results of two row constructors (as in
14854    <xref linkend="row-wise-comparison">) or comparing a row constructor
14855    to the output of a subquery (as in <xref linkend="functions-subquery">).
14856    In other contexts where two composite-type values are compared, two
14857    NULL field values are considered equal, and a NULL is considered larger
14858    than a non-NULL.  This is necessary in order to have consistent sorting
14859    and indexing behavior for composite types.
14860   </para>
14861
14862   <para>
14863    Each side is evaluated and they are compared row-wise.  Composite type
14864    comparisons are allowed when the <replaceable>operator</replaceable> is
14865    <literal>=</>,
14866    <literal>&lt;&gt;</>,
14867    <literal>&lt;</>,
14868    <literal>&lt;=</>,
14869    <literal>&gt;</> or
14870    <literal>&gt;=</>,
14871    or has semantics similar to one of these.  (To be specific, an operator
14872    can be a row comparison operator if it is a member of a B-tree operator
14873    class, or is the negator of the <literal>=</> member of a B-tree operator
14874    class.)  The default behavior of the above operators is the same as for
14875    <literal>IS [ NOT ] DISTINCT FROM</literal> for row constructors (see
14876    <xref linkend="row-wise-comparison">).
14877   </para>
14878
14879   <para>
14880    To support matching of rows which include elements without a default
14881    B-tree operator class, the following operators are defined for composite
14882    type comparison:
14883    <literal>*=</>,
14884    <literal>*&lt;&gt;</>,
14885    <literal>*&lt;</>,
14886    <literal>*&lt;=</>,
14887    <literal>*&gt;</>, and
14888    <literal>*&gt;=</>.
14889    These operators compare the internal binary representation of the two
14890    rows.  Two rows might have a different binary representation even
14891    though comparisons of the two rows with the equality operator is true.
14892    The ordering of rows under these comparison operators is deterministic
14893    but not otherwise meaningful.  These operators are used internally for
14894    materialized views and might be useful for other specialized purposes
14895    such as replication but are not intended to be generally useful for
14896    writing queries.
14897   </para>
14898   </sect2>
14899  </sect1>
14900
14901  <sect1 id="functions-srf">
14902   <title>Set Returning Functions</title>
14903
14904   <indexterm zone="functions-srf">
14905    <primary>set returning functions</primary>
14906    <secondary>functions</secondary>
14907   </indexterm>
14908
14909   <indexterm>
14910    <primary>generate_series</primary>
14911   </indexterm>
14912
14913   <para>
14914    This section describes functions that possibly return more than one row.
14915    The most widely used functions in this class are series generating
14916    functions, as detailed in <xref linkend="functions-srf-series"> and
14917    <xref linkend="functions-srf-subscripts">.  Other, more specialized
14918    set-returning functions are described elsewhere in this manual.
14919    See <xref linkend="queries-tablefunctions"> for ways to combine multiple
14920    set-returning functions.
14921   </para>
14922
14923   <table id="functions-srf-series">
14924    <title>Series Generating Functions</title>
14925    <tgroup cols="4">
14926     <thead>
14927      <row>
14928       <entry>Function</entry>
14929       <entry>Argument Type</entry>
14930       <entry>Return Type</entry>
14931       <entry>Description</entry>
14932      </row>
14933     </thead>
14934
14935     <tbody>
14936      <row>
14937       <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>)</function></literal></entry>
14938       <entry><type>int</type>, <type>bigint</type> or <type>numeric</type></entry>
14939       <entry><type>setof int</type>, <type>setof bigint</type>, or <type>setof numeric</type> (same as argument type)</entry>
14940       <entry>
14941        Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
14942        with a step size of one
14943       </entry>
14944      </row>
14945
14946      <row>
14947       <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>, <parameter>step</parameter>)</function></literal></entry>
14948       <entry><type>int</type>, <type>bigint</type> or <type>numeric</type></entry>
14949       <entry><type>setof int</type>, <type>setof bigint</type> or <type>setof numeric</type> (same as argument type)</entry>
14950       <entry>
14951        Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
14952        with a step size of <parameter>step</parameter>
14953       </entry>
14954      </row>
14955
14956      <row>
14957       <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>, <parameter>step</parameter> <type>interval</>)</function></literal></entry>
14958       <entry><type>timestamp</type> or <type>timestamp with time zone</type></entry>
14959       <entry><type>setof timestamp</type> or <type>setof timestamp with time zone</type> (same as argument type)</entry>
14960       <entry>
14961        Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
14962        with a step size of <parameter>step</parameter>
14963       </entry>
14964      </row>
14965
14966     </tbody>
14967    </tgroup>
14968   </table>
14969
14970   <para>
14971    When <parameter>step</parameter> is positive, zero rows are returned if
14972    <parameter>start</parameter> is greater than <parameter>stop</parameter>.
14973    Conversely, when <parameter>step</parameter> is negative, zero rows are
14974    returned if <parameter>start</parameter> is less than <parameter>stop</parameter>.
14975    Zero rows are also returned for <literal>NULL</literal> inputs. It is an error
14976    for <parameter>step</parameter> to be zero. Some examples follow:
14977 <programlisting>
14978 SELECT * FROM generate_series(2,4);
14979  generate_series
14980 -----------------
14981                2
14982                3
14983                4
14984 (3 rows)
14985
14986 SELECT * FROM generate_series(5,1,-2);
14987  generate_series
14988 -----------------
14989                5
14990                3
14991                1
14992 (3 rows)
14993
14994 SELECT * FROM generate_series(4,3);
14995  generate_series
14996 -----------------
14997 (0 rows)
14998
14999 SELECT generate_series(1.1, 4, 1.3);
15000  generate_series 
15001 -----------------
15002              1.1
15003              2.4
15004              3.7
15005 (3 rows)
15006
15007 -- this example relies on the date-plus-integer operator
15008 SELECT current_date + s.a AS dates FROM generate_series(0,14,7) AS s(a);
15009    dates
15010 ------------
15011  2004-02-05
15012  2004-02-12
15013  2004-02-19
15014 (3 rows)
15015
15016 SELECT * FROM generate_series('2008-03-01 00:00'::timestamp,
15017                               '2008-03-04 12:00', '10 hours');
15018    generate_series   
15019 ---------------------
15020  2008-03-01 00:00:00
15021  2008-03-01 10:00:00
15022  2008-03-01 20:00:00
15023  2008-03-02 06:00:00
15024  2008-03-02 16:00:00
15025  2008-03-03 02:00:00
15026  2008-03-03 12:00:00
15027  2008-03-03 22:00:00
15028  2008-03-04 08:00:00
15029 (9 rows)
15030 </programlisting>
15031   </para>
15032
15033   <table id="functions-srf-subscripts">
15034    <title>Subscript Generating Functions</title>
15035    <tgroup cols="3">
15036     <thead>
15037      <row>
15038       <entry>Function</entry>
15039       <entry>Return Type</entry>
15040       <entry>Description</entry>
15041      </row>
15042     </thead>
15043
15044     <tbody>
15045      <row>
15046       <entry><literal><function>generate_subscripts(<parameter>array anyarray</parameter>, <parameter>dim int</parameter>)</function></literal></entry>
15047       <entry><type>setof int</type></entry>
15048       <entry>
15049        Generate a series comprising the given array's subscripts.
15050       </entry>
15051      </row>
15052
15053      <row>
15054       <entry><literal><function>generate_subscripts(<parameter>array anyarray</parameter>, <parameter>dim int</parameter>, <parameter>reverse boolean</parameter>)</function></literal></entry>
15055       <entry><type>setof int</type></entry>
15056       <entry>
15057        Generate a series comprising the given array's subscripts. When
15058        <parameter>reverse</parameter> is true, the series is returned in
15059        reverse order.
15060       </entry>
15061      </row>
15062
15063     </tbody>
15064    </tgroup>
15065   </table>
15066
15067   <indexterm>
15068    <primary>generate_subscripts</primary>
15069   </indexterm>
15070
15071   <para>
15072    <function>generate_subscripts</> is a convenience function that generates
15073    the set of valid subscripts for the specified dimension of the given
15074    array.
15075    Zero rows are returned for arrays that do not have the requested dimension,
15076    or for NULL arrays (but valid subscripts are returned for NULL array
15077    elements).  Some examples follow:
15078 <programlisting>
15079 -- basic usage
15080 SELECT generate_subscripts('{NULL,1,NULL,2}'::int[], 1) AS s;
15081  s 
15082 ---
15083  1
15084  2
15085  3
15086  4
15087 (4 rows)
15088
15089 -- presenting an array, the subscript and the subscripted
15090 -- value requires a subquery
15091 SELECT * FROM arrays;
15092          a          
15093 --------------------
15094  {-1,-2}
15095  {100,200,300}
15096 (2 rows)
15097
15098 SELECT a AS array, s AS subscript, a[s] AS value
15099 FROM (SELECT generate_subscripts(a, 1) AS s, a FROM arrays) foo;
15100      array     | subscript | value
15101 ---------------+-----------+-------
15102  {-1,-2}       |         1 |    -1
15103  {-1,-2}       |         2 |    -2
15104  {100,200,300} |         1 |   100
15105  {100,200,300} |         2 |   200
15106  {100,200,300} |         3 |   300
15107 (5 rows)
15108
15109 -- unnest a 2D array
15110 CREATE OR REPLACE FUNCTION unnest2(anyarray)
15111 RETURNS SETOF anyelement AS $$
15112 select $1[i][j]
15113    from generate_subscripts($1,1) g1(i),
15114         generate_subscripts($1,2) g2(j);
15115 $$ LANGUAGE sql IMMUTABLE;
15116 CREATE FUNCTION
15117 SELECT * FROM unnest2(ARRAY[[1,2],[3,4]]);
15118  unnest2 
15119 ---------
15120        1
15121        2
15122        3
15123        4
15124 (4 rows)
15125 </programlisting>
15126   </para>
15127
15128   <indexterm>
15129    <primary>ordinality</primary>
15130   </indexterm>
15131
15132   <para>
15133    When a function in the <literal>FROM</literal> clause is suffixed
15134    by <literal>WITH ORDINALITY</literal>, a <type>bigint</type> column is
15135    appended to the output which starts from 1 and increments by 1 for each row
15136    of the function's output.  This is most useful in the case of set returning
15137    functions such as <function>unnest()</>.
15138
15139 <programlisting>
15140 -- set returning function WITH ORDINALITY
15141 SELECT * FROM pg_ls_dir('.') WITH ORDINALITY AS t(ls,n);
15142        ls        | n
15143 -----------------+----
15144  pg_serial       |  1
15145  pg_twophase     |  2
15146  postmaster.opts |  3
15147  pg_notify       |  4
15148  postgresql.conf |  5
15149  pg_tblspc       |  6
15150  logfile         |  7
15151  base            |  8
15152  postmaster.pid  |  9
15153  pg_ident.conf   | 10
15154  global          | 11
15155  pg_clog         | 12
15156  pg_snapshots    | 13
15157  pg_multixact    | 14
15158  PG_VERSION      | 15
15159  pg_xlog         | 16
15160  pg_hba.conf     | 17
15161  pg_stat_tmp     | 18
15162  pg_subtrans     | 19
15163 (19 rows)
15164 </programlisting>
15165   </para>
15166
15167  </sect1>
15168
15169  <sect1 id="functions-info">
15170   <title>System Information Functions</title>
15171
15172   <para>
15173    <xref linkend="functions-info-session-table"> shows several
15174    functions that extract session and system information.
15175   </para>
15176
15177   <para>
15178    In addition to the functions listed in this section, there are a number of
15179    functions related to the statistics system that also provide system
15180    information. See <xref linkend="monitoring-stats-views"> for more
15181    information.
15182   </para>
15183
15184    <table id="functions-info-session-table">
15185     <title>Session Information Functions</title>
15186     <tgroup cols="3">
15187      <thead>
15188       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
15189      </thead>
15190
15191      <tbody>
15192       <row>
15193        <entry><literal><function>current_catalog</function></literal></entry>
15194        <entry><type>name</type></entry>
15195        <entry>name of current database (called <quote>catalog</quote> in the SQL standard)</entry>
15196       </row>
15197
15198       <row>
15199        <entry><literal><function>current_database()</function></literal></entry>
15200        <entry><type>name</type></entry>
15201        <entry>name of current database</entry>
15202       </row>
15203
15204       <row>
15205        <entry><literal><function>current_query()</function></literal></entry>
15206        <entry><type>text</type></entry>
15207        <entry>text of the currently executing query, as submitted
15208        by the client (might contain more than one statement)</entry>
15209       </row>
15210
15211       <row>
15212        <entry><literal><function>current_schema</function>[()]</literal></entry>
15213        <entry><type>name</type></entry>
15214        <entry>name of current schema</entry>
15215       </row>
15216
15217       <row>
15218        <entry><literal><function>current_schemas(<type>boolean</type>)</function></literal></entry>
15219        <entry><type>name[]</type></entry>
15220        <entry>names of schemas in search path, optionally including implicit schemas</entry>
15221       </row>
15222
15223       <row>
15224        <entry><literal><function>current_user</function></literal></entry>
15225        <entry><type>name</type></entry>
15226        <entry>user name of current execution context</entry>
15227       </row>
15228
15229       <row>
15230        <entry><literal><function>inet_client_addr()</function></literal></entry>
15231        <entry><type>inet</type></entry>
15232        <entry>address of the remote connection</entry>
15233       </row>
15234
15235       <row>
15236        <entry><literal><function>inet_client_port()</function></literal></entry>
15237        <entry><type>int</type></entry>
15238        <entry>port of the remote connection</entry>
15239       </row>
15240
15241       <row>
15242        <entry><literal><function>inet_server_addr()</function></literal></entry>
15243        <entry><type>inet</type></entry>
15244        <entry>address of the local connection</entry>
15245       </row>
15246
15247       <row>
15248        <entry><literal><function>inet_server_port()</function></literal></entry>
15249        <entry><type>int</type></entry>
15250        <entry>port of the local connection</entry>
15251       </row>
15252
15253       <row>
15254        <!-- See also the entry for this in monitoring.sgml -->
15255        <entry><literal><function>pg_backend_pid()</function></literal></entry>
15256        <entry><type>int</type></entry>
15257        <entry>
15258         Process ID of the server process attached to the current session
15259        </entry>
15260       </row>
15261
15262       <row>
15263        <entry><literal><function>pg_blocking_pids(<type>int</type>)</function></literal></entry>
15264        <entry><type>int[]</type></entry>
15265        <entry>Process ID(s) that are blocking specified server process ID</entry>
15266       </row>
15267
15268       <row>
15269        <entry><literal><function>pg_conf_load_time()</function></literal></entry>
15270        <entry><type>timestamp with time zone</type></entry>
15271        <entry>configuration load time</entry>
15272       </row>
15273
15274       <row>
15275        <entry><literal><function>pg_my_temp_schema()</function></literal></entry>
15276        <entry><type>oid</type></entry>
15277        <entry>OID of session's temporary schema, or 0 if none</entry>
15278       </row>
15279
15280       <row>
15281        <entry><literal><function>pg_is_other_temp_schema(<type>oid</type>)</function></literal></entry>
15282        <entry><type>boolean</type></entry>
15283        <entry>is schema another session's temporary schema?</entry>
15284       </row>
15285
15286       <row>
15287        <entry><literal><function>pg_listening_channels()</function></literal></entry>
15288        <entry><type>setof text</type></entry>
15289        <entry>channel names that the session is currently listening on</entry>
15290       </row>
15291
15292       <row>
15293        <entry><literal><function>pg_notification_queue_usage()</function></literal></entry>
15294        <entry><type>double</type></entry>
15295        <entry>fraction of the asynchronous notification queue currently occupied (0-1)</entry>
15296       </row>
15297
15298       <row>
15299        <entry><literal><function>pg_postmaster_start_time()</function></literal></entry>
15300        <entry><type>timestamp with time zone</type></entry>
15301        <entry>server start time</entry>
15302       </row>
15303
15304       <row>
15305        <entry><literal><function>pg_trigger_depth()</function></literal></entry>
15306        <entry><type>int</type></entry>
15307        <entry>current nesting level of <productname>PostgreSQL</> triggers
15308        (0 if not called, directly or indirectly, from inside a trigger)</entry>
15309       </row>
15310
15311       <row>
15312        <entry><literal><function>session_user</function></literal></entry>
15313        <entry><type>name</type></entry>
15314        <entry>session user name</entry>
15315       </row>
15316
15317       <row>
15318        <entry><literal><function>user</function></literal></entry>
15319        <entry><type>name</type></entry>
15320        <entry>equivalent to <function>current_user</function></entry>
15321       </row>
15322
15323       <row>
15324        <entry><literal><function>version()</function></literal></entry>
15325        <entry><type>text</type></entry>
15326        <entry><productname>PostgreSQL</> version information. See also <xref linkend="guc-server-version-num"> for a machine-readable version.</entry>
15327       </row>
15328      </tbody>
15329     </tgroup>
15330    </table>
15331
15332    <note>
15333     <para>
15334      <function>current_catalog</function>, <function>current_schema</function>,
15335      <function>current_user</function>, <function>session_user</function>,
15336      and <function>user</function> have special syntactic status
15337      in <acronym>SQL</acronym>: they must be called without trailing
15338      parentheses.  (In PostgreSQL, parentheses can optionally be used with
15339      <function>current_schema</function>, but not with the others.)
15340     </para>
15341    </note>
15342
15343    <indexterm>
15344     <primary>current_catalog</primary>
15345    </indexterm>
15346
15347    <indexterm>
15348     <primary>current_database</primary>
15349    </indexterm>
15350
15351    <indexterm>
15352     <primary>current_query</primary>
15353    </indexterm>
15354
15355    <indexterm>
15356     <primary>current_schema</primary>
15357    </indexterm>
15358
15359    <indexterm>
15360     <primary>current_schemas</primary>
15361    </indexterm>
15362
15363    <indexterm>
15364     <primary>current_user</primary>
15365    </indexterm>
15366
15367    <indexterm>
15368     <primary>pg_backend_pid</primary>
15369    </indexterm>
15370
15371    <indexterm>
15372     <primary>schema</primary>
15373     <secondary>current</secondary>
15374    </indexterm>
15375
15376    <indexterm>
15377     <primary>search path</primary>
15378     <secondary>current</secondary>
15379    </indexterm>
15380
15381    <indexterm>
15382     <primary>session_user</primary>
15383    </indexterm>
15384
15385    <indexterm>
15386     <primary>user</primary>
15387     <secondary>current</secondary>
15388    </indexterm>
15389
15390    <indexterm>
15391     <primary>user</primary>
15392    </indexterm>
15393
15394    <para>
15395     The <function>session_user</function> is normally the user who initiated
15396     the current database connection; but superusers can change this setting
15397     with <xref linkend="sql-set-session-authorization">.
15398     The <function>current_user</function> is the user identifier
15399     that is applicable for permission checking. Normally it is equal
15400     to the session user, but it can be changed with
15401     <xref linkend="sql-set-role">.
15402     It also changes during the execution of
15403     functions with the attribute <literal>SECURITY DEFINER</literal>.
15404     In Unix parlance, the session user is the <quote>real user</quote> and
15405     the current user is the <quote>effective user</quote>.
15406    </para>
15407
15408    <para>
15409     <function>current_schema</function> returns the name of the schema that is
15410     first in the search path (or a null value if the search path is
15411     empty).  This is the schema that will be used for any tables or
15412     other named objects that are created without specifying a target schema.
15413     <function>current_schemas(boolean)</function> returns an array of the names of all
15414     schemas presently in the search path.  The Boolean option determines whether or not
15415     implicitly included system schemas such as <literal>pg_catalog</> are included in the
15416     returned search path.
15417    </para>
15418
15419    <note>
15420     <para>
15421      The search path can be altered at run time.  The command is:
15422 <programlisting>
15423 SET search_path TO <replaceable>schema</> <optional>, <replaceable>schema</>, ...</optional>
15424 </programlisting>
15425     </para>
15426    </note>
15427
15428    <indexterm>
15429     <primary>inet_client_addr</primary>
15430    </indexterm>
15431
15432    <indexterm>
15433     <primary>inet_client_port</primary>
15434    </indexterm>
15435
15436    <indexterm>
15437     <primary>inet_server_addr</primary>
15438    </indexterm>
15439
15440    <indexterm>
15441     <primary>inet_server_port</primary>
15442    </indexterm>
15443
15444    <para>
15445      <function>inet_client_addr</function> returns the IP address of the
15446      current client, and <function>inet_client_port</function> returns the
15447      port number.
15448      <function>inet_server_addr</function> returns the IP address on which
15449      the server accepted the current connection, and
15450      <function>inet_server_port</function> returns the port number.
15451      All these functions return NULL if the current connection is via a
15452      Unix-domain socket.
15453    </para>
15454
15455    <indexterm>
15456     <primary>pg_blocking_pids</primary>
15457    </indexterm>
15458
15459    <para>
15460     <function>pg_blocking_pids</function> returns an array of the process IDs
15461     of the sessions that are blocking the server process with the specified
15462     process ID, or an empty array if there is no such server process or it is
15463     not blocked.  One server process blocks another if it either holds a lock
15464     that conflicts with the blocked process's lock request (hard block), or is
15465     waiting for a lock that would conflict with the blocked process's lock
15466     request and is ahead of it in the wait queue (soft block).  When using
15467     parallel queries the result always lists client-visible process IDs (that
15468     is, <function>pg_backend_pid</> results) even if the actual lock is held
15469     or awaited by a child worker process.  As a result of that, there may be
15470     duplicated PIDs in the result.  Also note that when a prepared transaction
15471     holds a conflicting lock, it will be represented by a zero process ID in
15472     the result of this function.
15473     Frequent calls to this function could have some impact on database
15474     performance, because it needs exclusive access to the lock manager's
15475     shared state for a short time.
15476    </para>
15477
15478    <indexterm>
15479     <primary>pg_conf_load_time</primary>
15480    </indexterm>
15481
15482    <para>
15483     <function>pg_conf_load_time</function> returns the
15484     <type>timestamp with time zone</type> when the
15485     server configuration files were last loaded.
15486     (If the current session was alive at the time, this will be the time
15487     when the session itself re-read the configuration files, so the
15488     reading will vary a little in different sessions.  Otherwise it is
15489     the time when the postmaster process re-read the configuration files.)
15490    </para>
15491
15492    <indexterm>
15493     <primary>pg_my_temp_schema</primary>
15494    </indexterm>
15495
15496    <indexterm>
15497     <primary>pg_is_other_temp_schema</primary>
15498    </indexterm>
15499
15500    <para>
15501     <function>pg_my_temp_schema</function> returns the OID of the current
15502     session's temporary schema, or zero if it has none (because it has not
15503     created any temporary tables).
15504     <function>pg_is_other_temp_schema</function> returns true if the
15505     given OID is the OID of another session's temporary schema.
15506     (This can be useful, for example, to exclude other sessions' temporary
15507     tables from a catalog display.)
15508    </para>
15509
15510    <indexterm>
15511     <primary>pg_listening_channels</primary>
15512    </indexterm>
15513
15514    <indexterm>
15515     <primary>pg_notification_queue_usage</primary>
15516    </indexterm>
15517
15518    <para>
15519     <function>pg_listening_channels</function> returns a set of names of
15520     asynchronous notification channels that the current session is listening
15521     to.  <function>pg_notification_queue_usage</function> returns the
15522     fraction of the total available space for notifications currently
15523     occupied by notifications that are waiting to be processed, as a
15524     <type>double</type> in the range 0-1.
15525     See <xref linkend="sql-listen"> and <xref linkend="sql-notify">
15526     for more information.
15527    </para>
15528
15529    <indexterm>
15530     <primary>pg_postmaster_start_time</primary>
15531    </indexterm>
15532
15533    <para>
15534     <function>pg_postmaster_start_time</function> returns the
15535     <type>timestamp with time zone</type> when the
15536     server started.
15537    </para>
15538
15539    <indexterm>
15540     <primary>version</primary>
15541    </indexterm>
15542
15543    <para>
15544     <function>version</function> returns a string describing the
15545     <productname>PostgreSQL</productname> server's version. You can also
15546     get this information from <xref linkend="guc-server-version"> or
15547     for a machine-readable version, <xref linkend="guc-server-version-num">.
15548     Software developers should use <literal>server_version_num</literal>
15549     (available since 8.2) or <xref linkend="libpq-pqserverversion"> instead
15550     of parsing the text version.
15551    </para>
15552
15553   <indexterm>
15554    <primary>privilege</primary>
15555    <secondary>querying</secondary>
15556   </indexterm>
15557
15558   <para>
15559    <xref linkend="functions-info-access-table"> lists functions that
15560    allow the user to query object access privileges programmatically.
15561    See <xref linkend="ddl-priv"> for more information about
15562    privileges.
15563   </para>
15564
15565    <table id="functions-info-access-table">
15566     <title>Access Privilege Inquiry Functions</title>
15567     <tgroup cols="3">
15568      <thead>
15569       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
15570      </thead>
15571
15572      <tbody>
15573       <row>
15574        <entry><literal><function>has_any_column_privilege</function>(<parameter>user</parameter>,
15575                                   <parameter>table</parameter>,
15576                                   <parameter>privilege</parameter>)</literal>
15577        </entry>
15578        <entry><type>boolean</type></entry>
15579        <entry>does user have privilege for any column of table</entry>
15580       </row>
15581       <row>
15582        <entry><literal><function>has_any_column_privilege</function>(<parameter>table</parameter>,
15583                                   <parameter>privilege</parameter>)</literal>
15584        </entry>
15585        <entry><type>boolean</type></entry>
15586        <entry>does current user have privilege for any column of table</entry>
15587       </row>
15588       <row>
15589        <entry><literal><function>has_column_privilege</function>(<parameter>user</parameter>,
15590                                   <parameter>table</parameter>,
15591                                   <parameter>column</parameter>,
15592                                   <parameter>privilege</parameter>)</literal>
15593        </entry>
15594        <entry><type>boolean</type></entry>
15595        <entry>does user have privilege for column</entry>
15596       </row>
15597       <row>
15598        <entry><literal><function>has_column_privilege</function>(<parameter>table</parameter>,
15599                                   <parameter>column</parameter>,
15600                                   <parameter>privilege</parameter>)</literal>
15601        </entry>
15602        <entry><type>boolean</type></entry>
15603        <entry>does current user have privilege for column</entry>
15604       </row>
15605       <row>
15606        <entry><literal><function>has_database_privilege</function>(<parameter>user</parameter>,
15607                                   <parameter>database</parameter>,
15608                                   <parameter>privilege</parameter>)</literal>
15609        </entry>
15610        <entry><type>boolean</type></entry>
15611        <entry>does user have privilege for database</entry>
15612       </row>
15613       <row>
15614        <entry><literal><function>has_database_privilege</function>(<parameter>database</parameter>,
15615                                   <parameter>privilege</parameter>)</literal>
15616        </entry>
15617        <entry><type>boolean</type></entry>
15618        <entry>does current user have privilege for database</entry>
15619       </row>
15620       <row>
15621        <entry><literal><function>has_foreign_data_wrapper_privilege</function>(<parameter>user</parameter>,
15622                                   <parameter>fdw</parameter>,
15623                                   <parameter>privilege</parameter>)</literal>
15624        </entry>
15625        <entry><type>boolean</type></entry>
15626        <entry>does user have privilege for foreign-data wrapper</entry>
15627       </row>
15628       <row>
15629        <entry><literal><function>has_foreign_data_wrapper_privilege</function>(<parameter>fdw</parameter>,
15630                                   <parameter>privilege</parameter>)</literal>
15631        </entry>
15632        <entry><type>boolean</type></entry>
15633        <entry>does current user have privilege for foreign-data wrapper</entry>
15634       </row>
15635       <row>
15636        <entry><literal><function>has_function_privilege</function>(<parameter>user</parameter>,
15637                                   <parameter>function</parameter>,
15638                                   <parameter>privilege</parameter>)</literal>
15639        </entry>
15640        <entry><type>boolean</type></entry>
15641        <entry>does user have privilege for function</entry>
15642       </row>
15643       <row>
15644        <entry><literal><function>has_function_privilege</function>(<parameter>function</parameter>,
15645                                   <parameter>privilege</parameter>)</literal>
15646        </entry>
15647        <entry><type>boolean</type></entry>
15648        <entry>does current user have privilege for function</entry>
15649       </row>
15650       <row>
15651        <entry><literal><function>has_language_privilege</function>(<parameter>user</parameter>,
15652                                   <parameter>language</parameter>,
15653                                   <parameter>privilege</parameter>)</literal>
15654        </entry>
15655        <entry><type>boolean</type></entry>
15656        <entry>does user have privilege for language</entry>
15657       </row>
15658       <row>
15659        <entry><literal><function>has_language_privilege</function>(<parameter>language</parameter>,
15660                                   <parameter>privilege</parameter>)</literal>
15661        </entry>
15662        <entry><type>boolean</type></entry>
15663        <entry>does current user have privilege for language</entry>
15664       </row>
15665       <row>
15666        <entry><literal><function>has_schema_privilege</function>(<parameter>user</parameter>,
15667                                   <parameter>schema</parameter>,
15668                                   <parameter>privilege</parameter>)</literal>
15669        </entry>
15670        <entry><type>boolean</type></entry>
15671        <entry>does user have privilege for schema</entry>
15672       </row>
15673       <row>
15674        <entry><literal><function>has_schema_privilege</function>(<parameter>schema</parameter>,
15675                                   <parameter>privilege</parameter>)</literal>
15676        </entry>
15677        <entry><type>boolean</type></entry>
15678        <entry>does current user have privilege for schema</entry>
15679       </row>
15680       <row>
15681        <entry><literal><function>has_sequence_privilege</function>(<parameter>user</parameter>,
15682                                   <parameter>sequence</parameter>,
15683                                   <parameter>privilege</parameter>)</literal>
15684        </entry>
15685        <entry><type>boolean</type></entry>
15686        <entry>does user have privilege for sequence</entry>
15687       </row>
15688       <row>
15689        <entry><literal><function>has_sequence_privilege</function>(<parameter>sequence</parameter>,
15690                                   <parameter>privilege</parameter>)</literal>
15691        </entry>
15692        <entry><type>boolean</type></entry>
15693        <entry>does current user have privilege for sequence</entry>
15694       </row>
15695       <row>
15696        <entry><literal><function>has_server_privilege</function>(<parameter>user</parameter>,
15697                                   <parameter>server</parameter>,
15698                                   <parameter>privilege</parameter>)</literal>
15699        </entry>
15700        <entry><type>boolean</type></entry>
15701        <entry>does user have privilege for foreign server</entry>
15702       </row>
15703       <row>
15704        <entry><literal><function>has_server_privilege</function>(<parameter>server</parameter>,
15705                                   <parameter>privilege</parameter>)</literal>
15706        </entry>
15707        <entry><type>boolean</type></entry>
15708        <entry>does current user have privilege for foreign server</entry>
15709       </row>
15710       <row>
15711        <entry><literal><function>has_table_privilege</function>(<parameter>user</parameter>,
15712                                   <parameter>table</parameter>,
15713                                   <parameter>privilege</parameter>)</literal>
15714        </entry>
15715        <entry><type>boolean</type></entry>
15716        <entry>does user have privilege for table</entry>
15717       </row>
15718       <row>
15719        <entry><literal><function>has_table_privilege</function>(<parameter>table</parameter>,
15720                                   <parameter>privilege</parameter>)</literal>
15721        </entry>
15722        <entry><type>boolean</type></entry>
15723        <entry>does current user have privilege for table</entry>
15724       </row>
15725       <row>
15726        <entry><literal><function>has_tablespace_privilege</function>(<parameter>user</parameter>,
15727                                   <parameter>tablespace</parameter>,
15728                                   <parameter>privilege</parameter>)</literal>
15729        </entry>
15730        <entry><type>boolean</type></entry>
15731        <entry>does user have privilege for tablespace</entry>
15732       </row>
15733       <row>
15734        <entry><literal><function>has_tablespace_privilege</function>(<parameter>tablespace</parameter>,
15735                                   <parameter>privilege</parameter>)</literal>
15736        </entry>
15737        <entry><type>boolean</type></entry>
15738        <entry>does current user have privilege for tablespace</entry>
15739       </row>
15740       <row>
15741        <entry><literal><function>pg_has_role</function>(<parameter>user</parameter>,
15742                                   <parameter>role</parameter>,
15743                                   <parameter>privilege</parameter>)</literal>
15744        </entry>
15745        <entry><type>boolean</type></entry>
15746        <entry>does user have privilege for role</entry>
15747       </row>
15748       <row>
15749        <entry><literal><function>pg_has_role</function>(<parameter>role</parameter>,
15750                                   <parameter>privilege</parameter>)</literal>
15751        </entry>
15752        <entry><type>boolean</type></entry>
15753        <entry>does current user have privilege for role</entry>
15754       </row>
15755       <row>
15756        <entry><literal><function>row_security_active</function>(<parameter>table</parameter>)</literal>
15757        </entry>
15758        <entry><type>boolean</type></entry>
15759        <entry>does current user have row level security active for table</entry>
15760       </row>
15761      </tbody>
15762     </tgroup>
15763    </table>
15764
15765    <indexterm>
15766     <primary>has_any_column_privilege</primary>
15767    </indexterm>
15768    <indexterm>
15769     <primary>has_column_privilege</primary>
15770    </indexterm>
15771    <indexterm>
15772     <primary>has_database_privilege</primary>
15773    </indexterm>
15774    <indexterm>
15775     <primary>has_function_privilege</primary>
15776    </indexterm>
15777    <indexterm>
15778     <primary>has_foreign_data_wrapper_privilege</primary>
15779    </indexterm>
15780    <indexterm>
15781     <primary>has_language_privilege</primary>
15782    </indexterm>
15783    <indexterm>
15784     <primary>has_schema_privilege</primary>
15785    </indexterm>
15786    <indexterm>
15787     <primary>has_server_privilege</primary>
15788    </indexterm>
15789    <indexterm>
15790     <primary>has_sequence_privilege</primary>
15791    </indexterm>
15792    <indexterm>
15793     <primary>has_table_privilege</primary>
15794    </indexterm>
15795    <indexterm>
15796     <primary>has_tablespace_privilege</primary>
15797    </indexterm>
15798    <indexterm>
15799     <primary>pg_has_role</primary>
15800    </indexterm>
15801    <indexterm>
15802     <primary>row_security_active</primary>
15803    </indexterm>
15804
15805    <para>
15806     <function>has_table_privilege</function> checks whether a user
15807     can access a table in a particular way.  The user can be
15808     specified by name, by OID (<literal>pg_authid.oid</literal>),
15809     <literal>public</> to indicate the PUBLIC pseudo-role, or if the argument is
15810     omitted
15811     <function>current_user</function> is assumed.  The table can be specified
15812     by name or by OID.  (Thus, there are actually six variants of
15813     <function>has_table_privilege</function>, which can be distinguished by
15814     the number and types of their arguments.)  When specifying by name,
15815     the name can be schema-qualified if necessary.
15816     The desired access privilege type
15817     is specified by a text string, which must evaluate to one of the
15818     values <literal>SELECT</literal>, <literal>INSERT</literal>,
15819     <literal>UPDATE</literal>, <literal>DELETE</literal>, <literal>TRUNCATE</>,
15820     <literal>REFERENCES</literal>, or <literal>TRIGGER</literal>.  Optionally,
15821     <literal>WITH GRANT OPTION</> can be added to a privilege type to test
15822     whether the privilege is held with grant option.  Also, multiple privilege
15823     types can be listed separated by commas, in which case the result will
15824     be <literal>true</> if any of the listed privileges is held.
15825     (Case of the privilege string is not significant, and extra whitespace
15826     is allowed between but not within privilege names.)
15827     Some examples:
15828 <programlisting>
15829 SELECT has_table_privilege('myschema.mytable', 'select');
15830 SELECT has_table_privilege('joe', 'mytable', 'INSERT, SELECT WITH GRANT OPTION');
15831 </programlisting>
15832    </para>
15833
15834    <para>
15835     <function>has_sequence_privilege</function> checks whether a user
15836     can access a sequence in a particular way.  The possibilities for its
15837     arguments are analogous to <function>has_table_privilege</function>.
15838     The desired access privilege type must evaluate to one of
15839     <literal>USAGE</literal>,
15840     <literal>SELECT</literal>, or
15841     <literal>UPDATE</literal>.
15842    </para>
15843
15844    <para>
15845     <function>has_any_column_privilege</function> checks whether a user can
15846     access any column of a table in a particular way.
15847     Its argument possibilities
15848     are analogous to <function>has_table_privilege</>,
15849     except that the desired access privilege type must evaluate to some
15850     combination of
15851     <literal>SELECT</literal>,
15852     <literal>INSERT</literal>,
15853     <literal>UPDATE</literal>, or
15854     <literal>REFERENCES</literal>.  Note that having any of these privileges
15855     at the table level implicitly grants it for each column of the table,
15856     so <function>has_any_column_privilege</function> will always return
15857     <literal>true</> if <function>has_table_privilege</> does for the same
15858     arguments.  But <function>has_any_column_privilege</> also succeeds if
15859     there is a column-level grant of the privilege for at least one column.
15860    </para>
15861
15862    <para>
15863     <function>has_column_privilege</function> checks whether a user
15864     can access a column in a particular way.
15865     Its argument possibilities
15866     are analogous to <function>has_table_privilege</function>,
15867     with the addition that the column can be specified either by name
15868     or attribute number.
15869     The desired access privilege type must evaluate to some combination of
15870     <literal>SELECT</literal>,
15871     <literal>INSERT</literal>,
15872     <literal>UPDATE</literal>, or
15873     <literal>REFERENCES</literal>.  Note that having any of these privileges
15874     at the table level implicitly grants it for each column of the table.
15875    </para>
15876
15877    <para>
15878     <function>has_database_privilege</function> checks whether a user
15879     can access a database in a particular way.
15880     Its argument possibilities
15881     are analogous to <function>has_table_privilege</function>.
15882     The desired access privilege type must evaluate to some combination of
15883     <literal>CREATE</literal>,
15884     <literal>CONNECT</literal>,
15885     <literal>TEMPORARY</literal>, or
15886     <literal>TEMP</literal> (which is equivalent to
15887     <literal>TEMPORARY</literal>).
15888    </para>
15889
15890    <para>
15891     <function>has_function_privilege</function> checks whether a user
15892     can access a function in a particular way.
15893     Its argument possibilities
15894     are analogous to <function>has_table_privilege</function>.
15895     When specifying a function by a text string rather than by OID,
15896     the allowed input is the same as for the <type>regprocedure</> data type
15897     (see <xref linkend="datatype-oid">).
15898     The desired access privilege type must evaluate to
15899     <literal>EXECUTE</literal>.
15900     An example is:
15901 <programlisting>
15902 SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');
15903 </programlisting>
15904    </para>
15905
15906    <para>
15907     <function>has_foreign_data_wrapper_privilege</function> checks whether a user
15908     can access a foreign-data wrapper in a particular way.
15909     Its argument possibilities
15910     are analogous to <function>has_table_privilege</function>.
15911     The desired access privilege type must evaluate to
15912     <literal>USAGE</literal>.
15913    </para>
15914
15915    <para>
15916     <function>has_language_privilege</function> checks whether a user
15917     can access a procedural language in a particular way.
15918     Its argument possibilities
15919     are analogous to <function>has_table_privilege</function>.
15920     The desired access privilege type must evaluate to
15921     <literal>USAGE</literal>.
15922    </para>
15923
15924    <para>
15925     <function>has_schema_privilege</function> checks whether a user
15926     can access a schema in a particular way.
15927     Its argument possibilities
15928     are analogous to <function>has_table_privilege</function>.
15929     The desired access privilege type must evaluate to some combination of
15930     <literal>CREATE</literal> or
15931     <literal>USAGE</literal>.
15932    </para>
15933
15934    <para>
15935     <function>has_server_privilege</function> checks whether a user
15936     can access a foreign server in a particular way.
15937     Its argument possibilities
15938     are analogous to <function>has_table_privilege</function>.
15939     The desired access privilege type must evaluate to
15940     <literal>USAGE</literal>.
15941    </para>
15942
15943    <para>
15944     <function>has_tablespace_privilege</function> checks whether a user
15945     can access a tablespace in a particular way.
15946     Its argument possibilities
15947     are analogous to <function>has_table_privilege</function>.
15948     The desired access privilege type must evaluate to
15949     <literal>CREATE</literal>.
15950    </para>
15951
15952    <para>
15953     <function>pg_has_role</function> checks whether a user
15954     can access a role in a particular way.
15955     Its argument possibilities
15956     are analogous to <function>has_table_privilege</function>,
15957     except that <literal>public</> is not allowed as a user name.
15958     The desired access privilege type must evaluate to some combination of
15959     <literal>MEMBER</literal> or
15960     <literal>USAGE</literal>.
15961     <literal>MEMBER</literal> denotes direct or indirect membership in
15962     the role (that is, the right to do <command>SET ROLE</>), while
15963     <literal>USAGE</literal> denotes whether the privileges of the role
15964     are immediately available without doing <command>SET ROLE</>.
15965    </para>
15966
15967    <para>
15968     <function>row_security_active</function> checks whether row level
15969     security is active for the specified table in the context of the
15970     <function>current_user</function> and environment. The table can
15971     be specified by name or by OID.
15972    </para>
15973
15974   <para>
15975    <xref linkend="functions-info-schema-table"> shows functions that
15976    determine whether a certain object is <firstterm>visible</> in the
15977    current schema search path.
15978    For example, a table is said to be visible if its
15979    containing schema is in the search path and no table of the same
15980    name appears earlier in the search path.  This is equivalent to the
15981    statement that the table can be referenced by name without explicit
15982    schema qualification.  To list the names of all visible tables:
15983 <programlisting>
15984 SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
15985 </programlisting>
15986   </para>
15987
15988    <indexterm>
15989     <primary>search path</primary>
15990     <secondary>object visibility</secondary>
15991    </indexterm>
15992
15993    <table id="functions-info-schema-table">
15994     <title>Schema Visibility Inquiry Functions</title>
15995     <tgroup cols="3">
15996      <thead>
15997       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
15998      </thead>
15999
16000      <tbody>
16001       <row>
16002        <entry><literal><function>pg_collation_is_visible(<parameter>collation_oid</parameter>)</function></literal>
16003        </entry>
16004        <entry><type>boolean</type></entry>
16005        <entry>is collation visible in search path</entry>
16006       </row>
16007       <row>
16008        <entry><literal><function>pg_conversion_is_visible(<parameter>conversion_oid</parameter>)</function></literal>
16009        </entry>
16010        <entry><type>boolean</type></entry>
16011        <entry>is conversion visible in search path</entry>
16012       </row>
16013       <row>
16014        <entry><literal><function>pg_function_is_visible(<parameter>function_oid</parameter>)</function></literal>
16015        </entry>
16016        <entry><type>boolean</type></entry>
16017        <entry>is function visible in search path</entry>
16018       </row>
16019       <row>
16020        <entry><literal><function>pg_opclass_is_visible(<parameter>opclass_oid</parameter>)</function></literal>
16021        </entry>
16022        <entry><type>boolean</type></entry>
16023        <entry>is operator class visible in search path</entry>
16024       </row>
16025       <row>
16026        <entry><literal><function>pg_operator_is_visible(<parameter>operator_oid</parameter>)</function></literal>
16027        </entry>
16028        <entry><type>boolean</type></entry>
16029        <entry>is operator visible in search path</entry>
16030       </row>
16031       <row>
16032        <entry><literal><function>pg_opfamily_is_visible(<parameter>opclass_oid</parameter>)</function></literal>
16033        </entry>
16034        <entry><type>boolean</type></entry>
16035        <entry>is operator family visible in search path</entry>
16036       </row>
16037       <row>
16038        <entry><literal><function>pg_table_is_visible(<parameter>table_oid</parameter>)</function></literal>
16039        </entry>
16040        <entry><type>boolean</type></entry>
16041        <entry>is table visible in search path</entry>
16042       </row>
16043       <row>
16044        <entry><literal><function>pg_ts_config_is_visible(<parameter>config_oid</parameter>)</function></literal>
16045        </entry>
16046        <entry><type>boolean</type></entry>
16047        <entry>is text search configuration visible in search path</entry>
16048       </row>
16049       <row>
16050        <entry><literal><function>pg_ts_dict_is_visible(<parameter>dict_oid</parameter>)</function></literal>
16051        </entry>
16052        <entry><type>boolean</type></entry>
16053        <entry>is text search dictionary visible in search path</entry>
16054       </row>
16055       <row>
16056        <entry><literal><function>pg_ts_parser_is_visible(<parameter>parser_oid</parameter>)</function></literal>
16057        </entry>
16058        <entry><type>boolean</type></entry>
16059        <entry>is text search parser visible in search path</entry>
16060       </row>
16061       <row>
16062        <entry><literal><function>pg_ts_template_is_visible(<parameter>template_oid</parameter>)</function></literal>
16063        </entry>
16064        <entry><type>boolean</type></entry>
16065        <entry>is text search template visible in search path</entry>
16066       </row>
16067       <row>
16068        <entry><literal><function>pg_type_is_visible(<parameter>type_oid</parameter>)</function></literal>
16069        </entry>
16070        <entry><type>boolean</type></entry>
16071        <entry>is type (or domain) visible in search path</entry>
16072       </row>
16073      </tbody>
16074     </tgroup>
16075    </table>
16076
16077    <indexterm>
16078     <primary>pg_collation_is_visible</primary>
16079    </indexterm>
16080    <indexterm>
16081     <primary>pg_conversion_is_visible</primary>
16082    </indexterm>
16083    <indexterm>
16084     <primary>pg_function_is_visible</primary>
16085    </indexterm>
16086    <indexterm>
16087     <primary>pg_opclass_is_visible</primary>
16088    </indexterm>
16089    <indexterm>
16090     <primary>pg_operator_is_visible</primary>
16091    </indexterm>
16092    <indexterm>
16093     <primary>pg_opfamily_is_visible</primary>
16094    </indexterm>
16095    <indexterm>
16096     <primary>pg_table_is_visible</primary>
16097    </indexterm>
16098    <indexterm>
16099     <primary>pg_ts_config_is_visible</primary>
16100    </indexterm>
16101    <indexterm>
16102     <primary>pg_ts_dict_is_visible</primary>
16103    </indexterm>
16104    <indexterm>
16105     <primary>pg_ts_parser_is_visible</primary>
16106    </indexterm>
16107    <indexterm>
16108     <primary>pg_ts_template_is_visible</primary>
16109    </indexterm>
16110    <indexterm>
16111     <primary>pg_type_is_visible</primary>
16112    </indexterm>
16113
16114    <para>
16115     Each function performs the visibility check for one type of database
16116     object.  Note that <function>pg_table_is_visible</function> can also be used
16117     with views, materialized views, indexes, sequences and foreign tables;
16118     <function>pg_type_is_visible</function> can also be used with domains.
16119     For functions and operators, an object in
16120     the search path is visible if there is no object of the same name
16121     <emphasis>and argument data type(s)</> earlier in the path.  For operator
16122     classes, both name and associated index access method are considered.
16123    </para>
16124
16125    <para>
16126     All these functions require object OIDs to identify the object to be
16127     checked.  If you want to test an object by name, it is convenient to use
16128     the OID alias types (<type>regclass</>, <type>regtype</>,
16129     <type>regprocedure</>, <type>regoperator</>, <type>regconfig</>,
16130     or <type>regdictionary</>),
16131     for example:
16132 <programlisting>
16133 SELECT pg_type_is_visible('myschema.widget'::regtype);
16134 </programlisting>
16135     Note that it would not make much sense to test a non-schema-qualified
16136     type name in this way &mdash; if the name can be recognized at all, it must be visible.
16137    </para>
16138
16139    <indexterm>
16140     <primary>format_type</primary>
16141    </indexterm>
16142
16143    <indexterm>
16144     <primary>pg_get_constraintdef</primary>
16145    </indexterm>
16146
16147    <indexterm>
16148     <primary>pg_get_expr</primary>
16149    </indexterm>
16150
16151    <indexterm>
16152     <primary>pg_get_functiondef</primary>
16153    </indexterm>
16154
16155    <indexterm>
16156     <primary>pg_get_function_arguments</primary>
16157    </indexterm>
16158
16159    <indexterm>
16160     <primary>pg_get_function_identity_arguments</primary>
16161    </indexterm>
16162
16163    <indexterm>
16164     <primary>pg_get_function_result</primary>
16165    </indexterm>
16166
16167    <indexterm>
16168     <primary>pg_get_indexdef</primary>
16169    </indexterm>
16170
16171    <indexterm>
16172     <primary>pg_get_keywords</primary>
16173    </indexterm>
16174
16175    <indexterm>
16176     <primary>pg_get_ruledef</primary>
16177    </indexterm>
16178
16179    <indexterm>
16180     <primary>pg_get_serial_sequence</primary>
16181    </indexterm>
16182
16183    <indexterm>
16184     <primary>pg_get_triggerdef</primary>
16185    </indexterm>
16186
16187    <indexterm>
16188     <primary>pg_get_userbyid</primary>
16189    </indexterm>
16190
16191    <indexterm>
16192     <primary>pg_get_viewdef</primary>
16193    </indexterm>
16194
16195    <indexterm>
16196     <primary>pg_options_to_table</primary>
16197    </indexterm>
16198
16199    <indexterm>
16200     <primary>pg_tablespace_databases</primary>
16201    </indexterm>
16202
16203    <indexterm>
16204     <primary>pg_tablespace_location</primary>
16205    </indexterm>
16206
16207    <indexterm>
16208     <primary>pg_typeof</primary>
16209    </indexterm>
16210
16211    <indexterm>
16212     <primary>collation for</primary>
16213    </indexterm>
16214
16215    <indexterm>
16216     <primary>to_regclass</primary>
16217    </indexterm>
16218
16219    <indexterm>
16220     <primary>to_regproc</primary>
16221    </indexterm>
16222
16223    <indexterm>
16224     <primary>to_regprocedure</primary>
16225    </indexterm>
16226
16227    <indexterm>
16228     <primary>to_regoper</primary>
16229    </indexterm>
16230
16231    <indexterm>
16232     <primary>to_regoperator</primary>
16233    </indexterm>
16234
16235    <indexterm>
16236     <primary>to_regtype</primary>
16237    </indexterm>
16238
16239    <indexterm>
16240     <primary>to_regnamespace</primary>
16241    </indexterm>
16242
16243    <indexterm>
16244     <primary>to_regrole</primary>
16245    </indexterm>
16246
16247   <para>
16248    <xref linkend="functions-info-catalog-table"> lists functions that
16249    extract information from the system catalogs.
16250   </para>
16251
16252    <table id="functions-info-catalog-table">
16253     <title>System Catalog Information Functions</title>
16254     <tgroup cols="3">
16255      <thead>
16256       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16257      </thead>
16258
16259      <tbody>
16260       <row>
16261        <entry><literal><function>format_type(<parameter>type_oid</parameter>, <parameter>typemod</>)</function></literal></entry>
16262        <entry><type>text</type></entry>
16263        <entry>get SQL name of a data type</entry>
16264       </row>
16265       <row>
16266        <entry><literal><function>pg_get_constraintdef(<parameter>constraint_oid</parameter>)</function></literal></entry>
16267        <entry><type>text</type></entry>
16268        <entry>get definition of a constraint</entry>
16269       </row>
16270       <row>
16271        <entry><literal><function>pg_get_constraintdef(<parameter>constraint_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16272        <entry><type>text</type></entry>
16273        <entry>get definition of a constraint</entry>
16274       </row>
16275       <row>
16276        <entry><literal><function>pg_get_expr(<parameter>pg_node_tree</parameter>, <parameter>relation_oid</>)</function></literal></entry>
16277        <entry><type>text</type></entry>
16278        <entry>decompile internal form of an expression, assuming that any Vars
16279        in it refer to the relation indicated by the second parameter</entry>
16280       </row>
16281       <row>
16282        <entry><literal><function>pg_get_expr(<parameter>pg_node_tree</parameter>, <parameter>relation_oid</>, <parameter>pretty_bool</>)</function></literal></entry>
16283        <entry><type>text</type></entry>
16284        <entry>decompile internal form of an expression, assuming that any Vars
16285        in it refer to the relation indicated by the second parameter</entry>
16286       </row>
16287       <row>
16288        <entry><literal><function>pg_get_functiondef(<parameter>func_oid</parameter>)</function></literal></entry>
16289        <entry><type>text</type></entry>
16290        <entry>get definition of a function</entry>
16291       </row>
16292       <row>
16293        <entry><literal><function>pg_get_function_arguments(<parameter>func_oid</parameter>)</function></literal></entry>
16294        <entry><type>text</type></entry>
16295        <entry>get argument list of function's definition (with default values)</entry>
16296       </row>
16297       <row>
16298        <entry><literal><function>pg_get_function_identity_arguments(<parameter>func_oid</parameter>)</function></literal></entry>
16299        <entry><type>text</type></entry>
16300        <entry>get argument list to identify a function (without default values)</entry>
16301       </row>
16302       <row>
16303        <entry><literal><function>pg_get_function_result(<parameter>func_oid</parameter>)</function></literal></entry>
16304        <entry><type>text</type></entry>
16305        <entry>get <literal>RETURNS</> clause for function</entry>
16306       </row>
16307       <row>
16308        <entry><literal><function>pg_get_indexdef(<parameter>index_oid</parameter>)</function></literal></entry>
16309        <entry><type>text</type></entry>
16310        <entry>get <command>CREATE INDEX</> command for index</entry>
16311       </row>
16312       <row>
16313        <entry><literal><function>pg_get_indexdef(<parameter>index_oid</parameter>, <parameter>column_no</>, <parameter>pretty_bool</>)</function></literal></entry>
16314        <entry><type>text</type></entry>
16315        <entry>get <command>CREATE INDEX</> command for index,
16316        or definition of just one index column when
16317        <parameter>column_no</> is not zero</entry>
16318       </row>
16319       <row>
16320        <entry><literal><function>pg_get_keywords()</function></literal></entry>
16321        <entry><type>setof record</type></entry>
16322        <entry>get list of SQL keywords and their categories</entry>
16323       </row>
16324       <row>
16325        <entry><literal><function>pg_get_ruledef(<parameter>rule_oid</parameter>)</function></literal></entry>
16326        <entry><type>text</type></entry>
16327        <entry>get <command>CREATE RULE</> command for rule</entry>
16328       </row>
16329       <row>
16330        <entry><literal><function>pg_get_ruledef(<parameter>rule_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16331        <entry><type>text</type></entry>
16332        <entry>get <command>CREATE RULE</> command for rule</entry>
16333       </row>
16334       <row>
16335        <entry><literal><function>pg_get_serial_sequence(<parameter>table_name</parameter>, <parameter>column_name</parameter>)</function></literal></entry>
16336        <entry><type>text</type></entry>
16337        <entry>get name of the sequence that a <type>serial</type>, <type>smallserial</type> or <type>bigserial</type> column
16338        uses</entry>
16339       </row>
16340       <row>
16341        <entry><function>pg_get_triggerdef</function>(<parameter>trigger_oid</parameter>)</entry>
16342        <entry><type>text</type></entry>
16343        <entry>get <command>CREATE [ CONSTRAINT ] TRIGGER</> command for trigger</entry>
16344       </row>
16345       <row>
16346        <entry><function>pg_get_triggerdef</function>(<parameter>trigger_oid</parameter>, <parameter>pretty_bool</>)</entry>
16347        <entry><type>text</type></entry>
16348        <entry>get <command>CREATE [ CONSTRAINT ] TRIGGER</> command for trigger</entry>
16349       </row>
16350       <row>
16351        <entry><literal><function>pg_get_userbyid(<parameter>role_oid</parameter>)</function></literal></entry>
16352        <entry><type>name</type></entry>
16353        <entry>get role name with given OID</entry>
16354       </row>
16355       <row>
16356        <entry><literal><function>pg_get_viewdef(<parameter>view_name</parameter>)</function></literal></entry>
16357        <entry><type>text</type></entry>
16358        <entry>get underlying <command>SELECT</command> command for view or materialized view (<emphasis>deprecated</emphasis>)</entry>
16359       </row>
16360       <row>
16361        <entry><literal><function>pg_get_viewdef(<parameter>view_name</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16362        <entry><type>text</type></entry>
16363        <entry>get underlying <command>SELECT</command> command for view or materialized view (<emphasis>deprecated</emphasis>)</entry>
16364       </row>
16365       <row>
16366        <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>)</function></literal></entry>
16367        <entry><type>text</type></entry>
16368        <entry>get underlying <command>SELECT</command> command for view or materialized view</entry>
16369       </row>
16370       <row>
16371        <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
16372        <entry><type>text</type></entry>
16373        <entry>get underlying <command>SELECT</command> command for view or materialized view</entry>
16374       </row>
16375       <row>
16376        <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>, <parameter>wrap_column_int</>)</function></literal></entry>
16377        <entry><type>text</type></entry>
16378        <entry>get underlying <command>SELECT</command> command for view or
16379               materialized view; lines with fields are wrapped to specified
16380               number of columns, pretty-printing is implied</entry>
16381       </row>
16382       <row>
16383        <entry><literal><function>pg_options_to_table(<parameter>reloptions</parameter>)</function></literal></entry>
16384        <entry><type>setof record</type></entry>
16385        <entry>get the set of storage option name/value pairs</entry>
16386       </row>
16387       <row>
16388        <entry><literal><function>pg_tablespace_databases(<parameter>tablespace_oid</parameter>)</function></literal></entry>
16389        <entry><type>setof oid</type></entry>
16390        <entry>get the set of database OIDs that have objects in the tablespace</entry>
16391       </row>
16392       <row>
16393        <entry><literal><function>pg_tablespace_location(<parameter>tablespace_oid</parameter>)</function></literal></entry>
16394        <entry><type>text</type></entry>
16395        <entry>get the path in the file system that this tablespace is located in</entry>
16396       </row>
16397       <row>
16398        <entry><literal><function>pg_typeof(<parameter>any</parameter>)</function></literal></entry>
16399        <entry><type>regtype</type></entry>
16400        <entry>get the data type of any value</entry>
16401       </row>
16402       <row>
16403        <entry><literal><function>collation for (<parameter>any</parameter>)</function></literal></entry>
16404        <entry><type>text</type></entry>
16405        <entry>get the collation of the argument</entry>
16406       </row>
16407       <row>
16408        <entry><literal><function>to_regclass(<parameter>rel_name</parameter>)</function></literal></entry>
16409        <entry><type>regclass</type></entry>
16410        <entry>get the OID of the named relation</entry>
16411       </row>
16412       <row>
16413        <entry><literal><function>to_regproc(<parameter>func_name</parameter>)</function></literal></entry>
16414        <entry><type>regproc</type></entry>
16415        <entry>get the OID of the named function</entry>
16416       </row>
16417       <row>
16418        <entry><literal><function>to_regprocedure(<parameter>func_name</parameter>)</function></literal></entry>
16419        <entry><type>regprocedure</type></entry>
16420        <entry>get the OID of the named function</entry>
16421       </row>
16422       <row>
16423        <entry><literal><function>to_regoper(<parameter>operator_name</parameter>)</function></literal></entry>
16424        <entry><type>regoper</type></entry>
16425        <entry>get the OID of the named operator</entry>
16426       </row>
16427       <row>
16428        <entry><literal><function>to_regoperator(<parameter>operator_name</parameter>)</function></literal></entry>
16429        <entry><type>regoperator</type></entry>
16430        <entry>get the OID of the named operator</entry>
16431       </row>
16432       <row>
16433        <entry><literal><function>to_regtype(<parameter>type_name</parameter>)</function></literal></entry>
16434        <entry><type>regtype</type></entry>
16435        <entry>get the OID of the named type</entry>
16436       </row>
16437       <row>
16438        <entry><literal><function>to_regnamespace(<parameter>schema_name</parameter>)</function></literal></entry>
16439        <entry><type>regnamespace</type></entry>
16440        <entry>get the OID of the named schema</entry>
16441       </row>
16442       <row>
16443        <entry><literal><function>to_regrole(<parameter>role_name</parameter>)</function></literal></entry>
16444        <entry><type>regrole</type></entry>
16445        <entry>get the OID of the named role</entry>
16446       </row>
16447      </tbody>
16448     </tgroup>
16449    </table>
16450
16451   <para>
16452    <function>format_type</function> returns the SQL name of a data type that
16453    is identified by its type OID and possibly a type modifier.  Pass NULL
16454    for the type modifier if no specific modifier is known.
16455   </para>
16456
16457   <para>
16458    <function>pg_get_keywords</function> returns a set of records describing
16459    the SQL keywords recognized by the server. The <structfield>word</> column
16460    contains the keyword.  The <structfield>catcode</> column contains a
16461    category code: <literal>U</> for unreserved, <literal>C</> for column name,
16462    <literal>T</> for type or function name, or <literal>R</> for reserved.
16463    The <structfield>catdesc</> column contains a possibly-localized string
16464    describing the category.
16465   </para>
16466
16467   <para>
16468    <function>pg_get_constraintdef</function>,
16469    <function>pg_get_indexdef</function>, <function>pg_get_ruledef</function>,
16470    and <function>pg_get_triggerdef</function>, respectively reconstruct the
16471    creating command for a constraint, index, rule, or trigger. (Note that this
16472    is a decompiled reconstruction, not the original text of the command.)
16473    <function>pg_get_expr</function> decompiles the internal form of an
16474    individual expression, such as the default value for a column.  It can be
16475    useful when examining the contents of system catalogs.  If the expression
16476    might contain Vars, specify the OID of the relation they refer to as the
16477    second parameter; if no Vars are expected, zero is sufficient.
16478    <function>pg_get_viewdef</function> reconstructs the <command>SELECT</>
16479    query that defines a view. Most of these functions come in two variants,
16480    one of which can optionally <quote>pretty-print</> the result.  The
16481    pretty-printed format is more readable, but the default format is more
16482    likely to be interpreted the same way by future versions of
16483    <productname>PostgreSQL</>; avoid using pretty-printed output for dump
16484    purposes.  Passing <literal>false</> for the pretty-print parameter yields
16485    the same result as the variant that does not have the parameter at all.
16486   </para>
16487
16488   <para>
16489    <function>pg_get_functiondef</> returns a complete
16490    <command>CREATE OR REPLACE FUNCTION</> statement for a function.
16491    <function>pg_get_function_arguments</function> returns the argument list
16492    of a function, in the form it would need to appear in within
16493    <command>CREATE FUNCTION</>.
16494    <function>pg_get_function_result</function> similarly returns the
16495    appropriate <literal>RETURNS</> clause for the function.
16496    <function>pg_get_function_identity_arguments</function> returns the
16497    argument list necessary to identify a function, in the form it
16498    would need to appear in within <command>ALTER FUNCTION</>, for
16499    instance.  This form omits default values.
16500   </para>
16501
16502   <para>
16503    <function>pg_get_serial_sequence</function> returns the name of the
16504    sequence associated with a column, or NULL if no sequence is associated
16505    with the column.  The first input parameter is a table name with
16506    optional schema, and the second parameter is a column name.  Because
16507    the first parameter is potentially a schema and table, it is not treated
16508    as a double-quoted identifier, meaning it is lower cased by default,
16509    while the second parameter, being just a column name, is treated as
16510    double-quoted and has its case preserved.  The function returns a value
16511    suitably formatted for passing to sequence functions (see <xref
16512    linkend="functions-sequence">).  This association can be modified or
16513    removed with <command>ALTER SEQUENCE OWNED BY</>.  (The function
16514    probably should have been called
16515    <function>pg_get_owned_sequence</function>; its current name reflects the fact
16516    that it's typically used with <type>serial</> or <type>bigserial</>
16517    columns.)
16518   </para>
16519
16520   <para>
16521    <function>pg_get_userbyid</function> extracts a role's name given
16522    its OID.
16523   </para>
16524
16525   <para>
16526    <function>pg_options_to_table</function> returns the set of storage
16527    option name/value pairs
16528    (<literal>option_name</>/<literal>option_value</>) when passed
16529    <structname>pg_class</>.<structfield>reloptions</> or
16530    <structname>pg_attribute</>.<structfield>attoptions</>.
16531   </para>
16532
16533   <para>
16534    <function>pg_tablespace_databases</function> allows a tablespace to be
16535    examined. It returns the set of OIDs of databases that have objects stored
16536    in the tablespace. If this function returns any rows, the tablespace is not
16537    empty and cannot be dropped. To display the specific objects populating the
16538    tablespace, you will need to connect to the databases identified by
16539    <function>pg_tablespace_databases</function> and query their
16540    <structname>pg_class</> catalogs.
16541   </para>
16542
16543   <para>
16544    <function>pg_typeof</function> returns the OID of the data type of the
16545    value that is passed to it.  This can be helpful for troubleshooting or
16546    dynamically constructing SQL queries.  The function is declared as
16547    returning <type>regtype</>, which is an OID alias type (see
16548    <xref linkend="datatype-oid">); this means that it is the same as an
16549    OID for comparison purposes but displays as a type name.  For example:
16550 <programlisting>
16551 SELECT pg_typeof(33);
16552
16553  pg_typeof 
16554 -----------
16555  integer
16556 (1 row)
16557
16558 SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
16559  typlen 
16560 --------
16561       4
16562 (1 row)
16563 </programlisting>
16564   </para>
16565
16566   <para>
16567    The expression <literal>collation for</literal> returns the collation of the
16568    value that is passed to it.  Example:
16569 <programlisting>
16570 SELECT collation for (description) FROM pg_description LIMIT 1;
16571  pg_collation_for 
16572 ------------------
16573  "default"
16574 (1 row)
16575
16576 SELECT collation for ('foo' COLLATE "de_DE");
16577  pg_collation_for 
16578 ------------------
16579  "de_DE"
16580 (1 row)
16581 </programlisting>
16582   The value might be quoted and schema-qualified.  If no collation is derived
16583   for the argument expression, then a null value is returned.  If the argument
16584   is not of a collatable data type, then an error is raised.
16585   </para>
16586
16587   <para>
16588    The <function>to_regclass</function>, <function>to_regproc</function>,
16589    <function>to_regprocedure</function>, <function>to_regoper</function>,
16590    <function>to_regoperator</function>, <function>to_regtype</function>,
16591    <function>to_regnamespace</function>, and <function>to_regrole</function>
16592    functions translate relation, function, operator, type, schema, and role
16593    names (given as <type>text</>) to objects of
16594    type <type>regclass</>, <type>regproc</>, <type>regprocedure</type>,
16595    <type>regoper</>, <type>regoperator</type>, <type>regtype</>,
16596    <type>regnamespace</>, and <type>regrole</>
16597    respectively.  These functions differ from a cast from
16598    text in that they don't accept a numeric OID, and that they return null
16599    rather than throwing an error if the name is not found (or, for
16600    <function>to_regproc</function> and <function>to_regoper</function>, if
16601    the given name matches multiple objects).
16602   </para>
16603
16604    <indexterm>
16605     <primary>pg_describe_object</primary>
16606    </indexterm>
16607
16608    <indexterm>
16609     <primary>pg_identify_object</primary>
16610    </indexterm>
16611
16612    <indexterm>
16613     <primary>pg_identify_object_as_address</primary>
16614    </indexterm>
16615
16616    <indexterm>
16617     <primary>pg_get_object_address</primary>
16618    </indexterm>
16619
16620   <para>
16621    <xref linkend="functions-info-object-table"> lists functions related to
16622    database object identification and addressing.
16623   </para>
16624
16625    <table id="functions-info-object-table">
16626     <title>Object Information and Addressing Functions</title>
16627     <tgroup cols="3">
16628      <thead>
16629       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16630      </thead>
16631
16632      <tbody>
16633       <row>
16634        <entry><literal><function>pg_describe_object(<parameter>catalog_id</parameter>, <parameter>object_id</parameter>, <parameter>object_sub_id</parameter>)</function></literal></entry>
16635        <entry><type>text</type></entry>
16636        <entry>get description of a database object</entry>
16637       </row>
16638       <row>
16639        <entry><literal><function>pg_identify_object(<parameter>catalog_id</parameter> <type>oid</>, <parameter>object_id</parameter> <type>oid</>, <parameter>object_sub_id</parameter> <type>integer</>)</function></literal></entry>
16640        <entry><parameter>type</> <type>text</>, <parameter>schema</> <type>text</>, <parameter>name</> <type>text</>, <parameter>identity</> <type>text</></entry>
16641        <entry>get identity of a database object</entry>
16642       </row>
16643       <row>
16644        <entry><literal><function>pg_identify_object_as_address(<parameter>catalog_id</parameter> <type>oid</>, <parameter>object_id</parameter> <type>oid</>, <parameter>object_sub_id</parameter> <type>integer</>)</function></literal></entry>
16645        <entry><parameter>type</> <type>text</>, <parameter>name</> <type>text[]</>, <parameter>args</> <type>text[]</></entry>
16646        <entry>get external representation of a database object's address</entry>
16647       </row>
16648       <row>
16649        <entry><literal><function>pg_get_object_address(<parameter>type</parameter> <type>text</>, <parameter>name</parameter> <type>text[]</>, <parameter>args</parameter> <type>text[]</>)</function></literal></entry>
16650        <entry><parameter>catalog_id</> <type>oid</>, <parameter>object_id</> <type>oid</>, <parameter>object_sub_id</> <type>int32</></entry>
16651        <entry>get address of a database object, from its external representation</entry>
16652       </row>
16653      </tbody>
16654     </tgroup>
16655    </table>
16656
16657   <para>
16658    <function>pg_describe_object</function> returns a textual description of a database
16659    object specified by catalog OID, object OID and a (possibly zero) sub-object ID.
16660    This description is intended to be human-readable, and might be translated,
16661    depending on server configuration.
16662    This is useful to determine the identity of an object as stored in the
16663    <structname>pg_depend</structname> catalog.
16664   </para>
16665
16666   <para>
16667    <function>pg_identify_object</function> returns a row containing enough information
16668    to uniquely identify the database object specified by catalog OID, object OID and a
16669    (possibly zero) sub-object ID.  This information is intended to be machine-readable,
16670    and is never translated.
16671    <parameter>type</> identifies the type of database object;
16672    <parameter>schema</> is the schema name that the object belongs in, or
16673    <literal>NULL</> for object types that do not belong to schemas;
16674    <parameter>name</> is the name of the object, quoted if necessary, only
16675    present if it can be used (alongside schema name, if pertinent) as a unique
16676    identifier of the object, otherwise <literal>NULL</>;
16677    <parameter>identity</> is the complete object identity, with the precise format
16678    depending on object type, and each part within the format being
16679    schema-qualified and quoted as necessary.
16680   </para>
16681
16682   <para>
16683    <function>pg_identify_object_as_address</function> returns a row containing
16684    enough information to uniquely identify the database object specified by
16685    catalog OID, object OID and a (possibly zero) sub-object ID.  The returned
16686    information is independent of the current server, that is, it could be used
16687    to identify an identically named object in another server.
16688    <parameter>type</> identifies the type of database object;
16689    <parameter>name</> and <parameter>args</> are text arrays that together
16690    form a reference to the object.  These three columns can be passed to
16691    <function>pg_get_object_address</> to obtain the internal address
16692    of the object.
16693    This function is the inverse of <function>pg_get_object_address</function>.
16694   </para>
16695
16696   <para>
16697    <function>pg_get_object_address</function> returns a row containing enough
16698    information to uniquely identify the database object specified by its
16699    type and object name and argument arrays.  The returned values are the
16700    ones that would be used in system catalogs such as <structname>pg_depend</>
16701    and can be passed to other system functions such as
16702    <function>pg_identify_object</> or <function>pg_describe_object</>.
16703    <parameter>catalog_id</> is the OID of the system catalog containing the
16704    object;
16705    <parameter>object_id</> is the OID of the object itself, and
16706    <parameter>object_sub_id</> is the object sub-ID, or zero if none.
16707    This function is the inverse of <function>pg_identify_object_as_address</function>.
16708   </para>
16709
16710    <indexterm>
16711     <primary>col_description</primary>
16712    </indexterm>
16713
16714    <indexterm>
16715     <primary>obj_description</primary>
16716    </indexterm>
16717
16718    <indexterm>
16719     <primary>shobj_description</primary>
16720    </indexterm>
16721
16722    <indexterm>
16723     <primary>comment</primary>
16724     <secondary sortas="database objects">about database objects</secondary>
16725    </indexterm>
16726
16727    <para>
16728     The functions shown in <xref linkend="functions-info-comment-table">
16729     extract comments previously stored with the <xref linkend="sql-comment">
16730     command.  A null value is returned if no
16731     comment could be found for the specified parameters.
16732    </para>
16733
16734    <table id="functions-info-comment-table">
16735     <title>Comment Information Functions</title>
16736     <tgroup cols="3">
16737      <thead>
16738       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16739      </thead>
16740
16741      <tbody>
16742       <row>
16743        <entry><literal><function>col_description(<parameter>table_oid</parameter>, <parameter>column_number</parameter>)</function></literal></entry>
16744        <entry><type>text</type></entry>
16745        <entry>get comment for a table column</entry>
16746       </row>
16747       <row>
16748        <entry><literal><function>obj_description(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</function></literal></entry>
16749        <entry><type>text</type></entry>
16750        <entry>get comment for a database object</entry>
16751       </row>
16752       <row>
16753        <entry><literal><function>obj_description(<parameter>object_oid</parameter>)</function></literal></entry>
16754        <entry><type>text</type></entry>
16755        <entry>get comment for a database object (<emphasis>deprecated</emphasis>)</entry>
16756       </row>
16757       <row>
16758        <entry><literal><function>shobj_description(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</function></literal></entry>
16759        <entry><type>text</type></entry>
16760        <entry>get comment for a shared database object</entry>
16761       </row>
16762      </tbody>
16763     </tgroup>
16764    </table>
16765
16766    <para>
16767     <function>col_description</function> returns the comment for a table
16768     column, which is specified by the OID of its table and its column number.
16769     (<function>obj_description</function> cannot be used for table columns
16770     since columns do not have OIDs of their own.)
16771    </para>
16772
16773    <para>
16774     The two-parameter form of <function>obj_description</function> returns the
16775     comment for a database object specified by its OID and the name of the
16776     containing system catalog.  For example,
16777     <literal>obj_description(123456,'pg_class')</literal>
16778     would retrieve the comment for the table with OID 123456.
16779     The one-parameter form of <function>obj_description</function> requires only
16780     the object OID.  It is deprecated since there is no guarantee that
16781     OIDs are unique across different system catalogs; therefore, the wrong
16782     comment might be returned.
16783    </para>
16784
16785    <para>
16786     <function>shobj_description</function> is used just like
16787     <function>obj_description</function> except it is used for retrieving
16788     comments on shared objects.  Some system catalogs are global to all
16789     databases within each cluster, and the descriptions for objects in them
16790     are stored globally as well.
16791    </para>
16792
16793    <indexterm>
16794     <primary>txid_current</primary>
16795    </indexterm>
16796
16797    <indexterm>
16798     <primary>txid_current_snapshot</primary>
16799    </indexterm>
16800
16801    <indexterm>
16802     <primary>txid_snapshot_xip</primary>
16803    </indexterm>
16804
16805    <indexterm>
16806     <primary>txid_snapshot_xmax</primary>
16807    </indexterm>
16808
16809    <indexterm>
16810     <primary>txid_snapshot_xmin</primary>
16811    </indexterm>
16812
16813    <indexterm>
16814     <primary>txid_visible_in_snapshot</primary>
16815    </indexterm>
16816
16817    <para>
16818     The functions shown in <xref linkend="functions-txid-snapshot">
16819     provide server transaction information in an exportable form.  The main
16820     use of these functions is to determine which transactions were committed
16821     between two snapshots.
16822    </para>
16823
16824    <table id="functions-txid-snapshot">
16825     <title>Transaction IDs and Snapshots</title>
16826     <tgroup cols="3">
16827      <thead>
16828       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16829      </thead>
16830
16831      <tbody>
16832       <row>
16833        <entry><literal><function>txid_current()</function></literal></entry>
16834        <entry><type>bigint</type></entry>
16835        <entry>get current transaction ID, assigning a new one if the current transaction does not have one</entry>
16836       </row>
16837       <row>
16838        <entry><literal><function>txid_current_snapshot()</function></literal></entry>
16839        <entry><type>txid_snapshot</type></entry>
16840        <entry>get current snapshot</entry>
16841       </row>
16842       <row>
16843        <entry><literal><function>txid_snapshot_xip(<parameter>txid_snapshot</parameter>)</function></literal></entry>
16844        <entry><type>setof bigint</type></entry>
16845        <entry>get in-progress transaction IDs in snapshot</entry>
16846       </row>
16847       <row>
16848        <entry><literal><function>txid_snapshot_xmax(<parameter>txid_snapshot</parameter>)</function></literal></entry>
16849        <entry><type>bigint</type></entry>
16850        <entry>get <literal>xmax</literal> of snapshot</entry>
16851       </row>
16852       <row>
16853        <entry><literal><function>txid_snapshot_xmin(<parameter>txid_snapshot</parameter>)</function></literal></entry>
16854        <entry><type>bigint</type></entry>
16855        <entry>get <literal>xmin</literal> of snapshot</entry>
16856       </row>
16857       <row>
16858        <entry><literal><function>txid_visible_in_snapshot(<parameter>bigint</parameter>, <parameter>txid_snapshot</parameter>)</function></literal></entry>
16859        <entry><type>boolean</type></entry>
16860        <entry>is transaction ID visible in snapshot? (do not use with subtransaction ids)</entry>
16861       </row>
16862      </tbody>
16863     </tgroup>
16864    </table>
16865
16866    <para>
16867     The internal transaction ID type (<type>xid</>) is 32 bits wide and
16868     wraps around every 4 billion transactions.  However, these functions
16869     export a 64-bit format that is extended with an <quote>epoch</> counter
16870     so it will not wrap around during the life of an installation.
16871     The data type used by these functions, <type>txid_snapshot</type>,
16872     stores information about transaction ID
16873     visibility at a particular moment in time.  Its components are
16874     described in <xref linkend="functions-txid-snapshot-parts">.
16875    </para>
16876
16877    <table id="functions-txid-snapshot-parts">
16878     <title>Snapshot Components</title>
16879     <tgroup cols="2">
16880      <thead>
16881       <row>
16882        <entry>Name</entry>
16883        <entry>Description</entry>
16884       </row>
16885      </thead>
16886
16887      <tbody>
16888
16889       <row>
16890        <entry><type>xmin</type></entry>
16891        <entry>
16892          Earliest transaction ID (txid) that is still active.  All earlier
16893          transactions will either be committed and visible, or rolled
16894          back and dead.
16895        </entry>
16896       </row>
16897
16898       <row>
16899        <entry><type>xmax</type></entry>
16900        <entry>
16901         First as-yet-unassigned txid.  All txids greater than or equal to this
16902         are not yet started as of the time of the snapshot, and thus invisible.
16903        </entry>
16904       </row>
16905
16906       <row>
16907        <entry><type>xip_list</type></entry>
16908        <entry>
16909         Active txids at the time of the snapshot.  The list
16910         includes only those active txids between <literal>xmin</>
16911         and <literal>xmax</>; there might be active txids higher
16912         than <literal>xmax</>.  A txid that is <literal>xmin &lt;= txid &lt;
16913         xmax</literal> and not in this list was already completed
16914         at the time of the snapshot, and thus either visible or
16915         dead according to its commit status.  The list does not
16916         include txids of subtransactions.
16917        </entry>
16918       </row>
16919
16920      </tbody>
16921     </tgroup>
16922    </table>
16923
16924    <para>
16925     <type>txid_snapshot</>'s textual representation is
16926     <literal><replaceable>xmin</>:<replaceable>xmax</>:<replaceable>xip_list</></literal>.
16927     For example <literal>10:20:10,14,15</literal> means
16928     <literal>xmin=10, xmax=20, xip_list=10, 14, 15</literal>.
16929    </para>
16930
16931    <para>
16932     The functions shown in <xref linkend="functions-commit-timestamp">
16933     provide information about transactions that have been already committed.
16934     These functions mainly provide information about when the transactions
16935     were committed. They only provide useful data when
16936     <xref linkend="guc-track-commit-timestamp"> configuration option is enabled
16937     and only for transactions that were committed after it was enabled.
16938    </para>
16939
16940    <table id="functions-commit-timestamp">
16941     <title>Committed transaction information</title>
16942     <tgroup cols="3">
16943      <thead>
16944       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16945      </thead>
16946
16947      <tbody>
16948       <row>
16949        <entry>
16950         <indexterm><primary>pg_xact_commit_timestamp</primary></indexterm>
16951         <literal><function>pg_xact_commit_timestamp(<parameter>xid</parameter>)</function></literal>
16952        </entry>
16953        <entry><type>timestamp with time zone</type></entry>
16954        <entry>get commit timestamp of a transaction</entry>
16955       </row>
16956
16957       <row>
16958        <entry>
16959         <indexterm><primary>pg_last_committed_xact</primary></indexterm>
16960         <literal><function>pg_last_committed_xact()</function></literal>
16961        </entry>
16962        <entry><parameter>xid</> <type>xid</>, <parameter>timestamp</> <type>timestamp with time zone</></entry>
16963        <entry>get transaction ID and commit timestamp of latest committed transaction</entry>
16964       </row>
16965      </tbody>
16966     </tgroup>
16967    </table>
16968
16969    <para>
16970     The functions shown in <xref linkend="functions-controldata">
16971     print information initialized during <command>initdb</>, such
16972     as the catalog version. They also show information about write-ahead
16973     logging and checkpoint processing. This information is cluster-wide,
16974     and not specific to any one database. They provide most of the same
16975     information, from the same source, as
16976     <xref linkend="APP-PGCONTROLDATA">, although in a form better suited
16977     to <acronym>SQL</acronym> functions.
16978    </para>
16979
16980    <table id="functions-controldata">
16981     <title>Control Data Functions</title>
16982     <tgroup cols="3">
16983      <thead>
16984       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
16985      </thead>
16986
16987      <tbody>
16988       <row>
16989        <entry>
16990         <indexterm><primary>pg_control_checkpoint</primary></indexterm>
16991         <literal><function>pg_control_checkpoint()</function></literal>
16992        </entry>
16993        <entry><type>record</type></entry>
16994        <entry>
16995         Returns information about current checkpoint state.
16996        </entry>
16997       </row>
16998
16999       <row>
17000        <entry>
17001         <indexterm><primary>pg_control_system</primary></indexterm>
17002         <literal><function>pg_control_system()</function></literal>
17003        </entry>
17004        <entry><type>record</type></entry>
17005        <entry>
17006         Returns information about current controldata file state.
17007        </entry>
17008       </row>
17009
17010       <row>
17011        <entry>
17012         <indexterm><primary>pg_control_init</primary></indexterm>
17013         <literal><function>pg_control_init()</function></literal>
17014        </entry>
17015        <entry><type>record</type></entry>
17016        <entry>
17017         Returns information about cluster initialization state.
17018        </entry>
17019       </row>
17020
17021       <row>
17022        <entry>
17023         <indexterm><primary>pg_control_recovery</primary></indexterm>
17024         <literal><function>pg_control_recovery()</function></literal>
17025        </entry>
17026        <entry><type>record</type></entry>
17027        <entry>
17028         Returns information about recovery state.
17029        </entry>
17030       </row>
17031
17032      </tbody>
17033     </tgroup>
17034    </table>
17035
17036    <para>
17037     <function>pg_control_checkpoint</> returns a record, shown in
17038     <xref linkend="functions-pg-control-checkpoint">
17039    </para>
17040
17041    <table id="functions-pg-control-checkpoint">
17042     <title><function>pg_control_checkpoint</> Columns</title>
17043     <tgroup cols="2">
17044      <thead>
17045       <row>
17046        <entry>Column Name</entry>
17047        <entry>Data Type</entry>
17048       </row>
17049      </thead>
17050
17051      <tbody>
17052
17053       <row>
17054        <entry>checkpoint_location</entry>
17055        <entry><type>pg_lsn</type></entry>
17056       </row>
17057
17058       <row>
17059        <entry>prior_location</entry>
17060        <entry><type>pg_lsn</type></entry>
17061       </row>
17062
17063       <row>
17064        <entry>redo_location</entry>
17065        <entry><type>pg_lsn</type></entry>
17066       </row>
17067
17068       <row>
17069        <entry>redo_wal_file</entry>
17070        <entry><type>text</type></entry>
17071       </row>
17072
17073       <row>
17074        <entry>timeline_id</entry>
17075        <entry><type>integer</type></entry>
17076       </row>
17077
17078       <row>
17079        <entry>prev_timeline_id</entry>
17080        <entry><type>integer</type></entry>
17081       </row>
17082
17083       <row>
17084        <entry>full_page_writes</entry>
17085        <entry><type>boolean</type></entry>
17086       </row>
17087
17088       <row>
17089        <entry>next_xid</entry>
17090        <entry><type>text</type></entry>
17091       </row>
17092
17093       <row>
17094        <entry>next_oid</entry>
17095        <entry><type>oid</type></entry>
17096       </row>
17097
17098       <row>
17099        <entry>next_multixact_id</entry>
17100        <entry><type>xid</type></entry>
17101       </row>
17102
17103       <row>
17104        <entry>next_multi_offset</entry>
17105        <entry><type>xid</type></entry>
17106       </row>
17107
17108       <row>
17109        <entry>oldest_xid</entry>
17110        <entry><type>xid</type></entry>
17111       </row>
17112
17113       <row>
17114        <entry>oldest_xid_dbid</entry>
17115        <entry><type>oid</type></entry>
17116       </row>
17117
17118       <row>
17119        <entry>oldest_active_xid</entry>
17120        <entry><type>xid</type></entry>
17121       </row>
17122
17123       <row>
17124        <entry>oldest_multi_xid</entry>
17125        <entry><type>xid</type></entry>
17126       </row>
17127
17128       <row>
17129        <entry>oldest_multi_dbid</entry>
17130        <entry><type>oid</type></entry>
17131       </row>
17132
17133       <row>
17134        <entry>oldest_commit_ts_xid</entry>
17135        <entry><type>xid</type></entry>
17136       </row>
17137
17138       <row>
17139        <entry>newest_commit_ts_xid</entry>
17140        <entry><type>xid</type></entry>
17141       </row>
17142
17143       <row>
17144        <entry>checkpoint_time</entry>
17145        <entry><type>timestamp with time zone</type></entry>
17146       </row>
17147
17148      </tbody>
17149     </tgroup>
17150    </table>
17151
17152    <para>
17153     <function>pg_control_system</> returns a record, shown in
17154     <xref linkend="functions-pg-control-system">
17155    </para>
17156
17157    <table id="functions-pg-control-system">
17158     <title><function>pg_control_system</> Columns</title>
17159     <tgroup cols="2">
17160      <thead>
17161       <row>
17162        <entry>Column Name</entry>
17163        <entry>Data Type</entry>
17164       </row>
17165      </thead>
17166
17167      <tbody>
17168
17169       <row>
17170        <entry>pg_control_version</entry>
17171        <entry><type>integer</type></entry>
17172       </row>
17173
17174       <row>
17175        <entry>catalog_version_no</entry>
17176        <entry><type>integer</type></entry>
17177       </row>
17178
17179       <row>
17180        <entry>system_identifier</entry>
17181        <entry><type>bigint</type></entry>
17182       </row>
17183
17184       <row>
17185        <entry>pg_control_last_modified</entry>
17186        <entry><type>timestamp with time zone</type></entry>
17187       </row>
17188
17189      </tbody>
17190     </tgroup>
17191    </table>
17192
17193    <para>
17194     <function>pg_control_init</> returns a record, shown in
17195     <xref linkend="functions-pg-control-init">
17196    </para>
17197
17198    <table id="functions-pg-control-init">
17199     <title><function>pg_control_init</> Columns</title>
17200     <tgroup cols="2">
17201      <thead>
17202       <row>
17203        <entry>Column Name</entry>
17204        <entry>Data Type</entry>
17205       </row>
17206      </thead>
17207
17208      <tbody>
17209
17210       <row>
17211        <entry>max_data_alignment</entry>
17212        <entry><type>integer</type></entry>
17213       </row>
17214
17215       <row>
17216        <entry>database_block_size</entry>
17217        <entry><type>integer</type></entry>
17218       </row>
17219
17220       <row>
17221        <entry>blocks_per_segment</entry>
17222        <entry><type>integer</type></entry>
17223       </row>
17224
17225       <row>
17226        <entry>wal_block_size</entry>
17227        <entry><type>integer</type></entry>
17228       </row>
17229
17230       <row>
17231        <entry>bytes_per_wal_segment</entry>
17232        <entry><type>integer</type></entry>
17233       </row>
17234
17235       <row>
17236        <entry>max_identifier_length</entry>
17237        <entry><type>integer</type></entry>
17238       </row>
17239
17240       <row>
17241        <entry>max_index_columns</entry>
17242        <entry><type>integer</type></entry>
17243       </row>
17244
17245       <row>
17246        <entry>max_toast_chunk_size</entry>
17247        <entry><type>integer</type></entry>
17248       </row>
17249
17250       <row>
17251        <entry>large_object_chunk_size</entry>
17252        <entry><type>integer</type></entry>
17253       </row>
17254
17255       <row>
17256        <entry>bigint_timestamps</entry>
17257        <entry><type>boolean</type></entry>
17258       </row>
17259
17260       <row>
17261        <entry>float4_pass_by_value</entry>
17262        <entry><type>boolean</type></entry>
17263       </row>
17264
17265       <row>
17266        <entry>float8_pass_by_value</entry>
17267        <entry><type>boolean</type></entry>
17268       </row>
17269
17270       <row>
17271        <entry>data_page_checksum_version</entry>
17272        <entry><type>integer</type></entry>
17273       </row>
17274
17275      </tbody>
17276     </tgroup>
17277    </table>
17278
17279    <para>
17280     <function>pg_control_recovery</> returns a record, shown in
17281     <xref linkend="functions-pg-control-recovery">
17282    </para>
17283
17284    <table id="functions-pg-control-recovery">
17285     <title><function>pg_control_recovery</> Columns</title>
17286     <tgroup cols="2">
17287      <thead>
17288       <row>
17289        <entry>Column Name</entry>
17290        <entry>Data Type</entry>
17291       </row>
17292      </thead>
17293
17294      <tbody>
17295
17296       <row>
17297        <entry>min_recovery_end_location</entry>
17298        <entry><type>pg_lsn</type></entry>
17299       </row>
17300
17301       <row>
17302        <entry>min_recovery_end_timeline</entry>
17303        <entry><type>integer</type></entry>
17304       </row>
17305
17306       <row>
17307        <entry>backup_start_location</entry>
17308        <entry><type>pg_lsn</type></entry>
17309       </row>
17310
17311       <row>
17312        <entry>backup_end_location</entry>
17313        <entry><type>pg_lsn</type></entry>
17314       </row>
17315
17316       <row>
17317        <entry>end_of_backup_record_required</entry>
17318        <entry><type>boolean</type></entry>
17319       </row>
17320
17321      </tbody>
17322     </tgroup>
17323    </table>
17324
17325   </sect1>
17326
17327   <sect1 id="functions-admin">
17328    <title>System Administration Functions</title>
17329
17330    <para>
17331     The functions described in this section are used to control and
17332     monitor a <productname>PostgreSQL</> installation.
17333    </para>
17334
17335   <sect2 id="functions-admin-set">
17336    <title>Configuration Settings Functions</title>
17337
17338    <para>
17339     <xref linkend="functions-admin-set-table"> shows the functions
17340     available to query and alter run-time configuration parameters.
17341    </para>
17342
17343    <table id="functions-admin-set-table">
17344     <title>Configuration Settings Functions</title>
17345     <tgroup cols="3">
17346      <thead>
17347       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
17348      </thead>
17349
17350      <tbody>
17351       <row>
17352        <entry>
17353         <indexterm>
17354          <primary>current_setting</primary>
17355         </indexterm>
17356         <literal><function>current_setting(<parameter>setting_name</parameter> [, <parameter>missing_ok</parameter> ])</function></literal>
17357        </entry>
17358        <entry><type>text</type></entry>
17359        <entry>get current value of setting</entry>
17360       </row>
17361       <row>
17362        <entry>
17363         <indexterm>
17364          <primary>set_config</primary>
17365         </indexterm>
17366         <literal><function>set_config(<parameter>setting_name</parameter>,
17367                              <parameter>new_value</parameter>,
17368                              <parameter>is_local</parameter>)</function></literal>
17369        </entry>
17370        <entry><type>text</type></entry>
17371        <entry>set parameter and return new value</entry>
17372       </row>
17373      </tbody>
17374     </tgroup>
17375    </table>
17376
17377    <indexterm>
17378     <primary>SET</primary>
17379    </indexterm>
17380
17381    <indexterm>
17382     <primary>SHOW</primary>
17383    </indexterm>
17384
17385    <indexterm>
17386     <primary>configuration</primary>
17387     <secondary sortas="server">of the server</secondary>
17388     <tertiary>functions</tertiary>
17389    </indexterm>
17390
17391    <para>
17392     The function <function>current_setting</function> yields the
17393     current value of the setting <parameter>setting_name</parameter>.
17394     It corresponds to the <acronym>SQL</acronym> command
17395     <command>SHOW</command>.  An example:
17396 <programlisting>
17397 SELECT current_setting('datestyle');
17398
17399  current_setting
17400 -----------------
17401  ISO, MDY
17402 (1 row)
17403 </programlisting>
17404
17405     If there is no setting named <parameter>setting_name</parameter>,
17406     <function>current_setting</function> throws an error
17407     unless <parameter>missing_ok</parameter> is supplied and is
17408     <literal>true</literal>.
17409    </para>
17410
17411    <para>
17412     <function>set_config</function> sets the parameter
17413     <parameter>setting_name</parameter> to
17414     <parameter>new_value</parameter>.  If
17415     <parameter>is_local</parameter> is <literal>true</literal>, the
17416     new value will only apply to the current transaction. If you want
17417     the new value to apply for the current session, use
17418     <literal>false</literal> instead. The function corresponds to the
17419     SQL command <command>SET</command>. An example:
17420 <programlisting>
17421 SELECT set_config('log_statement_stats', 'off', false);
17422
17423  set_config
17424 ------------
17425  off
17426 (1 row)
17427 </programlisting>
17428    </para>
17429
17430   </sect2>
17431
17432   <sect2 id="functions-admin-signal">
17433    <title>Server Signaling Functions</title>
17434
17435    <indexterm>
17436     <primary>pg_cancel_backend</primary>
17437    </indexterm>
17438    <indexterm>
17439     <primary>pg_reload_conf</primary>
17440    </indexterm>
17441    <indexterm>
17442     <primary>pg_rotate_logfile</primary>
17443    </indexterm>
17444    <indexterm>
17445     <primary>pg_terminate_backend</primary>
17446    </indexterm>
17447
17448    <indexterm>
17449     <primary>signal</primary>
17450     <secondary sortas="backend">backend processes</secondary>
17451    </indexterm>
17452
17453    <para>
17454     The functions shown in <xref
17455     linkend="functions-admin-signal-table"> send control signals to
17456     other server processes.  Use of these functions is restricted to
17457     superusers by default but access may be granted to others with the
17458     <command>GRANT</command>, with noted exceptions.
17459    </para>
17460
17461    <table id="functions-admin-signal-table">
17462     <title>Server Signaling Functions</title>
17463     <tgroup cols="3">
17464      <thead>
17465       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
17466       </row>
17467      </thead>
17468
17469      <tbody>
17470       <row>
17471        <entry>
17472         <literal><function>pg_cancel_backend(<parameter>pid</parameter> <type>int</>)</function></literal>
17473         </entry>
17474        <entry><type>boolean</type></entry>
17475        <entry>Cancel a backend's current query.  This is also allowed if the
17476         calling role is a member of the role whose backend is being canceled or
17477         the calling role has been granted <literal>pg_signal_backend</literal>,
17478         however only superusers can cancel superuser backends.
17479         </entry>
17480       </row>
17481       <row>
17482        <entry>
17483         <literal><function>pg_reload_conf()</function></literal>
17484         </entry>
17485        <entry><type>boolean</type></entry>
17486        <entry>Cause server processes to reload their configuration files</entry>
17487       </row>
17488       <row>
17489        <entry>
17490         <literal><function>pg_rotate_logfile()</function></literal>
17491         </entry>
17492        <entry><type>boolean</type></entry>
17493        <entry>Rotate server's log file</entry>
17494       </row>
17495       <row>
17496        <entry>
17497         <literal><function>pg_terminate_backend(<parameter>pid</parameter> <type>int</>)</function></literal>
17498         </entry>
17499        <entry><type>boolean</type></entry>
17500        <entry>Terminate a backend.  This is also allowed if the calling role
17501         is a member of the role whose backend is being terminated or the
17502         calling role has been granted <literal>pg_signal_backend</literal>,
17503         however only superusers can terminate superuser backends.
17504        </entry>
17505       </row>
17506      </tbody>
17507     </tgroup>
17508    </table>
17509
17510    <para>
17511     Each of these functions returns <literal>true</literal> if
17512     successful and <literal>false</literal> otherwise.
17513    </para>
17514
17515    <para>
17516     <function>pg_cancel_backend</> and <function>pg_terminate_backend</>
17517     send signals (<systemitem>SIGINT</> or <systemitem>SIGTERM</>
17518     respectively) to backend processes identified by process ID.
17519     The process ID of an active backend can be found from
17520     the <structfield>pid</structfield> column of the
17521     <structname>pg_stat_activity</structname> view, or by listing the
17522     <command>postgres</command> processes on the server (using
17523     <application>ps</> on Unix or the <application>Task
17524     Manager</> on <productname>Windows</>).
17525     The role of an active backend can be found from the
17526     <structfield>usename</structfield> column of the
17527     <structname>pg_stat_activity</structname> view.
17528    </para>
17529
17530    <para>
17531     <function>pg_reload_conf</> sends a <systemitem>SIGHUP</> signal
17532     to the server, causing configuration files
17533     to be reloaded by all server processes.
17534    </para>
17535
17536    <para>
17537     <function>pg_rotate_logfile</> signals the log-file manager to switch
17538     to a new output file immediately.  This works only when the built-in
17539     log collector is running, since otherwise there is no log-file manager
17540     subprocess.
17541    </para>
17542
17543   </sect2>
17544
17545   <sect2 id="functions-admin-backup">
17546    <title>Backup Control Functions</title>
17547
17548    <indexterm>
17549     <primary>backup</primary>
17550    </indexterm>
17551    <indexterm>
17552     <primary>pg_create_restore_point</primary>
17553    </indexterm>
17554    <indexterm>
17555     <primary>pg_current_xlog_flush_location</primary>
17556    </indexterm>
17557    <indexterm>
17558     <primary>pg_current_xlog_insert_location</primary>
17559    </indexterm>
17560    <indexterm>
17561     <primary>pg_current_xlog_location</primary>
17562    </indexterm>
17563    <indexterm>
17564     <primary>pg_start_backup</primary>
17565    </indexterm>
17566    <indexterm>
17567     <primary>pg_stop_backup</primary>
17568    </indexterm>
17569    <indexterm>
17570     <primary>pg_is_in_backup</primary>
17571    </indexterm>
17572    <indexterm>
17573     <primary>pg_backup_start_time</primary>
17574    </indexterm>
17575    <indexterm>
17576     <primary>pg_switch_xlog</primary>
17577    </indexterm>
17578    <indexterm>
17579     <primary>pg_xlogfile_name</primary>
17580    </indexterm>
17581    <indexterm>
17582     <primary>pg_xlogfile_name_offset</primary>
17583    </indexterm>
17584    <indexterm>
17585     <primary>pg_xlog_location_diff</primary>
17586    </indexterm>
17587
17588    <para>
17589     The functions shown in <xref
17590     linkend="functions-admin-backup-table"> assist in making on-line backups.
17591     These functions cannot be executed during recovery (except
17592     <function>pg_is_in_backup</function>, <function>pg_backup_start_time</function>
17593     and <function>pg_xlog_location_diff</function>).
17594    </para>
17595
17596    <table id="functions-admin-backup-table">
17597     <title>Backup Control Functions</title>
17598     <tgroup cols="3">
17599      <thead>
17600       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
17601       </row>
17602      </thead>
17603
17604      <tbody>
17605       <row>
17606        <entry>
17607         <literal><function>pg_create_restore_point(<parameter>name</> <type>text</>)</function></literal>
17608         </entry>
17609        <entry><type>pg_lsn</type></entry>
17610        <entry>Create a named point for performing restore (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17611       </row>
17612       <row>
17613        <entry>
17614         <literal><function>pg_current_xlog_flush_location()</function></literal>
17615         </entry>
17616        <entry><type>pg_lsn</type></entry>
17617        <entry>Get current transaction log flush location</entry>
17618       </row>
17619       <row>
17620        <entry>
17621         <literal><function>pg_current_xlog_insert_location()</function></literal>
17622         </entry>
17623        <entry><type>pg_lsn</type></entry>
17624        <entry>Get current transaction log insert location</entry>
17625       </row>
17626       <row>
17627        <entry>
17628         <literal><function>pg_current_xlog_location()</function></literal>
17629         </entry>
17630        <entry><type>pg_lsn</type></entry>
17631        <entry>Get current transaction log write location</entry>
17632       </row>
17633       <row>
17634        <entry>
17635         <literal><function>pg_start_backup(<parameter>label</> <type>text</> <optional>, <parameter>fast</> <type>boolean</> <optional>, <parameter>exclusive</> <type>boolean</> </optional></optional>)</function></literal>
17636         </entry>
17637        <entry><type>pg_lsn</type></entry>
17638        <entry>Prepare for performing on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17639       </row>
17640       <row>
17641        <entry>
17642         <literal><function>pg_stop_backup()</function></literal>
17643         </entry>
17644        <entry><type>pg_lsn</type></entry>
17645        <entry>Finish performing exclusive on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17646       </row>
17647       <row>
17648        <entry>
17649         <literal><function>pg_stop_backup(<parameter>exclusive</> <type>boolean</>)</function></literal>
17650         </entry>
17651        <entry><type>setof record</type></entry>
17652        <entry>Finish performing exclusive or non-exclusive on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17653       </row>
17654       <row>
17655        <entry>
17656         <literal><function>pg_is_in_backup()</function></literal>
17657         </entry>
17658        <entry><type>bool</type></entry>
17659        <entry>True if an on-line exclusive backup is still in progress.</entry>
17660       </row>
17661       <row>
17662        <entry>
17663         <literal><function>pg_backup_start_time()</function></literal>
17664         </entry>
17665        <entry><type>timestamp with time zone</type></entry>
17666        <entry>Get start time of an on-line exclusive backup in progress.</entry>
17667       </row>
17668       <row>
17669        <entry>
17670         <literal><function>pg_switch_xlog()</function></literal>
17671         </entry>
17672        <entry><type>pg_lsn</type></entry>
17673        <entry>Force switch to a new transaction log file (restricted to superusers by default, but other users can be granted EXECUTE to run the function)</entry>
17674       </row>
17675       <row>
17676        <entry>
17677         <literal><function>pg_xlogfile_name(<parameter>location</> <type>pg_lsn</>)</function></literal>
17678         </entry>
17679        <entry><type>text</type></entry>
17680        <entry>Convert transaction log location string to file name</entry>
17681       </row>
17682       <row>
17683        <entry>
17684         <literal><function>pg_xlogfile_name_offset(<parameter>location</> <type>pg_lsn</>)</function></literal>
17685         </entry>
17686        <entry><type>text</>, <type>integer</></entry>
17687        <entry>Convert transaction log location string to file name and decimal byte offset within file</entry>
17688       </row>
17689       <row>
17690        <entry>
17691         <literal><function>pg_xlog_location_diff(<parameter>location</> <type>pg_lsn</>, <parameter>location</> <type>pg_lsn</>)</function></literal>
17692        </entry>
17693        <entry><type>numeric</></entry>
17694        <entry>Calculate the difference between two transaction log locations</entry>
17695       </row>
17696      </tbody>
17697     </tgroup>
17698    </table>
17699
17700    <para>
17701     <function>pg_start_backup</> accepts an arbitrary user-defined label for
17702     the backup.  (Typically this would be the name under which the backup dump
17703     file will be stored.) When used in exclusive mode, the function writes a
17704     backup label file (<filename>backup_label</>) and, if there are any links
17705     in the <filename>pg_tblspc/</> directory, a tablespace map file
17706     (<filename>tablespace_map</>) into the database cluster's data directory,
17707     performs a checkpoint, and then returns the backup's starting transaction
17708     log location as text.  The user can ignore this result value, but it is
17709     provided in case it is useful. When used in non-exclusive mode, the
17710     contents of these files are instead returned by the
17711     <function>pg_stop_backup</> function, and should be written to the backup
17712     by the caller.
17713
17714 <programlisting>
17715 postgres=# select pg_start_backup('label_goes_here');
17716  pg_start_backup
17717 -----------------
17718  0/D4445B8
17719 (1 row)
17720 </programlisting>
17721     There is an optional second parameter of type <type>boolean</type>.  If <literal>true</>,
17722     it specifies executing <function>pg_start_backup</> as quickly as
17723     possible.  This forces an immediate checkpoint which will cause a
17724     spike in I/O operations, slowing any concurrently executing queries.
17725    </para>
17726
17727    <para>
17728     In an exclusive backup, <function>pg_stop_backup</> removes the label file
17729     and, if it exists, the <filename>tablespace_map</> file created by
17730     <function>pg_start_backup</>. In a non-exclusive backup, the contents of
17731     the <filename>backup_label</> and <filename>tablespace_map</> are returned
17732     in the result of the function, and should be written to files in the
17733     backup (and not in the data directory).
17734    </para>
17735
17736    <para>
17737     The function also creates a backup history file in the transaction log
17738     archive area. The history file includes the label given to
17739     <function>pg_start_backup</>, the starting and ending transaction log locations for
17740     the backup, and the starting and ending times of the backup.  The return
17741     value is the backup's ending transaction log location (which again
17742     can be ignored).  After recording the ending location, the current
17743     transaction log insertion
17744     point is automatically advanced to the next transaction log file, so that the
17745     ending transaction log file can be archived immediately to complete the backup.
17746    </para>
17747
17748    <para>
17749     <function>pg_switch_xlog</> moves to the next transaction log file, allowing the
17750     current file to be archived (assuming you are using continuous archiving).
17751     The return value is the ending transaction log location + 1 within the just-completed transaction log file.
17752     If there has been no transaction log activity since the last transaction log switch,
17753     <function>pg_switch_xlog</> does nothing and returns the start location
17754     of the transaction log file currently in use.
17755    </para>
17756
17757    <para>
17758     <function>pg_create_restore_point</> creates a named transaction log
17759     record that can be used as recovery target, and returns the corresponding
17760     transaction log location.  The given name can then be used with
17761     <xref linkend="recovery-target-name"> to specify the point up to which
17762     recovery will proceed.  Avoid creating multiple restore points with the
17763     same name, since recovery will stop at the first one whose name matches
17764     the recovery target.
17765    </para>
17766
17767    <para>
17768     <function>pg_current_xlog_location</> displays the current transaction log write
17769     location in the same format used by the above functions.  Similarly,
17770     <function>pg_current_xlog_insert_location</> displays the current transaction log
17771     insertion point and <function>pg_current_xlog_flush_location</> displays the
17772     current transaction log flush point. The insertion point is the <quote>logical</>
17773     end of the transaction log at any instant, while the write location is the end of
17774     what has actually been written out from the server's internal buffers and flush
17775     location is the location guaranteed to be written to durable storage. The write
17776     location is the end of what can be examined from outside the server, and is usually
17777     what you want if you are interested in archiving partially-complete transaction log
17778     files.  The insertion and flush points are made available primarily for server
17779     debugging purposes.  These are both read-only operations and do not
17780     require superuser permissions.
17781    </para>
17782
17783    <para>
17784     You can use <function>pg_xlogfile_name_offset</> to extract the
17785     corresponding transaction log file name and byte offset from the results of any of the
17786     above functions.  For example:
17787 <programlisting>
17788 postgres=# SELECT * FROM pg_xlogfile_name_offset(pg_stop_backup());
17789         file_name         | file_offset 
17790 --------------------------+-------------
17791  00000001000000000000000D |     4039624
17792 (1 row)
17793 </programlisting>
17794     Similarly, <function>pg_xlogfile_name</> extracts just the transaction log file name.
17795     When the given transaction log location is exactly at a transaction log file boundary, both
17796     these functions return the name of the preceding transaction log file.
17797     This is usually the desired behavior for managing transaction log archiving
17798     behavior, since the preceding file is the last one that currently
17799     needs to be archived.
17800    </para>
17801
17802    <para>
17803     <function>pg_xlog_location_diff</> calculates the difference in bytes
17804     between two transaction log locations. It can be used with
17805     <structname>pg_stat_replication</structname> or some functions shown in
17806     <xref linkend="functions-admin-backup-table"> to get the replication lag.
17807    </para>
17808
17809    <para>
17810     For details about proper usage of these functions, see
17811     <xref linkend="continuous-archiving">.
17812    </para>
17813
17814   </sect2>
17815
17816   <sect2 id="functions-recovery-control">
17817    <title>Recovery Control Functions</title>
17818
17819    <indexterm>
17820     <primary>pg_is_in_recovery</primary>
17821    </indexterm>
17822    <indexterm>
17823     <primary>pg_last_xlog_receive_location</primary>
17824    </indexterm>
17825    <indexterm>
17826     <primary>pg_last_xlog_replay_location</primary>
17827    </indexterm>
17828    <indexterm>
17829     <primary>pg_last_xact_replay_timestamp</primary>
17830    </indexterm>
17831
17832    <para>
17833     The functions shown in <xref
17834     linkend="functions-recovery-info-table"> provide information
17835     about the current status of the standby.
17836     These functions may be executed both during recovery and in normal running.
17837    </para>
17838
17839    <table id="functions-recovery-info-table">
17840     <title>Recovery Information Functions</title>
17841     <tgroup cols="3">
17842      <thead>
17843       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
17844       </row>
17845      </thead>
17846
17847      <tbody>
17848       <row>
17849        <entry>
17850         <literal><function>pg_is_in_recovery()</function></literal>
17851         </entry>
17852        <entry><type>bool</type></entry>
17853        <entry>True if recovery is still in progress.
17854        </entry>
17855       </row>
17856       <row>
17857        <entry>
17858         <literal><function>pg_last_xlog_receive_location()</function></literal>
17859         </entry>
17860        <entry><type>pg_lsn</type></entry>
17861        <entry>Get last transaction log location received and synced to disk by
17862         streaming replication. While streaming replication is in progress
17863         this will increase monotonically. If recovery has completed this will
17864         remain static at
17865         the value of the last WAL record received and synced to disk during
17866         recovery. If streaming replication is disabled, or if it has not yet
17867         started, the function returns NULL.
17868        </entry>
17869       </row>
17870       <row>
17871        <entry>
17872         <literal><function>pg_last_xlog_replay_location()</function></literal>
17873         </entry>
17874        <entry><type>pg_lsn</type></entry>
17875        <entry>Get last transaction log location replayed during recovery.
17876         If recovery is still in progress this will increase monotonically.
17877         If recovery has completed then this value will remain static at
17878         the value of the last WAL record applied during that recovery.
17879         When the server has been started normally without recovery
17880         the function returns NULL.
17881        </entry>
17882       </row>
17883       <row>
17884        <entry>
17885         <literal><function>pg_last_xact_replay_timestamp()</function></literal>
17886         </entry>
17887        <entry><type>timestamp with time zone</type></entry>
17888        <entry>Get time stamp of last transaction replayed during recovery.
17889         This is the time at which the commit or abort WAL record for that
17890         transaction was generated on the primary.
17891         If no transactions have been replayed during recovery, this function
17892         returns NULL.  Otherwise, if recovery is still in progress this will
17893         increase monotonically.  If recovery has completed then this value will
17894         remain static at the value of the last transaction applied during that
17895         recovery.  When the server has been started normally without recovery
17896         the function returns NULL.
17897        </entry>
17898       </row>
17899      </tbody>
17900     </tgroup>
17901    </table>
17902
17903    <indexterm>
17904     <primary>pg_is_xlog_replay_paused</primary>
17905    </indexterm>
17906    <indexterm>
17907     <primary>pg_xlog_replay_pause</primary>
17908    </indexterm>
17909    <indexterm>
17910     <primary>pg_xlog_replay_resume</primary>
17911    </indexterm>
17912
17913    <para>
17914     The functions shown in <xref
17915     linkend="functions-recovery-control-table"> control the progress of recovery.
17916     These functions may be executed only during recovery.
17917    </para>
17918
17919    <table id="functions-recovery-control-table">
17920     <title>Recovery Control Functions</title>
17921     <tgroup cols="3">
17922      <thead>
17923       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
17924       </row>
17925      </thead>
17926
17927      <tbody>
17928       <row>
17929        <entry>
17930         <literal><function>pg_is_xlog_replay_paused()</function></literal>
17931         </entry>
17932        <entry><type>bool</type></entry>
17933        <entry>True if recovery is paused.
17934        </entry>
17935       </row>
17936       <row>
17937        <entry>
17938         <literal><function>pg_xlog_replay_pause()</function></literal>
17939         </entry>
17940        <entry><type>void</type></entry>
17941        <entry>Pauses recovery immediately (restricted to superusers by default, but other users can be granted EXECUTE to run the function).
17942        </entry>
17943       </row>
17944       <row>
17945        <entry>
17946         <literal><function>pg_xlog_replay_resume()</function></literal>
17947         </entry>
17948        <entry><type>void</type></entry>
17949        <entry>Restarts recovery if it was paused (restricted to superusers by default, but other users can be granted EXECUTE to run the function).
17950        </entry>
17951       </row>
17952      </tbody>
17953     </tgroup>
17954    </table>
17955
17956    <para>
17957     While recovery is paused no further database changes are applied.
17958     If in hot standby, all new queries will see the same consistent snapshot
17959     of the database, and no further query conflicts will be generated until
17960     recovery is resumed.
17961    </para>
17962
17963    <para>
17964     If streaming replication is disabled, the paused state may continue
17965     indefinitely without problem. While streaming replication is in
17966     progress WAL records will continue to be received, which will
17967     eventually fill available disk space, depending upon the duration of
17968     the pause, the rate of WAL generation and available disk space.
17969    </para>
17970
17971   </sect2>
17972
17973   <sect2 id="functions-snapshot-synchronization">
17974    <title>Snapshot Synchronization Functions</title>
17975
17976    <indexterm>
17977      <primary>pg_export_snapshot</primary>
17978    </indexterm>
17979
17980    <para>
17981     <productname>PostgreSQL</> allows database sessions to synchronize their
17982     snapshots. A <firstterm>snapshot</> determines which data is visible to the
17983     transaction that is using the snapshot. Synchronized snapshots are
17984     necessary when two or more sessions need to see identical content in the
17985     database. If two sessions just start their transactions independently,
17986     there is always a possibility that some third transaction commits
17987     between the executions of the two <command>START TRANSACTION</> commands,
17988     so that one session sees the effects of that transaction and the other
17989     does not.
17990    </para>
17991
17992    <para>
17993     To solve this problem, <productname>PostgreSQL</> allows a transaction to
17994     <firstterm>export</> the snapshot it is using.  As long as the exporting
17995     transaction remains open, other transactions can <firstterm>import</> its
17996     snapshot, and thereby be guaranteed that they see exactly the same view
17997     of the database that the first transaction sees.  But note that any
17998     database changes made by any one of these transactions remain invisible
17999     to the other transactions, as is usual for changes made by uncommitted
18000     transactions.  So the transactions are synchronized with respect to
18001     pre-existing data, but act normally for changes they make themselves.
18002    </para>
18003
18004    <para>
18005     Snapshots are exported with the <function>pg_export_snapshot</> function,
18006     shown in <xref linkend="functions-snapshot-synchronization-table">, and
18007     imported with the <xref linkend="sql-set-transaction"> command.
18008    </para>
18009
18010    <table id="functions-snapshot-synchronization-table">
18011     <title>Snapshot Synchronization Functions</title>
18012     <tgroup cols="3">
18013      <thead>
18014       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18015       </row>
18016      </thead>
18017
18018      <tbody>
18019       <row>
18020        <entry>
18021         <literal><function>pg_export_snapshot()</function></literal>
18022        </entry>
18023        <entry><type>text</type></entry>
18024        <entry>Save the current snapshot and return its identifier</entry>
18025       </row>
18026      </tbody>
18027     </tgroup>
18028    </table>
18029
18030    <para>
18031     The function <function>pg_export_snapshot</> saves the current snapshot
18032     and returns a <type>text</> string identifying the snapshot.  This string
18033     must be passed (outside the database) to clients that want to import the
18034     snapshot.  The snapshot is available for import only until the end of the
18035     transaction that exported it.  A transaction can export more than one
18036     snapshot, if needed.  Note that doing so is only useful in <literal>READ
18037     COMMITTED</> transactions, since in <literal>REPEATABLE READ</> and
18038     higher isolation levels, transactions use the same snapshot throughout
18039     their lifetime.  Once a transaction has exported any snapshots, it cannot
18040     be prepared with <xref linkend="sql-prepare-transaction">.
18041    </para>
18042
18043    <para>
18044     See  <xref linkend="sql-set-transaction"> for details of how to use an
18045     exported snapshot.
18046    </para>
18047   </sect2>
18048
18049   <sect2 id="functions-replication">
18050    <title>Replication Functions</title>
18051
18052    <para>
18053     The functions shown
18054     in <xref linkend="functions-replication-table"> are for
18055     controlling and interacting with replication features.
18056     See <xref linkend="streaming-replication">,
18057     <xref linkend="streaming-replication-slots">, and
18058     <xref linkend="replication-origins">
18059     for information about the underlying features.  Use of these
18060     functions is restricted to superusers.
18061    </para>
18062
18063    <para>
18064     Many of these functions have equivalent commands in the replication
18065     protocol; see <xref linkend="protocol-replication">.
18066    </para>
18067
18068    <para>
18069     The functions described in
18070     <xref linkend="functions-admin-backup">,
18071     <xref linkend="functions-recovery-control">, and
18072     <xref linkend="functions-snapshot-synchronization">
18073     are also relevant for replication.
18074    </para>
18075
18076    <table id="functions-replication-table">
18077     <title>Replication <acronym>SQL</acronym> Functions</title>
18078     <tgroup cols="3">
18079      <thead>
18080       <row>
18081        <entry>Function</entry>
18082        <entry>Return Type</entry>
18083        <entry>Description</entry>
18084       </row>
18085      </thead>
18086      <tbody>
18087       <row>
18088        <entry>
18089         <indexterm>
18090          <primary>pg_create_physical_replication_slot</primary>
18091         </indexterm>
18092         <literal><function>pg_create_physical_replication_slot(<parameter>slot_name</parameter> <type>name</type> <optional>, <parameter>immediately_reserve</> <type>boolean</> </optional>)</function></literal>
18093        </entry>
18094        <entry>
18095         (<parameter>slot_name</parameter> <type>name</type>, <parameter>xlog_position</parameter> <type>pg_lsn</type>)
18096        </entry>
18097        <entry>
18098         Creates a new physical replication slot named
18099         <parameter>slot_name</parameter>. The optional second parameter,
18100         when <literal>true</>, specifies that the <acronym>LSN</> for this
18101         replication slot be reserved immediately; otherwise
18102         the <acronym>LSN</> is reserved on first connection from a streaming
18103         replication client. Streaming changes from a physical slot is only
18104         possible with the streaming-replication protocol &mdash;
18105         see <xref linkend="protocol-replication">. This function corresponds
18106         to the replication protocol command <literal>CREATE_REPLICATION_SLOT
18107         ... PHYSICAL</literal>.
18108        </entry>
18109       </row>
18110       <row>
18111        <entry>
18112         <indexterm>
18113          <primary>pg_drop_replication_slot</primary>
18114         </indexterm>
18115         <literal><function>pg_drop_replication_slot(<parameter>slot_name</parameter> <type>name</type>)</function></literal>
18116        </entry>
18117        <entry>
18118         <type>void</type>
18119        </entry>
18120        <entry>
18121         Drops the physical or logical replication slot
18122         named <parameter>slot_name</parameter>. Same as replication protocol
18123         command <literal>DROP_REPLICATION_SLOT</>.
18124        </entry>
18125       </row>
18126
18127       <row>
18128        <entry>
18129         <indexterm>
18130          <primary>pg_create_logical_replication_slot</primary>
18131         </indexterm>
18132         <literal><function>pg_create_logical_replication_slot(<parameter>slot_name</parameter> <type>name</type>, <parameter>plugin</parameter> <type>name</type>)</function></literal>
18133        </entry>
18134        <entry>
18135         (<parameter>slot_name</parameter> <type>name</type>, <parameter>xlog_position</parameter> <type>pg_lsn</type>)
18136        </entry>
18137        <entry>
18138         Creates a new logical (decoding) replication slot named
18139         <parameter>slot_name</parameter> using the output plugin
18140         <parameter>plugin</parameter>.  A call to this function has the same
18141         effect as the replication protocol command
18142         <literal>CREATE_REPLICATION_SLOT ... LOGICAL</literal>.
18143        </entry>
18144       </row>
18145
18146       <row>
18147        <entry>
18148         <indexterm>
18149          <primary>pg_logical_slot_get_changes</primary>
18150         </indexterm>
18151         <literal><function>pg_logical_slot_get_changes(<parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>int</type>, VARIADIC <parameter>options</parameter> <type>text[]</type>)</function></literal>
18152        </entry>
18153        <entry>
18154         (<parameter>location</parameter> <type>pg_lsn</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>text</type>)
18155        </entry>
18156        <entry>
18157         Returns changes in the slot <parameter>slot_name</parameter>, starting
18158         from the point at which since changes have been consumed last.  If
18159         <parameter>upto_lsn</> and <parameter>upto_nchanges</> are NULL,
18160         logical decoding will continue until end of WAL.  If
18161         <parameter>upto_lsn</> is non-NULL, decoding will include only
18162         those transactions which commit prior to the specified LSN.  If
18163         <parameter>upto_nchanges</parameter> is non-NULL, decoding will
18164         stop when the number of rows produced by decoding exceeds
18165         the specified value.  Note, however, that the actual number of
18166         rows returned may be larger, since this limit is only checked after
18167         adding the rows produced when decoding each new transaction commit.
18168        </entry>
18169       </row>
18170
18171       <row>
18172        <entry>
18173         <indexterm>
18174          <primary>pg_logical_slot_peek_changes</primary>
18175         </indexterm>
18176         <literal><function>pg_logical_slot_peek_changes(<parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>int</type>, VARIADIC <parameter>options</parameter> <type>text[]</type>)</function></literal>
18177        </entry>
18178        <entry>
18179         (<parameter>location</parameter> <type>text</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>text</type>)
18180        </entry>
18181        <entry>
18182         Behaves just like
18183         the <function>pg_logical_slot_get_changes()</function> function,
18184         except that changes are not consumed; that is, they will be returned
18185         again on future calls.
18186        </entry>
18187       </row>
18188
18189       <row>
18190        <entry>
18191         <indexterm>
18192          <primary>pg_logical_slot_get_binary_changes</primary>
18193         </indexterm>
18194         <literal><function>pg_logical_slot_get_binary_changes(<parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>int</type>, VARIADIC <parameter>options</parameter> <type>text[]</type>)</function></literal>
18195        </entry>
18196        <entry>
18197         (<parameter>location</parameter> <type>pg_lsn</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>bytea</type>)
18198        </entry>
18199        <entry>
18200         Behaves just like
18201         the <function>pg_logical_slot_get_changes()</function> function,
18202         except that changes are returned as <type>bytea</type>.
18203        </entry>
18204       </row>
18205
18206       <row>
18207        <entry>
18208         <indexterm>
18209          <primary>pg_logical_slot_peek_binary_changes</primary>
18210         </indexterm>
18211         <literal><function>pg_logical_slot_peek_binary_changes(<parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>int</type>, VARIADIC <parameter>options</parameter> <type>text[]</type>)</function></literal>
18212        </entry>
18213        <entry>
18214         (<parameter>location</parameter> <type>pg_lsn</type>, <parameter>xid</parameter> <type>xid</type>, <parameter>data</parameter> <type>bytea</type>)
18215        </entry>
18216        <entry>
18217         Behaves just like
18218         the <function>pg_logical_slot_get_changes()</function> function,
18219         except that changes are returned as <type>bytea</type> and that
18220         changes are not consumed; that is, they will be returned again
18221         on future calls.
18222        </entry>
18223       </row>
18224
18225       <row>
18226        <entry id="pg-replication-origin-create">
18227         <indexterm>
18228          <primary>pg_replication_origin_create</primary>
18229         </indexterm>
18230         <literal><function>pg_replication_origin_create(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18231        </entry>
18232        <entry>
18233         <type>oid</type>
18234        </entry>
18235        <entry>
18236         Create a replication origin with the given external
18237         name, and return the internal id assigned to it.
18238        </entry>
18239       </row>
18240
18241       <row>
18242        <entry id="pg-replication-origin-drop">
18243         <indexterm>
18244          <primary>pg_replication_origin_drop</primary>
18245         </indexterm>
18246         <literal><function>pg_replication_origin_drop(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18247        </entry>
18248        <entry>
18249         void
18250        </entry>
18251        <entry>
18252         Delete a previously created replication origin, including any
18253         associated replay progress.
18254        </entry>
18255       </row>
18256
18257       <row>
18258        <entry>
18259         <indexterm>
18260          <primary>pg_replication_origin_oid</primary>
18261         </indexterm>
18262         <literal><function>pg_replication_origin_oid(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18263        </entry>
18264        <entry>
18265         <type>oid</type>
18266        </entry>
18267        <entry>
18268         Lookup a replication origin by name and return the internal id. If no
18269         corresponding replication origin is found an error is thrown.
18270        </entry>
18271       </row>
18272
18273       <row>
18274        <entry id="pg-replication-origin-session-setup">
18275         <indexterm>
18276          <primary>pg_replication_origin_session_setup</primary>
18277         </indexterm>
18278         <literal><function>pg_replication_origin_session_setup(<parameter>node_name</parameter> <type>text</type>)</function></literal>
18279        </entry>
18280        <entry>
18281         void
18282        </entry>
18283        <entry>
18284         Mark the current session as replaying from the given
18285         origin, allowing replay progress to be tracked.  Use
18286         <function>pg_replication_origin_session_reset</function> to revert.
18287         Can only be used if no previous origin is configured.
18288        </entry>
18289       </row>
18290
18291       <row>
18292        <entry>
18293         <indexterm>
18294          <primary>pg_replication_origin_session_reset</primary>
18295         </indexterm>
18296         <literal><function>pg_replication_origin_session_reset()</function></literal>
18297        </entry>
18298        <entry>
18299         void
18300        </entry>
18301        <entry>
18302         Cancel the effects
18303         of <function>pg_replication_origin_session_setup()</function>.
18304        </entry>
18305       </row>
18306
18307       <row>
18308        <entry>
18309         <indexterm>
18310          <primary>pg_replication_origin_session_is_setup</primary>
18311         </indexterm>
18312         <literal><function>pg_replication_origin_session_is_setup()</function></literal>
18313        </entry>
18314        <entry>
18315         <type>bool</type>
18316        </entry>
18317        <entry>
18318         Has a replication origin been configured in the current session?
18319        </entry>
18320       </row>
18321
18322       <row>
18323        <entry id="pg-replication-origin-session-progress">
18324         <indexterm>
18325          <primary>pg_replication_origin_session_progress</primary>
18326         </indexterm>
18327         <literal><function>pg_replication_origin_session_progress(<parameter>flush</parameter> <type>bool</type>)</function></literal>
18328        </entry>
18329        <entry>
18330         <type>pg_lsn</type>
18331        </entry>
18332        <entry>
18333         Return the replay position for the replication origin configured in
18334         the current session. The parameter <parameter>flush</parameter>
18335         determines whether the corresponding local transaction will be
18336         guaranteed to have been flushed to disk or not.
18337        </entry>
18338       </row>
18339
18340       <row>
18341        <entry id="pg-replication-origin-xact-setup">
18342         <indexterm>
18343          <primary>pg_replication_origin_xact_setup</primary>
18344         </indexterm>
18345         <literal><function>pg_replication_origin_xact_setup(<parameter>origin_lsn</parameter> <type>pg_lsn</type>, <parameter>origin_timestamp</parameter> <type>timestamptz</type>)</function></literal>
18346        </entry>
18347        <entry>
18348         void
18349        </entry>
18350        <entry>
18351         Mark the current transaction as replaying a transaction that has
18352         committed at the given <acronym>LSN</acronym> and timestamp. Can
18353         only be called when a replication origin has previously been
18354         configured using
18355         <function>pg_replication_origin_session_setup()</function>.
18356        </entry>
18357       </row>
18358
18359       <row>
18360        <entry id="pg-replication-origin-xact-reset">
18361         <indexterm>
18362          <primary>pg_replication_origin_xact_reset</primary>
18363         </indexterm>
18364         <literal><function>pg_replication_origin_xact_reset()</function></literal>
18365        </entry>
18366        <entry>
18367         void
18368        </entry>
18369        <entry>
18370         Cancel the effects of
18371         <function>pg_replication_origin_xact_setup()</function>.
18372        </entry>
18373       </row>
18374
18375       <row>
18376        <entry>
18377         <indexterm>
18378          <primary>pg_replication_origin_advance</primary>
18379         </indexterm>
18380         <literal>pg_replication_origin_advance<function>(<parameter>node_name</parameter> <type>text</type>, <parameter>pos</parameter> <type>pg_lsn</type>)</function></literal>
18381        </entry>
18382        <entry>
18383         void
18384        </entry>
18385        <entry>
18386         Set replication progress for the given node to the given
18387         position. This primarily is useful for setting up the initial position
18388         or a new position after configuration changes and similar. Be aware
18389         that careless use of this function can lead to inconsistently
18390         replicated data.
18391        </entry>
18392       </row>
18393
18394       <row>
18395        <entry id="pg-replication-origin-progress">
18396         <indexterm>
18397          <primary>pg_replication_origin_progress</primary>
18398         </indexterm>
18399         <literal><function>pg_replication_origin_progress(<parameter>node_name</parameter> <type>text</type>, <parameter>flush</parameter> <type>bool</type>)</function></literal>
18400        </entry>
18401        <entry>
18402         <type>pg_lsn</type>
18403        </entry>
18404        <entry>
18405         Return the replay position for the given replication origin. The
18406         parameter <parameter>flush</parameter> determines whether the
18407         corresponding local transaction will be guaranteed to have been
18408         flushed to disk or not.
18409        </entry>
18410       </row>
18411
18412       <row>
18413        <entry id="pg-logical-emit-message-text">
18414         <indexterm>
18415          <primary>pg_logical_emit_message</primary>
18416         </indexterm>
18417         <literal><function>pg_logical_emit_message(<parameter>transactional</parameter> <type>bool</type>, <parameter>prefix</parameter> <type>text</type>, <parameter>content</parameter> <type>text</type>)</function></literal>
18418        </entry>
18419        <entry>
18420         <type>pg_lsn</type>
18421        </entry>
18422        <entry>
18423         Emit text logical decoding message. This can be used to pass generic
18424         messages to logical decoding plugins through WAL. The parameter
18425         <parameter>transactional</parameter> specifies if the message should
18426         be part of current transaction or if it should be written immediately
18427         and decoded as soon as the logical decoding reads the record. The
18428         <parameter>prefix</parameter> is textual prefix used by the logical
18429         decoding plugins to easily recognize interesting messages for them.
18430         The <parameter>content</parameter> is the text of the message.
18431        </entry>
18432       </row>
18433
18434       <row>
18435        <entry id="pg-logical-emit-message-bytea">
18436         <literal><function>pg_logical_emit_message(<parameter>transactional</parameter> <type>bool</type>, <parameter>prefix</parameter> <type>text</type>, <parameter>content</parameter> <type>bytea</type>)</function></literal>
18437        </entry>
18438        <entry>
18439         <type>pg_lsn</type>
18440        </entry>
18441        <entry>
18442         Emit binary logical decoding message. This can be used to pass generic
18443         messages to logical decoding plugins through WAL. The parameter
18444         <parameter>transactional</parameter> specifies if the message should
18445         be part of current transaction or if it should be written immediately
18446         and decoded as soon as the logical decoding reads the record. The
18447         <parameter>prefix</parameter> is textual prefix used by the logical
18448         decoding plugins to easily recognize interesting messages for them.
18449         The <parameter>content</parameter> is the binary content of the
18450         message.
18451        </entry>
18452       </row>
18453
18454      </tbody>
18455     </tgroup>
18456    </table>
18457
18458   </sect2>
18459
18460   <sect2 id="functions-admin-dbobject">
18461    <title>Database Object Management Functions</title>
18462
18463    <para>
18464     The functions shown in <xref linkend="functions-admin-dbsize"> calculate
18465     the disk space usage of database objects.
18466    </para>
18467
18468    <indexterm>
18469     <primary>pg_column_size</primary>
18470    </indexterm>
18471    <indexterm>
18472     <primary>pg_database_size</primary>
18473    </indexterm>
18474    <indexterm>
18475     <primary>pg_indexes_size</primary>
18476    </indexterm>
18477    <indexterm>
18478     <primary>pg_relation_size</primary>
18479    </indexterm>
18480    <indexterm>
18481     <primary>pg_size_bytes</primary>
18482    </indexterm>
18483    <indexterm>
18484     <primary>pg_size_pretty</primary>
18485    </indexterm>
18486    <indexterm>
18487     <primary>pg_table_size</primary>
18488    </indexterm>
18489    <indexterm>
18490     <primary>pg_tablespace_size</primary>
18491    </indexterm>
18492    <indexterm>
18493     <primary>pg_total_relation_size</primary>
18494    </indexterm>
18495
18496    <table id="functions-admin-dbsize">
18497     <title>Database Object Size Functions</title>
18498     <tgroup cols="3">
18499      <thead>
18500       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18501       </row>
18502      </thead>
18503
18504      <tbody>
18505       <row>
18506        <entry><literal><function>pg_column_size(<type>any</type>)</function></literal></entry>
18507        <entry><type>int</type></entry>
18508        <entry>Number of bytes used to store a particular value (possibly compressed)</entry>
18509       </row>
18510       <row>
18511        <entry>
18512         <literal><function>pg_database_size(<type>oid</type>)</function></literal>
18513         </entry>
18514        <entry><type>bigint</type></entry>
18515        <entry>Disk space used by the database with the specified OID</entry>
18516       </row>
18517       <row>
18518        <entry>
18519         <literal><function>pg_database_size(<type>name</type>)</function></literal>
18520         </entry>
18521        <entry><type>bigint</type></entry>
18522        <entry>Disk space used by the database with the specified name</entry>
18523       </row>
18524       <row>
18525        <entry>
18526         <literal><function>pg_indexes_size(<type>regclass</type>)</function></literal>
18527         </entry>
18528        <entry><type>bigint</type></entry>
18529        <entry>
18530         Total disk space used by indexes attached to the specified table
18531        </entry>
18532       </row>
18533       <row>
18534        <entry>
18535         <literal><function>pg_relation_size(<parameter>relation</parameter> <type>regclass</type>, <parameter>fork</parameter> <type>text</type>)</function></literal>
18536         </entry>
18537        <entry><type>bigint</type></entry>
18538        <entry>
18539         Disk space used by the specified fork (<literal>'main'</literal>,
18540         <literal>'fsm'</literal>, <literal>'vm'</>, or <literal>'init'</>)
18541         of the specified table or index
18542        </entry>
18543       </row>
18544       <row>
18545        <entry>
18546         <literal><function>pg_relation_size(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
18547         </entry>
18548        <entry><type>bigint</type></entry>
18549        <entry>
18550         Shorthand for <literal>pg_relation_size(..., 'main')</literal>
18551        </entry>
18552       </row>
18553       <row>
18554        <entry>
18555         <literal><function>pg_size_bytes(<type>text</type>)</function></literal>
18556         </entry>
18557        <entry><type>bigint</type></entry>
18558        <entry>
18559          Converts a size in human-readable format with size units into bytes
18560        </entry>
18561       </row>
18562       <row>
18563        <entry>
18564         <literal><function>pg_size_pretty(<type>bigint</type>)</function></literal>
18565         </entry>
18566        <entry><type>text</type></entry>
18567        <entry>
18568          Converts a size in bytes expressed as a 64-bit integer into a
18569          human-readable format with size units
18570        </entry>
18571       </row>
18572       <row>
18573        <entry>
18574         <literal><function>pg_size_pretty(<type>numeric</type>)</function></literal>
18575         </entry>
18576        <entry><type>text</type></entry>
18577        <entry>
18578          Converts a size in bytes expressed as a numeric value into a
18579          human-readable format with size units
18580        </entry>
18581       </row>
18582       <row>
18583        <entry>
18584         <literal><function>pg_table_size(<type>regclass</type>)</function></literal>
18585         </entry>
18586        <entry><type>bigint</type></entry>
18587        <entry>
18588         Disk space used by the specified table, excluding indexes
18589         (but including TOAST, free space map, and visibility map)
18590        </entry>
18591       </row>
18592       <row>
18593        <entry>
18594         <literal><function>pg_tablespace_size(<type>oid</type>)</function></literal>
18595         </entry>
18596        <entry><type>bigint</type></entry>
18597        <entry>Disk space used by the tablespace with the specified OID</entry>
18598       </row>
18599       <row>
18600        <entry>
18601         <literal><function>pg_tablespace_size(<type>name</type>)</function></literal>
18602         </entry>
18603        <entry><type>bigint</type></entry>
18604        <entry>Disk space used by the tablespace with the specified name</entry>
18605       </row>
18606       <row>
18607        <entry>
18608         <literal><function>pg_total_relation_size(<type>regclass</type>)</function></literal>
18609         </entry>
18610        <entry><type>bigint</type></entry>
18611        <entry>
18612         Total disk space used by the specified table,
18613         including all indexes and <acronym>TOAST</> data
18614        </entry>
18615       </row>
18616      </tbody>
18617     </tgroup>
18618    </table>
18619
18620    <para>
18621     <function>pg_column_size</> shows the space used to store any individual
18622     data value.
18623    </para>
18624
18625    <para>
18626     <function>pg_total_relation_size</> accepts the OID or name of a
18627     table or toast table, and returns the total on-disk space used for
18628     that table, including all associated indexes.  This function is
18629     equivalent to <function>pg_table_size</function>
18630     <literal>+</> <function>pg_indexes_size</function>.
18631    </para>
18632
18633    <para>
18634     <function>pg_table_size</> accepts the OID or name of a table and
18635     returns the disk space needed for that table, exclusive of indexes.
18636     (TOAST space, free space map, and visibility map are included.)
18637    </para>
18638
18639    <para>
18640     <function>pg_indexes_size</> accepts the OID or name of a table and
18641     returns the total disk space used by all the indexes attached to that
18642     table.
18643    </para>
18644
18645    <para>
18646     <function>pg_database_size</function> and <function>pg_tablespace_size</>
18647     accept the OID or name of a database or tablespace, and return the total
18648     disk space used therein.  To use <function>pg_database_size</function>,
18649     you must have <literal>CONNECT</> permission on the specified database
18650     (which is granted by default).  To use <function>pg_tablespace_size</>,
18651     you must have <literal>CREATE</> permission on the specified tablespace,
18652     unless it is the default tablespace for the current database.
18653    </para>
18654
18655    <para>
18656     <function>pg_relation_size</> accepts the OID or name of a table, index
18657     or toast table, and returns the on-disk size in bytes of one fork of
18658     that relation.  (Note that for most purposes it is more convenient to
18659     use the higher-level functions <function>pg_total_relation_size</>
18660     or <function>pg_table_size</>, which sum the sizes of all forks.)
18661     With one argument, it returns the size of the main data fork of the
18662     relation.  The second argument can be provided to specify which fork
18663     to examine:
18664     <itemizedlist spacing="compact">
18665      <listitem>
18666       <para>
18667        <literal>'main'</literal> returns the size of the main
18668        data fork of the relation.
18669       </para>
18670      </listitem>
18671      <listitem>
18672       <para>
18673        <literal>'fsm'</literal> returns the size of the Free Space Map
18674        (see <xref linkend="storage-fsm">) associated with the relation.
18675       </para>
18676      </listitem>
18677      <listitem>
18678       <para>
18679        <literal>'vm'</literal> returns the size of the Visibility Map
18680        (see <xref linkend="storage-vm">) associated with the relation.
18681       </para>
18682      </listitem>
18683      <listitem>
18684       <para>
18685        <literal>'init'</literal> returns the size of the initialization
18686        fork, if any, associated with the relation.
18687       </para>
18688      </listitem>
18689     </itemizedlist>
18690    </para>
18691
18692    <para>
18693     <function>pg_size_pretty</> can be used to format the result of one of
18694     the other functions in a human-readable way, using bytes, kB, MB, GB or TB
18695     as appropriate.
18696    </para>
18697
18698    <para>
18699     <function>pg_size_bytes</> can be used to get the size in bytes from a
18700     string in human-readable format. The input may have units of bytes, kB,
18701     MB, GB or TB, and is parsed case-insensitively. If no units are specified,
18702     bytes are assumed.
18703    </para>
18704
18705    <note>
18706     <para>
18707      The units kB, MB, GB and TB used by the functions
18708      <function>pg_size_pretty</> and <function>pg_size_bytes</> are defined
18709      using powers of 2 rather than powers of 10, so 1kB is 1024 bytes, 1MB is
18710      1024<superscript>2</> = 1048576 bytes, and so on.
18711     </para>
18712    </note>
18713
18714    <para>
18715     The functions above that operate on tables or indexes accept a
18716     <type>regclass</> argument, which is simply the OID of the table or index
18717     in the <structname>pg_class</> system catalog.  You do not have to look up
18718     the OID by hand, however, since the <type>regclass</> data type's input
18719     converter will do the work for you.  Just write the table name enclosed in
18720     single quotes so that it looks like a literal constant.  For compatibility
18721     with the handling of ordinary <acronym>SQL</acronym> names, the string
18722     will be converted to lower case unless it contains double quotes around
18723     the table name.
18724    </para>
18725
18726    <para>
18727     If an OID that does not represent an existing object is passed as
18728     argument to one of the above functions, NULL is returned.
18729    </para>
18730
18731    <para>
18732     The functions shown in <xref linkend="functions-admin-dblocation"> assist
18733     in identifying the specific disk files associated with database objects.
18734    </para>
18735
18736    <indexterm>
18737     <primary>pg_relation_filenode</primary>
18738    </indexterm>
18739    <indexterm>
18740     <primary>pg_relation_filepath</primary>
18741    </indexterm>
18742    <indexterm>
18743     <primary>pg_filenode_relation</primary>
18744    </indexterm>
18745
18746    <table id="functions-admin-dblocation">
18747     <title>Database Object Location Functions</title>
18748     <tgroup cols="3">
18749      <thead>
18750       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18751       </row>
18752      </thead>
18753
18754      <tbody>
18755       <row>
18756        <entry>
18757         <literal><function>pg_relation_filenode(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
18758         </entry>
18759        <entry><type>oid</type></entry>
18760        <entry>
18761         Filenode number of the specified relation
18762        </entry>
18763       </row>
18764       <row>
18765        <entry>
18766         <literal><function>pg_relation_filepath(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
18767         </entry>
18768        <entry><type>text</type></entry>
18769        <entry>
18770         File path name of the specified relation
18771        </entry>
18772       </row>
18773       <row>
18774        <entry>
18775         <literal><function>pg_filenode_relation(<parameter>tablespace</parameter> <type>oid</type>, <parameter>filenode</parameter> <type>oid</type>)</function></literal>
18776         </entry>
18777        <entry><type>regclass</type></entry>
18778        <entry>
18779         Find the relation associated with a given tablespace and filenode
18780        </entry>
18781       </row>
18782      </tbody>
18783     </tgroup>
18784    </table>
18785
18786    <para>
18787     <function>pg_relation_filenode</> accepts the OID or name of a table,
18788     index, sequence, or toast table, and returns the <quote>filenode</> number
18789     currently assigned to it.  The filenode is the base component of the file
18790     name(s) used for the relation (see <xref linkend="storage-file-layout">
18791     for more information).  For most tables the result is the same as
18792     <structname>pg_class</>.<structfield>relfilenode</>, but for certain
18793     system catalogs <structfield>relfilenode</> is zero and this function must
18794     be used to get the correct value.  The function returns NULL if passed
18795     a relation that does not have storage, such as a view.
18796    </para>
18797
18798    <para>
18799     <function>pg_relation_filepath</> is similar to
18800     <function>pg_relation_filenode</>, but it returns the entire file path name
18801     (relative to the database cluster's data directory <varname>PGDATA</>) of
18802     the relation.
18803    </para>
18804
18805    <para>
18806     <function>pg_filenode_relation</> is the reverse of
18807     <function>pg_relation_filenode</>. Given a <quote>tablespace</> OID and
18808     a <quote>filenode</>, it returns the associated relation's OID. For a table
18809     in the database's default tablespace, the tablespace can be specified as 0.
18810    </para>
18811
18812   </sect2>
18813
18814   <sect2 id="functions-admin-index">
18815    <title>Index Maintenance Functions</title>
18816
18817    <indexterm>
18818     <primary>brin_summarize_new_values</primary>
18819    </indexterm>
18820
18821    <indexterm>
18822     <primary>gin_clean_pending_list</primary>
18823    </indexterm>
18824
18825    <para>
18826     <xref linkend="functions-admin-index-table"> shows the functions
18827     available for index maintenance tasks.
18828     These functions cannot be executed during recovery.
18829     Use of these functions is restricted to superusers and the owner
18830     of the given index.
18831    </para>
18832
18833    <table id="functions-admin-index-table">
18834     <title>Index Maintenance Functions</title>
18835     <tgroup cols="3">
18836      <thead>
18837       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
18838      </thead>
18839
18840      <tbody>
18841       <row>
18842        <entry>
18843         <literal><function>brin_summarize_new_values(<parameter>index_oid</> <type>regclass</>)</function></literal>
18844        </entry>
18845        <entry><type>integer</type></entry>
18846        <entry>summarize page ranges not already summarized</entry>
18847       </row>
18848       <row>
18849        <entry>
18850         <literal><function>gin_clean_pending_list(<parameter>index</> <type>regclass</>)</function></literal>
18851        </entry>
18852        <entry><type>bigint</type></entry>
18853        <entry>move GIN pending list entries into main index structure</entry>
18854       </row>
18855      </tbody>
18856     </tgroup>
18857    </table>
18858
18859    <para>
18860     <function>brin_summarize_new_values</> receives a BRIN index OID as
18861     argument and inspects the index to find page ranges in the base table
18862     that are not currently summarized by the index; for any such range
18863     it creates a new summary index tuple by scanning the table pages.
18864     It returns the number of new page range summaries that were inserted
18865     into the index.
18866    </para>
18867
18868    <para>
18869     <function>gin_clean_pending_list</> accepts the OID or name of
18870     a GIN index and cleans up the pending list of the specified GIN index
18871     by moving entries in it to the main GIN data structure in bulk.
18872     It returns the number of pages cleaned up from the pending list.
18873     Note that if the argument is a GIN index built with <literal>fastupdate</>
18874     option disabled, the cleanup does not happen and the return value is 0
18875     because the index doesn't have a pending list.
18876     Please see <xref linkend="gin-fast-update"> and <xref linkend="gin-tips">
18877     for details of the pending list and <literal>fastupdate</> option.
18878    </para>
18879
18880   </sect2>
18881
18882   <sect2 id="functions-admin-genfile">
18883    <title>Generic File Access Functions</title>
18884
18885    <para>
18886     The functions shown in <xref
18887     linkend="functions-admin-genfile-table"> provide native access to
18888     files on the machine hosting the server. Only files within the
18889     database cluster directory and the <varname>log_directory</> can be
18890     accessed.  Use a relative path for files in the cluster directory,
18891     and a path matching the <varname>log_directory</> configuration setting
18892     for log files.  Use of these functions is restricted to superusers.
18893    </para>
18894
18895    <table id="functions-admin-genfile-table">
18896     <title>Generic File Access Functions</title>
18897     <tgroup cols="3">
18898      <thead>
18899       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
18900       </row>
18901      </thead>
18902
18903      <tbody>
18904       <row>
18905        <entry>
18906         <literal><function>pg_ls_dir(<parameter>dirname</> <type>text</> [, <parameter>missing_ok</> <type>boolean</>, <parameter>include_dot_dirs</> <type>boolean</>])</function></literal>
18907        </entry>
18908        <entry><type>setof text</type></entry>
18909        <entry>
18910         List the contents of a directory.
18911        </entry>
18912       </row>
18913       <row>
18914        <entry>
18915         <literal><function>pg_read_file(<parameter>filename</> <type>text</> [, <parameter>offset</> <type>bigint</>, <parameter>length</> <type>bigint</> [, <parameter>missing_ok</> <type>boolean</>] ])</function></literal>
18916        </entry>
18917        <entry><type>text</type></entry>
18918        <entry>
18919         Return the contents of a text file.
18920        </entry>
18921       </row>
18922       <row>
18923        <entry>
18924         <literal><function>pg_read_binary_file(<parameter>filename</> <type>text</> [, <parameter>offset</> <type>bigint</>, <parameter>length</> <type>bigint</> [, <parameter>missing_ok</> <type>boolean</>] ])</function></literal>
18925        </entry>
18926        <entry><type>bytea</type></entry>
18927        <entry>
18928         Return the contents of a file.
18929        </entry>
18930       </row>
18931       <row>
18932        <entry>
18933         <literal><function>pg_stat_file(<parameter>filename</> <type>text</>[, <parameter>missing_ok</> <type>boolean</type>])</function></literal>
18934        </entry>
18935        <entry><type>record</type></entry>
18936        <entry>
18937         Return information about a file.
18938        </entry>
18939       </row>
18940      </tbody>
18941     </tgroup>
18942    </table>
18943
18944    <para>
18945     All of these functions take an optional <parameter>missing_ok</> parameter,
18946     which specifies the behavior when the file or directory does not exist.
18947     If <literal>true</literal>, the function returns NULL (except
18948     <function>pg_ls_dir</>, which returns an empty result set). If
18949     <literal>false</>, an error is raised. The default is <literal>false</>.
18950    </para>
18951
18952    <indexterm>
18953     <primary>pg_ls_dir</primary>
18954    </indexterm>
18955    <para>
18956     <function>pg_ls_dir</> returns the names of all files (and directories
18957     and other special files) in the specified directory. The <parameter>
18958     include_dot_dirs</> indicates whether <quote>.</> and <quote>..</> are
18959     included in the result set. The default is to exclude them
18960     (<literal>false</>), but including them can be useful when
18961     <parameter>missing_ok</> is <literal>true</literal>, to distinguish an
18962     empty directory from an non-existent directory.
18963    </para>
18964
18965    <indexterm>
18966     <primary>pg_read_file</primary>
18967    </indexterm>
18968    <para>
18969     <function>pg_read_file</> returns part of a text file, starting
18970     at the given <parameter>offset</>, returning at most <parameter>length</>
18971     bytes (less if the end of file is reached first).  If <parameter>offset</>
18972     is negative, it is relative to the end of the file.
18973     If <parameter>offset</> and <parameter>length</> are omitted, the entire
18974     file is returned.  The bytes read from the file are interpreted as a string
18975     in the server encoding; an error is thrown if they are not valid in that
18976     encoding.
18977    </para>
18978
18979    <indexterm>
18980     <primary>pg_read_binary_file</primary>
18981    </indexterm>
18982    <para>
18983     <function>pg_read_binary_file</> is similar to
18984     <function>pg_read_file</>, except that the result is a <type>bytea</type> value;
18985     accordingly, no encoding checks are performed.
18986     In combination with the <function>convert_from</> function, this function
18987     can be used to read a file in a specified encoding:
18988 <programlisting>
18989 SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');
18990 </programlisting>
18991    </para>
18992
18993    <indexterm>
18994     <primary>pg_stat_file</primary>
18995    </indexterm>
18996    <para>
18997     <function>pg_stat_file</> returns a record containing the file
18998     size, last accessed time stamp, last modified time stamp,
18999     last file status change time stamp (Unix platforms only),
19000     file creation time stamp (Windows only), and a <type>boolean</type>
19001     indicating if it is a directory.  Typical usages include:
19002 <programlisting>
19003 SELECT * FROM pg_stat_file('filename');
19004 SELECT (pg_stat_file('filename')).modification;
19005 </programlisting>
19006    </para>
19007
19008   </sect2>
19009
19010   <sect2 id="functions-advisory-locks">
19011    <title>Advisory Lock Functions</title>
19012
19013    <para>
19014     The functions shown in <xref linkend="functions-advisory-locks-table">
19015     manage advisory locks.  For details about proper use of these functions,
19016     see <xref linkend="advisory-locks">.
19017    </para>
19018
19019    <table id="functions-advisory-locks-table">
19020     <title>Advisory Lock Functions</title>
19021     <tgroup cols="3">
19022      <thead>
19023       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
19024       </row>
19025      </thead>
19026
19027      <tbody>
19028       <row>
19029        <entry>
19030         <literal><function>pg_advisory_lock(<parameter>key</> <type>bigint</>)</function></literal>
19031        </entry>
19032        <entry><type>void</type></entry>
19033        <entry>Obtain exclusive session level advisory lock</entry>
19034       </row>
19035       <row>
19036        <entry>
19037         <literal><function>pg_advisory_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19038        </entry>
19039        <entry><type>void</type></entry>
19040        <entry>Obtain exclusive session level advisory lock</entry>
19041       </row>
19042       <row>
19043        <entry>
19044         <literal><function>pg_advisory_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19045        </entry>
19046        <entry><type>void</type></entry>
19047        <entry>Obtain shared session level advisory lock</entry>
19048       </row>
19049       <row>
19050        <entry>
19051         <literal><function>pg_advisory_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19052        </entry>
19053        <entry><type>void</type></entry>
19054        <entry>Obtain shared session level advisory lock</entry>
19055       </row>
19056       <row>
19057        <entry>
19058         <literal><function>pg_advisory_unlock(<parameter>key</> <type>bigint</>)</function></literal>
19059        </entry>
19060        <entry><type>boolean</type></entry>
19061        <entry>Release an exclusive session level advisory lock</entry>
19062       </row>
19063       <row>
19064        <entry>
19065         <literal><function>pg_advisory_unlock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19066        </entry>
19067        <entry><type>boolean</type></entry>
19068        <entry>Release an exclusive session level advisory lock</entry>
19069       </row>
19070       <row>
19071        <entry>
19072         <literal><function>pg_advisory_unlock_all()</function></literal>
19073        </entry>
19074        <entry><type>void</type></entry>
19075        <entry>Release all session level advisory locks held by the current session</entry>
19076       </row>
19077       <row>
19078        <entry>
19079         <literal><function>pg_advisory_unlock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19080        </entry>
19081        <entry><type>boolean</type></entry>
19082        <entry>Release a shared session level advisory lock</entry>
19083       </row>
19084       <row>
19085        <entry>
19086         <literal><function>pg_advisory_unlock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19087        </entry>
19088        <entry><type>boolean</type></entry>
19089        <entry>Release a shared session level advisory lock</entry>
19090       </row>
19091       <row>
19092        <entry>
19093         <literal><function>pg_advisory_xact_lock(<parameter>key</> <type>bigint</>)</function></literal>
19094        </entry>
19095        <entry><type>void</type></entry>
19096        <entry>Obtain exclusive transaction level advisory lock</entry>
19097       </row>
19098       <row>
19099        <entry>
19100         <literal><function>pg_advisory_xact_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19101        </entry>
19102        <entry><type>void</type></entry>
19103        <entry>Obtain exclusive transaction level advisory lock</entry>
19104       </row>
19105       <row>
19106        <entry>
19107         <literal><function>pg_advisory_xact_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19108        </entry>
19109        <entry><type>void</type></entry>
19110        <entry>Obtain shared transaction level advisory lock</entry>
19111       </row>
19112       <row>
19113        <entry>
19114         <literal><function>pg_advisory_xact_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19115        </entry>
19116        <entry><type>void</type></entry>
19117        <entry>Obtain shared transaction level advisory lock</entry>
19118       </row>
19119       <row>
19120        <entry>
19121         <literal><function>pg_try_advisory_lock(<parameter>key</> <type>bigint</>)</function></literal>
19122        </entry>
19123        <entry><type>boolean</type></entry>
19124        <entry>Obtain exclusive session level advisory lock if available</entry>
19125       </row>
19126       <row>
19127        <entry>
19128         <literal><function>pg_try_advisory_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19129        </entry>
19130        <entry><type>boolean</type></entry>
19131        <entry>Obtain exclusive session level advisory lock if available</entry>
19132       </row>
19133       <row>
19134        <entry>
19135         <literal><function>pg_try_advisory_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19136        </entry>
19137        <entry><type>boolean</type></entry>
19138        <entry>Obtain shared session level advisory lock if available</entry>
19139       </row>
19140       <row>
19141        <entry>
19142         <literal><function>pg_try_advisory_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19143        </entry>
19144        <entry><type>boolean</type></entry>
19145        <entry>Obtain shared session level advisory lock if available</entry>
19146       </row>
19147       <row>
19148        <entry>
19149         <literal><function>pg_try_advisory_xact_lock(<parameter>key</> <type>bigint</>)</function></literal>
19150        </entry>
19151        <entry><type>boolean</type></entry>
19152        <entry>Obtain exclusive transaction level advisory lock if available</entry>
19153       </row>
19154       <row>
19155        <entry>
19156         <literal><function>pg_try_advisory_xact_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19157        </entry>
19158        <entry><type>boolean</type></entry>
19159        <entry>Obtain exclusive transaction level advisory lock if available</entry>
19160       </row>
19161       <row>
19162        <entry>
19163         <literal><function>pg_try_advisory_xact_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
19164        </entry>
19165        <entry><type>boolean</type></entry>
19166        <entry>Obtain shared transaction level advisory lock if available</entry>
19167       </row>
19168       <row>
19169        <entry>
19170         <literal><function>pg_try_advisory_xact_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
19171        </entry>
19172        <entry><type>boolean</type></entry>
19173        <entry>Obtain shared transaction level advisory lock if available</entry>
19174       </row>
19175      </tbody>
19176     </tgroup>
19177    </table>
19178
19179    <indexterm>
19180     <primary>pg_advisory_lock</primary>
19181    </indexterm>
19182    <para>
19183     <function>pg_advisory_lock</> locks an application-defined resource,
19184     which can be identified either by a single 64-bit key value or two
19185     32-bit key values (note that these two key spaces do not overlap).
19186     If another session already holds a lock on the same resource identifier,
19187     this function will wait until the resource becomes available.  The lock
19188     is exclusive.  Multiple lock requests stack, so that if the same resource
19189     is locked three times it must then be unlocked three times to be
19190     released for other sessions' use.
19191    </para>
19192
19193    <indexterm>
19194     <primary>pg_advisory_lock_shared</primary>
19195    </indexterm>
19196    <para>
19197     <function>pg_advisory_lock_shared</> works the same as
19198     <function>pg_advisory_lock</>,
19199     except the lock can be shared with other sessions requesting shared locks.
19200     Only would-be exclusive lockers are locked out.
19201    </para>
19202
19203    <indexterm>
19204     <primary>pg_try_advisory_lock</primary>
19205    </indexterm>
19206    <para>
19207     <function>pg_try_advisory_lock</> is similar to
19208     <function>pg_advisory_lock</>, except the function will not wait for the
19209     lock to become available.  It will either obtain the lock immediately and
19210     return <literal>true</>, or return <literal>false</> if the lock cannot be
19211     acquired immediately.
19212    </para>
19213
19214    <indexterm>
19215     <primary>pg_try_advisory_lock_shared</primary>
19216    </indexterm>
19217    <para>
19218     <function>pg_try_advisory_lock_shared</> works the same as
19219     <function>pg_try_advisory_lock</>, except it attempts to acquire
19220     a shared rather than an exclusive lock.
19221    </para>
19222
19223    <indexterm>
19224     <primary>pg_advisory_unlock</primary>
19225    </indexterm>
19226    <para>
19227     <function>pg_advisory_unlock</> will release a previously-acquired
19228     exclusive session level advisory lock.  It
19229     returns <literal>true</> if the lock is successfully released.
19230     If the lock was not held, it will return <literal>false</>,
19231     and in addition, an SQL warning will be reported by the server.
19232    </para>
19233
19234    <indexterm>
19235     <primary>pg_advisory_unlock_shared</primary>
19236    </indexterm>
19237    <para>
19238     <function>pg_advisory_unlock_shared</> works the same as
19239     <function>pg_advisory_unlock</>,
19240     except it releases a shared session level advisory lock.
19241    </para>
19242
19243    <indexterm>
19244     <primary>pg_advisory_unlock_all</primary>
19245    </indexterm>
19246    <para>
19247     <function>pg_advisory_unlock_all</> will release all session level advisory
19248     locks held by the current session.  (This function is implicitly invoked
19249     at session end, even if the client disconnects ungracefully.)
19250    </para>
19251
19252    <indexterm>
19253     <primary>pg_advisory_xact_lock</primary>
19254    </indexterm>
19255    <para>
19256     <function>pg_advisory_xact_lock</> works the same as
19257     <function>pg_advisory_lock</>, except the lock is automatically released
19258     at the end of the current transaction and cannot be released explicitly.
19259    </para>
19260
19261    <indexterm>
19262     <primary>pg_advisory_xact_lock_shared</primary>
19263    </indexterm>
19264    <para>
19265     <function>pg_advisory_xact_lock_shared</> works the same as
19266     <function>pg_advisory_lock_shared</>, except the lock is automatically released
19267     at the end of the current transaction and cannot be released explicitly.
19268    </para>
19269
19270    <indexterm>
19271     <primary>pg_try_advisory_xact_lock</primary>
19272    </indexterm>
19273    <para>
19274     <function>pg_try_advisory_xact_lock</> works the same as
19275     <function>pg_try_advisory_lock</>, except the lock, if acquired,
19276     is automatically released at the end of the current transaction and
19277     cannot be released explicitly.
19278    </para>
19279
19280    <indexterm>
19281     <primary>pg_try_advisory_xact_lock_shared</primary>
19282    </indexterm>
19283    <para>
19284     <function>pg_try_advisory_xact_lock_shared</> works the same as
19285     <function>pg_try_advisory_lock_shared</>, except the lock, if acquired,
19286     is automatically released at the end of the current transaction and
19287     cannot be released explicitly.
19288    </para>
19289
19290   </sect2>
19291
19292   </sect1>
19293
19294   <sect1 id="functions-trigger">
19295    <title>Trigger Functions</title>
19296
19297    <indexterm>
19298      <primary>suppress_redundant_updates_trigger</primary>
19299    </indexterm>
19300
19301    <para>
19302       Currently <productname>PostgreSQL</> provides one built in trigger
19303       function, <function>suppress_redundant_updates_trigger</>,
19304       which will prevent any update
19305       that does not actually change the data in the row from taking place, in
19306       contrast to the normal behavior which always performs the update
19307       regardless of whether or not the data has changed. (This normal behavior
19308       makes updates run faster, since no checking is required, and is also
19309       useful in certain cases.)
19310     </para>
19311
19312     <para>
19313       Ideally, you should normally avoid running updates that don't actually
19314       change the data in the record. Redundant updates can cost considerable
19315       unnecessary time, especially if there are lots of indexes to alter,
19316       and space in dead rows that will eventually have to be vacuumed.
19317       However, detecting such situations in client code is not
19318       always easy, or even possible, and writing expressions to detect
19319       them can be error-prone. An alternative is to use
19320       <function>suppress_redundant_updates_trigger</>, which will skip
19321       updates that don't change the data. You should use this with care,
19322       however. The trigger takes a small but non-trivial time for each record,
19323       so if most of the records affected by an update are actually changed,
19324       use of this trigger will actually make the update run slower.
19325     </para>
19326
19327     <para>
19328       The <function>suppress_redundant_updates_trigger</> function can be
19329       added to a table like this:
19330 <programlisting>
19331 CREATE TRIGGER z_min_update
19332 BEFORE UPDATE ON tablename
19333 FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger();
19334 </programlisting>
19335       In most cases, you would want to fire this trigger last for each row.
19336       Bearing in mind that triggers fire in name order, you would then
19337       choose a trigger name that comes after the name of any other trigger
19338       you might have on the table.
19339     </para>
19340     <para>
19341        For more information about creating triggers, see
19342         <xref linkend="SQL-CREATETRIGGER">.
19343     </para>
19344   </sect1>
19345
19346   <sect1 id="functions-event-triggers">
19347    <title>Event Trigger Functions</title>
19348
19349    <para>
19350     <productname>PostgreSQL</> provides these helper functions
19351     to retrieve information from event triggers.
19352    </para>
19353
19354    <para>
19355     For more information about event triggers,
19356     see <xref linkend="event-triggers">.
19357    </para>
19358
19359   <sect2 id="pg-event-trigger-ddl-command-end-functions">
19360    <title>Capturing Changes at Command End</title>
19361
19362    <indexterm>
19363     <primary>pg_event_trigger_ddl_commands</primary>
19364    </indexterm>
19365
19366    <para>
19367     <function>pg_event_trigger_ddl_commands</> returns a list of
19368     <acronym>DDL</acronym> commands executed by each user action,
19369     when invoked in a function attached to a
19370     <literal>ddl_command_end</> event trigger.  If called in any other
19371     context, an error is raised.
19372     <function>pg_event_trigger_ddl_commands</> returns one row for each
19373     base command executed; some commands that are a single SQL sentence
19374     may return more than one row.  This function returns the following
19375     columns:
19376
19377     <informaltable>
19378      <tgroup cols="3">
19379       <thead>
19380        <row>
19381         <entry>Name</entry>
19382         <entry>Type</entry>
19383         <entry>Description</entry>
19384        </row>
19385       </thead>
19386
19387       <tbody>
19388        <row>
19389         <entry><literal>classid</literal></entry>
19390         <entry><type>Oid</type></entry>
19391         <entry>OID of catalog the object belongs in</entry>
19392        </row>
19393        <row>
19394         <entry><literal>objid</literal></entry>
19395         <entry><type>Oid</type></entry>
19396         <entry>OID of the object in the catalog</entry>
19397        </row>
19398        <row>
19399         <entry><literal>objsubid</literal></entry>
19400         <entry><type>integer</type></entry>
19401         <entry>Object sub-id (e.g. attribute number for columns)</entry>
19402        </row>
19403        <row>
19404         <entry><literal>command_tag</literal></entry>
19405         <entry><type>text</type></entry>
19406         <entry>command tag</entry>
19407        </row>
19408        <row>
19409         <entry><literal>object_type</literal></entry>
19410         <entry><type>text</type></entry>
19411         <entry>Type of the object</entry>
19412        </row>
19413        <row>
19414         <entry><literal>schema_name</literal></entry>
19415         <entry><type>text</type></entry>
19416         <entry>
19417          Name of the schema the object belongs in, if any; otherwise <literal>NULL</>.
19418          No quoting is applied.
19419         </entry>
19420        </row>
19421        <row>
19422         <entry><literal>object_identity</literal></entry>
19423         <entry><type>text</type></entry>
19424         <entry>
19425          Text rendering of the object identity, schema-qualified. Each and every
19426          identifier present in the identity is quoted if necessary.
19427         </entry>
19428        </row>
19429        <row>
19430         <entry><literal>in_extension</literal></entry>
19431         <entry><type>bool</type></entry>
19432         <entry>whether the command is part of an extension script</entry>
19433        </row>
19434        <row>
19435         <entry><literal>command</literal></entry>
19436         <entry><type>pg_ddl_command</type></entry>
19437         <entry>
19438          A complete representation of the command, in internal format.
19439          This cannot be output directly, but it can be passed to other
19440          functions to obtain different pieces of information about the
19441          command.
19442         </entry>
19443        </row>
19444       </tbody>
19445      </tgroup>
19446     </informaltable>
19447    </para>
19448   </sect2>
19449
19450   <sect2 id="pg-event-trigger-sql-drop-functions">
19451    <title>Processing Objects Dropped by a DDL Command</title>
19452
19453    <indexterm>
19454      <primary>pg_event_trigger_dropped_objects</primary>
19455    </indexterm>
19456
19457    <para>
19458     <function>pg_event_trigger_dropped_objects</> returns a list of all objects
19459     dropped by the command in whose <literal>sql_drop</> event it is called.
19460     If called in any other context,
19461     <function>pg_event_trigger_dropped_objects</> raises an error.
19462     <function>pg_event_trigger_dropped_objects</> returns the following columns:
19463
19464     <informaltable>
19465      <tgroup cols="3">
19466       <thead>
19467        <row>
19468         <entry>Name</entry>
19469         <entry>Type</entry>
19470         <entry>Description</entry>
19471        </row>
19472       </thead>
19473
19474       <tbody>
19475        <row>
19476         <entry><literal>classid</literal></entry>
19477         <entry><type>Oid</type></entry>
19478         <entry>OID of catalog the object belonged in</entry>
19479        </row>
19480        <row>
19481         <entry><literal>objid</literal></entry>
19482         <entry><type>Oid</type></entry>
19483         <entry>OID the object had within the catalog</entry>
19484        </row>
19485        <row>
19486         <entry><literal>objsubid</literal></entry>
19487         <entry><type>int32</type></entry>
19488         <entry>Object sub-id (e.g. attribute number for columns)</entry>
19489        </row>
19490        <row>
19491         <entry><literal>original</literal></entry>
19492         <entry><type>bool</type></entry>
19493         <entry>Flag used to identify the root object(s) of the deletion</entry>
19494        </row>
19495        <row>
19496         <entry><literal>normal</literal></entry>
19497         <entry><type>bool</type></entry>
19498         <entry>
19499          Flag indicating that there's a normal dependency relationship
19500          in the dependency graph leading to this object
19501         </entry>
19502        </row>
19503        <row>
19504         <entry><literal>is_temporary</literal></entry>
19505         <entry><type>bool</type></entry>
19506         <entry>
19507          Flag indicating that the object was a temporary object.
19508         </entry>
19509        </row>
19510        <row>
19511         <entry><literal>object_type</literal></entry>
19512         <entry><type>text</type></entry>
19513         <entry>Type of the object</entry>
19514        </row>
19515        <row>
19516         <entry><literal>schema_name</literal></entry>
19517         <entry><type>text</type></entry>
19518         <entry>
19519          Name of the schema the object belonged in, if any; otherwise <literal>NULL</>.
19520          No quoting is applied.
19521         </entry>
19522        </row>
19523        <row>
19524         <entry><literal>object_name</literal></entry>
19525         <entry><type>text</type></entry>
19526         <entry>
19527          Name of the object, if the combination of schema and name can be
19528          used as a unique identifier for the object; otherwise <literal>NULL</>.
19529          No quoting is applied, and name is never schema-qualified.
19530         </entry>
19531        </row>
19532        <row>
19533         <entry><literal>object_identity</literal></entry>
19534         <entry><type>text</type></entry>
19535         <entry>
19536          Text rendering of the object identity, schema-qualified. Each and every
19537          identifier present in the identity is quoted if necessary.
19538         </entry>
19539        </row>
19540        <row>
19541         <entry><literal>address_names</literal></entry>
19542         <entry><type>text[]</type></entry>
19543         <entry>
19544          An array that, together with <literal>object_type</literal> and
19545          <literal>address_args</literal>,
19546          can be used by the <function>pg_get_object_address()</function> to
19547          recreate the object address in a remote server containing an
19548          identically named object of the same kind.
19549         </entry>
19550        </row>
19551        <row>
19552         <entry><literal>address_args</literal></entry>
19553         <entry><type>text[]</type></entry>
19554         <entry>
19555          Complement for <literal>address_names</literal> above.
19556         </entry>
19557        </row>
19558       </tbody>
19559      </tgroup>
19560     </informaltable>
19561    </para>
19562
19563    <para>
19564     The <function>pg_event_trigger_dropped_objects</> function can be used
19565     in an event trigger like this:
19566 <programlisting>
19567 CREATE FUNCTION test_event_trigger_for_drops()
19568         RETURNS event_trigger LANGUAGE plpgsql AS $$
19569 DECLARE
19570     obj record;
19571 BEGIN
19572     FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects()
19573     LOOP
19574         RAISE NOTICE '% dropped object: % %.% %',
19575                      tg_tag,
19576                      obj.object_type,
19577                      obj.schema_name,
19578                      obj.object_name,
19579                      obj.object_identity;
19580     END LOOP;
19581 END
19582 $$;
19583 CREATE EVENT TRIGGER test_event_trigger_for_drops
19584    ON sql_drop
19585    EXECUTE PROCEDURE test_event_trigger_for_drops();
19586 </programlisting>
19587     </para>
19588   </sect2>
19589
19590   <sect2 id="pg-event-trigger-table-rewrite-functions">
19591    <title>Handling a Table Rewrite Event</title>
19592
19593    <para>
19594     The functions shown in
19595     <xref linkend="functions-event-trigger-table-rewrite">
19596     provide information about a table for which a
19597     <literal>table_rewrite</> event has just been called.
19598     If called in any other context, an error is raised.
19599    </para>
19600
19601    <table id="functions-event-trigger-table-rewrite">
19602     <title>Table Rewrite information</title>
19603     <tgroup cols="3">
19604      <thead>
19605       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
19606      </thead>
19607
19608      <tbody>
19609       <row>
19610        <entry>
19611         <indexterm><primary>pg_event_trigger_table_rewrite_oid</primary></indexterm>
19612         <literal><function>pg_event_trigger_table_rewrite_oid()</function></literal>
19613        </entry>
19614        <entry><type>Oid</type></entry>
19615        <entry>The OID of the table about to be rewritten.</entry>
19616       </row>
19617
19618       <row>
19619        <entry>
19620         <indexterm><primary>pg_event_trigger_table_rewrite_reason</primary></indexterm>
19621         <literal><function>pg_event_trigger_table_rewrite_reason()</function></literal>
19622        </entry>
19623        <entry><type>int</type></entry>
19624        <entry>
19625         The reason code(s) explaining the reason for rewriting. The exact
19626         meaning of the codes is release dependent.
19627        </entry>
19628       </row>
19629      </tbody>
19630     </tgroup>
19631    </table>
19632
19633    <para>
19634     The <function>pg_event_trigger_table_rewrite_oid</> function can be used
19635     in an event trigger like this:
19636 <programlisting>
19637 CREATE FUNCTION test_event_trigger_table_rewrite_oid()
19638  RETURNS event_trigger
19639  LANGUAGE plpgsql AS
19640 $$
19641 BEGIN
19642   RAISE NOTICE 'rewriting table % for reason %',
19643                 pg_event_trigger_table_rewrite_oid()::regclass,
19644                 pg_event_trigger_table_rewrite_reason();
19645 END;
19646 $$;
19647
19648 CREATE EVENT TRIGGER test_table_rewrite_oid
19649                   ON table_rewrite
19650    EXECUTE PROCEDURE test_event_trigger_table_rewrite_oid();
19651 </programlisting>
19652     </para>
19653   </sect2>
19654   </sect1>
19655
19656 </chapter>