]> granicus.if.org Git - postgresql/blob - doc/src/sgml/func.sgml
Add LOCALTIME and LOCALTIMESTAMP functions per SQL99 standard.
[postgresql] / doc / src / sgml / func.sgml
1 <!--
2 $Header: /cvsroot/pgsql/doc/src/sgml/func.sgml,v 1.102 2002/06/15 02:59:55 thomas Exp $
3 PostgreSQL documentation
4 -->
5
6  <chapter id="functions">
7   <title>Functions and Operators</title>
8
9   <indexterm zone="functions">
10    <primary>functions</primary>
11   </indexterm>
12
13   <indexterm zone="functions">
14    <primary>operators</primary>
15   </indexterm>
16
17   <para>
18    <productname>PostgreSQL</productname> provides a large number of
19    functions and operators for the built-in data types.  Users can also
20    define their own functions and operators, as described in the
21    <citetitle>Programmer's Guide</citetitle>.  The
22    <application>psql</application> commands <command>\df</command> and
23    <command>\do</command> can be used to show the list of all actually
24    available functions and operators, respectively.
25   </para>
26
27   <para>
28    If you are concerned about portability then take note that most of
29    the functions and operators described in this chapter, with the
30    exception of the most trivial arithmetic and comparison operators
31    and some explicitly marked functions, are not specified by the
32    <acronym>SQL</acronym>
33    standard. Some of this extended functionality is present in other
34    <acronym>RDBMS</acronym> products, and in many cases this
35    functionality is compatible and consistent between various products.
36   </para>
37
38
39   <sect1 id="functions-logical">
40    <title>Logical Operators</title>
41
42    <indexterm zone="functions-logical">
43     <primary>operators</primary>
44     <secondary>logical</secondary>
45    </indexterm>
46
47    <indexterm>
48     <primary>Boolean</primary>
49     <secondary>operators</secondary>
50     <see>operators, logical</see>
51    </indexterm>
52
53    <para>
54     The usual logical operators are available:
55
56     <indexterm>
57      <primary>and</primary>
58      <secondary>operator</secondary>
59     </indexterm>
60
61     <indexterm>
62      <primary>or</primary>
63      <secondary>operator</secondary>
64     </indexterm>
65
66     <indexterm>
67      <primary>not</primary>
68      <secondary>operator</secondary>
69     </indexterm>
70
71     <simplelist>
72      <member>AND</member>
73      <member>OR</member>
74      <member>NOT</member>
75     </simplelist>
76
77     <acronym>SQL</acronym> uses a three-valued Boolean logic where NULL represents
78     <quote>unknown</quote>.  Observe the following truth tables:
79
80     <informaltable>
81      <tgroup cols="4">
82       <thead>
83        <row>
84         <entry><replaceable>a</replaceable></entry>
85         <entry><replaceable>b</replaceable></entry>
86         <entry><replaceable>a</replaceable> AND <replaceable>b</replaceable></entry>
87         <entry><replaceable>a</replaceable> OR <replaceable>b</replaceable></entry>
88        </row>
89       </thead>
90
91       <tbody>
92        <row>
93         <entry>TRUE</entry>
94         <entry>TRUE</entry>
95         <entry>TRUE</entry>
96         <entry>TRUE</entry>
97        </row>
98
99        <row>
100         <entry>TRUE</entry>
101         <entry>FALSE</entry>
102         <entry>FALSE</entry>
103         <entry>TRUE</entry>
104        </row>
105
106        <row>
107         <entry>TRUE</entry>
108         <entry>NULL</entry>
109         <entry>NULL</entry>
110         <entry>TRUE</entry>
111        </row>
112
113        <row>
114         <entry>FALSE</entry>
115         <entry>FALSE</entry>
116         <entry>FALSE</entry>
117         <entry>FALSE</entry>
118        </row>
119
120        <row>
121         <entry>FALSE</entry>
122         <entry>NULL</entry>
123         <entry>FALSE</entry>
124         <entry>NULL</entry>
125        </row>
126
127        <row>
128         <entry>NULL</entry>
129         <entry>NULL</entry>
130         <entry>NULL</entry>
131         <entry>NULL</entry>
132        </row>
133       </tbody>
134      </tgroup>
135     </informaltable>
136
137     <informaltable>
138      <tgroup cols="2">
139       <thead>
140        <row>
141         <entry><replaceable>a</replaceable></entry>
142         <entry>NOT <replaceable>a</replaceable></entry>
143        </row>
144       </thead>
145
146       <tbody>
147        <row>
148         <entry>TRUE</entry>
149         <entry>FALSE</entry>
150        </row>
151
152        <row>
153         <entry>FALSE</entry>
154         <entry>TRUE</entry>
155        </row>
156
157        <row>
158         <entry>NULL</entry>
159         <entry>NULL</entry>
160        </row>
161       </tbody>
162      </tgroup>
163     </informaltable>
164    </para>
165   </sect1>
166
167   <sect1 id="functions-comparison">
168    <title>Comparison Operators</title>
169
170    <indexterm zone="functions-comparison">
171     <primary>comparison</primary>
172     <secondary>operators</secondary>
173    </indexterm>
174
175    <table>
176     <title>Comparison Operators</title>
177     <tgroup cols="2">
178      <thead>
179       <row>
180        <entry>Operator</entry>
181        <entry>Description</entry>
182       </row>
183      </thead>
184
185      <tbody>
186       <row>
187        <entry> <literal>&lt;</literal> </entry>
188        <entry>less than</entry>
189       </row>
190
191       <row>
192        <entry> <literal>&gt;</literal> </entry>
193        <entry>greater than</entry>
194       </row>
195
196       <row>
197        <entry> <literal>&lt;=</literal> </entry>
198        <entry>less than or equal to</entry>
199       </row>
200
201       <row>
202        <entry> <literal>&gt;=</literal> </entry>
203        <entry>greater than or equal to</entry>
204       </row>
205
206       <row>
207        <entry> <literal>=</literal> </entry>
208        <entry>equal</entry>
209       </row>
210
211       <row>
212        <entry> <literal>&lt;&gt;</literal> or <literal>!=</literal> </entry>
213        <entry>not equal</entry>
214       </row>
215      </tbody>
216     </tgroup>
217    </table>
218
219    <note>
220     <para>
221      The <literal>!=</literal> operator is converted to
222      <literal>&lt;&gt;</literal> in the parser stage.  It is not
223      possible to implement <literal>!=</literal> and
224      <literal>&lt;&gt;</literal> operators that do different things.
225     </para>
226    </note>
227
228    <para>
229     Comparison operators are available for all data types where this
230     makes sense.  All comparison operators are binary operators that
231     return values of type <type>boolean</type>; expressions like
232     <literal>1 &lt; 2 &lt; 3</literal> are not valid (because there is
233     no <literal>&lt;</literal> operator to compare a Boolean value with
234     <literal>3</literal>).
235    </para>
236
237    <para>
238     <indexterm>
239      <primary>between</primary>
240     </indexterm>
241     In addition to the comparison operators, the special
242     <token>BETWEEN</token> construct is available.
243     <synopsis>
244 <replaceable>a</replaceable> BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
245     </synopsis>
246     is equivalent to
247     <synopsis>
248 <replaceable>a</replaceable> &gt;= <replaceable>x</replaceable> AND <replaceable>a</replaceable>able> &lt;= <replaceable>y</replaceable>
249     </synopsis>
250     Similarly,
251     <synopsis>
252 <replaceable>a</replaceable> NOT BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
253     </synopsis>
254     is equivalent to
255     <synopsis>
256 <replaceable>a</replaceable> &lt; <replaceable>x</replaceable> OR <replaceable>a</replaceable>able> &gt; <replaceable>y</replaceable>
257     </synopsis>
258     There is no difference between the two respective forms apart from
259     the <acronym>CPU</acronym> cycles required to rewrite the first one
260     into the second one internally.
261    </para>
262
263    <para>
264     To check whether a value is or is not NULL, use the constructs
265     <synopsis>
266 <replaceable>expression</replaceable> IS NULL
267 <replaceable>expression</replaceable> IS NOT NULL
268     </synopsis>
269     or the equivalent, but less standard, constructs
270     <synopsis>
271 <replaceable>expression</replaceable> ISNULL
272 <replaceable>expression</replaceable> NOTNULL
273     </synopsis>
274    </para>
275
276    <para>
277     Do <emphasis>not</emphasis> write
278     <literal><replaceable>expression</replaceable> = NULL</literal>
279     because NULL is not <quote>equal to</quote> NULL.  (NULL represents
280     an unknown value, and it is not known whether two unknown values are
281     equal.)
282    </para>
283
284    <para>
285     Some applications may (incorrectly) require that
286     <literal><replaceable>expression</replaceable> = NULL</literal>
287     returns true if <replaceable>expression</replaceable> evaluates to
288     the NULL value.  To support these applications, the run-time option
289     <varname>transform_null_equals</varname> can be turned on (e.g.,
290     <literal>SET transform_null_equals TO ON;</literal>).
291     <productname>PostgreSQL</productname> will then convert
292     <literal>x = NULL</literal> clauses to
293     <literal>x IS NULL</literal>.  This was 
294     the default behavior in releases 6.5 through 7.1.
295    </para>
296
297    <para>
298     Boolean values can also be tested using the constructs
299     <synopsis>
300 <replaceable>expression</replaceable> IS TRUE
301 <replaceable>expression</replaceable> IS NOT TRUE
302 <replaceable>expression</replaceable> IS FALSE
303 <replaceable>expression</replaceable> IS NOT FALSE
304 <replaceable>expression</replaceable> IS UNKNOWN
305 <replaceable>expression</replaceable> IS NOT UNKNOWN
306     </synopsis>
307     These are similar to <literal>IS NULL</literal> in that they will
308     always return TRUE or FALSE, never NULL, even when the operand is NULL.
309     A NULL input is treated as the logical value UNKNOWN.
310    </para>
311   </sect1>
312
313   <sect1 id="functions-math">
314    <title>Mathematical Functions and Operators</title>
315
316    <para>
317     Mathematical operators are provided for many
318     <productname>PostgreSQL</productname> types. For types without
319     common mathematical conventions for all possible permutations 
320     (e.g. date/time types) we
321     describe the actual behavior in subsequent sections.
322    </para>
323
324    <table>
325     <title>Mathematical Operators</title>
326
327     <tgroup cols="4">
328      <thead>
329       <row>
330        <entry>Name</entry>
331        <entry>Description</entry>
332        <entry>Example</entry>
333        <entry>Result</entry>
334       </row>
335      </thead>
336
337      <tbody>
338       <row>
339        <entry> <literal>+</literal> </entry>
340        <entry>Addition</entry>
341        <entry>2 + 3</entry>
342        <entry>5</entry>
343       </row>
344
345       <row>
346        <entry> <literal>-</literal> </entry>
347        <entry>Subtraction</entry>
348        <entry>2 - 3</entry>
349        <entry>-1</entry>
350       </row>
351
352       <row>
353        <entry> <literal>*</literal> </entry>
354        <entry>Multiplication</entry>
355        <entry>2 * 3</entry>
356        <entry>6</entry>
357       </row>
358
359       <row>
360        <entry> <literal>/</literal> </entry>
361        <entry>Division (integer division truncates results)</entry>
362        <entry>4 / 2</entry>
363        <entry>2</entry>
364       </row>
365
366       <row>
367        <entry> <literal>%</literal> </entry>
368        <entry>Modulo (remainder)</entry>
369        <entry>5 % 4</entry>
370        <entry>1</entry>
371       </row>
372
373       <row>
374        <entry> <literal>^</literal> </entry>
375        <entry>Exponentiation</entry>
376        <entry>2.0 ^ 3.0</entry>
377        <entry>8</entry>
378       </row>
379
380       <row>
381        <entry> <literal>|/</literal> </entry>
382        <entry>Square root</entry>
383        <entry>|/ 25.0</entry>
384        <entry>5</entry>
385       </row>
386
387       <row>
388        <entry> <literal>||/</literal> </entry>
389        <entry>Cube root</entry>
390        <entry>||/ 27.0</entry>
391        <entry>3</entry>
392       </row>
393
394       <row>
395        <entry> <literal>!</literal> </entry>
396        <entry>Factorial</entry>
397        <entry>5 !</entry>
398        <entry>120</entry>
399       </row>
400
401       <row>
402        <entry> <literal>!!</literal> </entry>
403        <entry>Factorial (prefix operator)</entry>
404        <entry>!! 5</entry>
405        <entry>120</entry>
406       </row>
407
408       <row>
409        <entry> <literal>@</literal> </entry>
410        <entry>Absolute value</entry>
411        <entry>@ -5.0</entry>
412        <entry>5</entry>
413       </row>
414
415       <row>
416        <entry> <literal>&amp;</literal> </entry>
417        <entry>Binary AND</entry>
418        <entry>91 & 15</entry>
419        <entry>11</entry>
420       </row>
421
422       <row>
423        <entry> <literal>|</literal> </entry>
424        <entry>Binary OR</entry>
425        <entry>32 | 3</entry>
426        <entry>35</entry>
427       </row>
428
429       <row>
430        <entry> <literal>#</literal> </entry>
431        <entry>Binary XOR</entry>
432        <entry>17 # 5</entry>
433        <entry>20</entry>
434       </row>
435
436       <row>
437        <entry> <literal>~</literal> </entry>
438        <entry>Binary NOT</entry>
439        <entry>~1</entry>
440        <entry>-2</entry>
441       </row>
442
443       <row>
444        <entry> &lt;&lt; </entry>
445        <entry>Binary shift left</entry>
446        <entry>1 &lt;&lt; 4</entry>
447        <entry>16</entry>
448       </row>
449
450       <row>
451        <entry> &gt;&gt; </entry>
452        <entry>Binary shift right</entry>
453        <entry>8 &gt;&gt; 2</entry>
454        <entry>2</entry>
455       </row>
456
457      </tbody>
458     </tgroup>
459    </table>
460
461    <para>
462     The <quote>binary</quote> operators are also available for the bit
463     string types <type>BIT</type> and <type>BIT VARYING</type>.
464
465     <table>
466      <title>Bit String Binary Operators</title>
467
468      <tgroup cols="2">
469       <thead>
470        <row>
471         <entry>Example</entry>
472         <entry>Result</entry>
473        </row>
474       </thead>
475
476       <tbody>
477        <row>
478         <entry>B'10001' & B'01101'</entry>
479         <entry>00001</entry>
480        </row>
481        <row>
482         <entry>B'10001' | B'01101'</entry>
483         <entry>11101</entry>
484        </row>
485        <row>
486         <entry>B'10001' # B'01101'</entry>
487         <entry>11110</entry>
488        </row>
489        <row>
490         <entry>~ B'10001'</entry>
491         <entry>01110</entry>
492        </row>
493        <row>
494         <entry>B'10001' << 3</entry>
495         <entry>01000</entry>
496        </row>
497        <row>
498         <entry>B'10001' >> 2</entry>
499         <entry>00100</entry>
500        </row>
501       </tbody>
502      </tgroup>
503     </table>
504
505     Bit string arguments to <literal>&</literal>, <literal>|</literal>,
506     and <literal>#</literal> must be of equal length.  When bit
507     shifting, the original length of the string is preserved, as shown
508     here.
509    </para>
510
511    <table tocentry="1">
512     <title>Mathematical Functions</title>
513     <tgroup cols="5">
514      <thead>
515       <row>
516        <entry>Function</entry>
517        <entry>Return Type</entry>
518        <entry>Description</entry>
519        <entry>Example</entry>
520        <entry>Result</entry>
521       </row>
522      </thead>
523
524      <tbody>
525       <row>
526        <entry><function>abs</function>(<replaceable>x</replaceable>)</entry>
527        <entry>(same as x)</entry>
528        <entry>absolute value</entry>
529        <entry><literal>abs(-17.4)</literal></entry>
530        <entry>17.4</entry>
531       </row>
532
533       <row>
534        <entry><function>cbrt</function>(<type>dp</type>)</entry>
535        <entry><type>dp</type></entry>
536        <entry>cube root</entry>
537        <entry><literal>cbrt(27.0)</literal></entry>
538        <entry>3</entry>
539       </row>
540
541       <row>
542        <entry><function>ceil</function>(<type>numeric</type>)</entry>
543        <entry><type>numeric</type></entry>
544        <entry>smallest integer not less than argument</entry>
545        <entry><literal>ceil(-42.8)</literal></entry>
546        <entry>-42</entry>
547       </row>
548
549       <row>
550        <entry><function>degrees</function>(<type>dp</type>)</entry>
551        <entry><type>dp</type></entry>
552        <entry>radians to degrees</entry>
553        <entry><literal>degrees(0.5)</literal></entry>
554        <entry>28.6478897565412</entry>
555       </row>
556
557       <row>
558        <entry><function>exp</function>(<type>dp</type>)</entry>
559        <entry><type>dp</type></entry>
560        <entry>exponential</entry>
561        <entry><literal>exp(1.0)</literal></entry>
562        <entry>2.71828182845905</entry>
563       </row>
564
565       <row>
566        <entry><function>floor</function>(<type>numeric</type>)</entry>
567        <entry><type>numeric</type></entry>
568        <entry>largest integer not greater than argument</entry>
569        <entry><literal>floor(-42.8)</literal></entry>
570        <entry>-43</entry>
571       </row>
572
573       <row>
574        <entry><function>ln</function>(<type>dp</type>)</entry>
575        <entry><type>dp</type></entry>
576        <entry>natural logarithm</entry>
577        <entry><literal>ln(2.0)</literal></entry>
578        <entry>0.693147180559945</entry>
579       </row>
580
581       <row>
582        <entry><function>log</function>(<type>dp</type>)</entry>
583        <entry><type>dp</type></entry>
584        <entry>base 10 logarithm</entry>
585        <entry><literal>log(100.0)</literal></entry>
586        <entry>2</entry>
587       </row>
588
589       <row>
590        <entry><function>log</function>(<parameter>b</parameter> <type>numeric</type>,
591         <parameter>x</parameter> <type>numeric</type>)</entry>
592        <entry><type>numeric</type></entry>
593        <entry>logarithm to base <parameter>b</parameter></entry>
594        <entry><literal>log(2.0, 64.0)</literal></entry>
595        <entry>6.0000000000</entry>
596       </row>
597
598       <row>
599        <entry><function>mod</function>(<parameter>y</parameter>,
600         <parameter>x</parameter>)</entry>
601        <entry>(same as argument types)</entry>
602        <entry>remainder of <parameter>y</parameter>/<parameter>x</parameter></entry>
603        <entry><literal>mod(9,4)</literal></entry>
604        <entry>1</entry>
605       </row>
606
607       <row>
608        <entry><function>pi</function>()</entry>
609        <entry><type>dp</type></entry>
610        <entry><quote>Pi</quote> constant</entry>
611        <entry><literal>pi()</literal></entry>
612        <entry>3.14159265358979</entry>
613       </row>
614
615       <row>
616        <entry><function>pow</function>(<parameter>e</parameter> <type>dp</type>,
617         <parameter>n</parameter> <type>dp</type>)</entry>
618        <entry><type>dp</type></entry>
619        <entry>raise a number to exponent <parameter>e</parameter></entry>
620        <entry><literal>pow(9.0, 3.0)</literal></entry>
621        <entry>729</entry>
622       </row>
623
624       <row>
625        <entry><function>radians</function>(<type>dp</type>)</entry>
626        <entry><type>dp</type></entry>
627        <entry>degrees to radians</entry>
628        <entry><literal>radians(45.0)</literal></entry>
629        <entry>0.785398163397448</entry>
630       </row>
631
632       <row>
633        <entry><function>random</function>()</entry>
634        <entry><type>dp</type></entry>
635        <entry>value between 0.0 to 1.0</entry>
636        <entry><literal>random()</literal></entry>
637        <entry></entry>
638       </row>
639
640       <row>
641        <entry><function>round</function>(<type>dp</type>)</entry>
642        <entry><type>dp</type></entry>
643        <entry>round to nearest integer</entry>
644        <entry><literal>round(42.4)</literal></entry>
645        <entry>42</entry>
646       </row>
647
648       <row>
649        <entry><function>round</function>(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>integer</type>)</entry>
650        <entry><type>numeric</type></entry>
651        <entry>round to <parameter>s</parameter> decimal places</entry>
652        <entry><literal>round(42.4382, 2)</literal></entry>
653        <entry>42.44</entry>
654       </row>
655 <!--
656      <row>
657       <entry><function>setseed</function>(<replaceable>new-seed</replaceable>)</entry>
658       <entry>set seed for subsequent random() calls</entry>
659       <entry><literal>setseed(0.54823)</literal></entry>
660       <entry></entry>
661      </row>
662 -->
663       <row>
664        <entry><function>sign</function>(<type>numeric</type>)</entry>
665        <entry><type>numeric</type></entry>
666        <entry>sign of the argument (-1, 0, +1)</entry>
667        <entry><literal>sign(-8.4)</literal></entry>
668        <entry>-1</entry>
669       </row>
670
671       <row>
672        <entry><function>sqrt</function>(<type>dp</type>)</entry>
673        <entry><type>dp</type></entry>
674        <entry>square root</entry>
675        <entry><literal>sqrt(2.0)</literal></entry>
676        <entry>1.4142135623731</entry>
677       </row>
678
679       <row>
680        <entry><function>trunc</function>(<type>dp</type>)</entry>
681        <entry><type>dp</type></entry>
682        <entry>truncate toward zero</entry>
683        <entry><literal>trunc(42.8)</literal></entry>
684        <entry>42</entry>
685       </row>
686
687       <row>
688        <entry><function>trunc</function>(<type>numeric</type>,
689         <parameter>r</parameter>rameter> <type>integer</type>)</entry>
690        <entry><type>numeric</type></entry>
691        <entry>truncate to <parameter>s</parameter> decimal places</entry>
692        <entry><literal>trunc(42.4382, 2)</literal></entry>
693        <entry>42.43</entry>
694       </row>
695
696      </tbody>
697     </tgroup>
698    </table>
699
700    <para>
701     In the table above, <literal>dp</literal> indicates <type>double precision</type>.
702     The functions <function>exp</function>, <function>ln</function>,
703     <function>log</function>, <function>pow</function>,
704     <function>round</function> (1 argument), <function>sqrt</function>,
705     and <function>trunc</function> (1 argument) are also available for
706     the type <type>numeric</type> in place of
707     <type>double precision</type>.
708     Functions returning a <type>numeric</type> result take
709     <type>numeric</type> input arguments, unless otherwise specified.
710     Many of these functions are implemented on top
711     of the host system's C library; accuracy and behavior in boundary cases
712     could therefore vary depending on the host system.
713    </para>
714
715    <table>
716     <title>Trigonometric Functions</title>
717
718     <tgroup cols="2">
719      <thead>
720       <row>
721        <entry>Function</entry>
722        <entry>Description</entry>
723       </row>
724      </thead>
725
726      <tbody>
727       <row>
728        <entry><function>acos</function>(<replaceable>x</replaceable>)</entry>
729        <entry>inverse cosine</entry>
730       </row>
731
732       <row>
733        <entry><function>asin</function>(<replaceable>x</replaceable>)</entry>
734        <entry>inverse sine</entry>
735       </row>
736
737       <row>
738        <entry><function>atan</function>(<replaceable>x</replaceable>)</entry>
739        <entry>inverse tangent</entry>
740       </row>
741
742       <row>
743        <entry><function>atan2</function>(<replaceable>x</replaceable>,
744         <replaceable>y</replaceable>)</entry>
745        <entry>inverse tangent of
746         <replaceable>a</replaceable>aceable>/<replaceable>x</replaceable></entry>
747       </row>
748
749       <row>
750        <entry><function>cos</function>(<replaceable>x</replaceable>)</entry>
751        <entry>cosine</entry>
752       </row>
753
754       <row>
755        <entry><function>cot</function>(<replaceable>x</replaceable>)</entry>
756        <entry>cotangent</entry>
757       </row>
758
759       <row>
760        <entry><function>sin</function>(<replaceable>x</replaceable>)</entry>
761        <entry>sine</entry>
762       </row>
763
764       <row>
765        <entry><function>tan</function>(<replaceable>x</replaceable>)</entry>
766        <entry>tangent</entry>
767       </row>
768      </tbody>
769     </tgroup>
770    </table>
771
772    <para>
773     All trigonometric functions have arguments and return values of
774     type <type>double precision</type>.
775    </para>
776
777   </sect1>
778
779
780   <sect1 id="functions-string">
781    <title>String Functions and Operators</title>
782
783    <para>
784     This section describes functions and operators for examining and
785     manipulating string values.  Strings in this context include values
786     of all the types <type>CHARACTER</type>, <type>CHARACTER
787      VARYING</type>, and <type>TEXT</type>.  Unless otherwise noted, all
788     of the functions listed below work on all of these types, but be
789     wary of potential effects of the automatic padding when using the
790     <type>CHARACTER</type> type.  Generally, the functions described
791     here also work on data of non-string types by converting that data
792     to a string representation first.  Some functions also exist
793     natively for bit-string types.
794    </para>
795
796    <para>
797     <acronym>SQL</acronym> defines some string functions with a special syntax where
798     certain keywords rather than commas are used to separate the
799     arguments.  Details are in <xref linkend="functions-string-sql">.
800     These functions are also implemented using the regular syntax for
801     function invocation.  (See <xref linkend="functions-string-other">.)
802    </para>
803
804    <table id="functions-string-sql">
805     <title><acronym>SQL</acronym> String Functions and Operators</title>
806     <tgroup cols="5">
807      <thead>
808       <row>
809        <entry>Function</entry>
810        <entry>Return Type</entry>
811        <entry>Description</entry>
812        <entry>Example</entry>
813        <entry>Result</entry>  
814       </row>
815      </thead>
816
817      <tbody>
818       <row>
819        <entry> <parameter>string</parameter> <literal>||</literal>
820         <parameter>string</parameter> </entry>
821        <entry> <type>text</type> </entry>
822        <entry>
823         string concatenation
824         <indexterm>
825          <primary>character strings</primary>
826          <secondary>concatenation</secondary>
827         </indexterm>
828        </entry>
829        <entry><literal>'Postgre' || 'SQL'</literal></entry>
830        <entry><literal>PostgreSQL</literal></entry>
831       </row>
832
833       <row>
834        <entry><function>bit_length</function>(<parameter>string</parameter>)</entry>
835        <entry><type>integer</type></entry>
836        <entry>number of bits in string</entry>
837        <entry><literal>bit_length('jose')</literal></entry>
838        <entry><literal>32</literal></entry>
839       </row>
840
841       <row>
842        <entry><function>char_length</function>(<parameter>string</parameter>) or <function>character_length</function>(<parameter>string</parameter>)</entry>
843        <entry><type>integer</type></entry>
844        <entry>
845         number of characters in string
846         <indexterm>
847          <primary>character strings</primary>
848          <secondary>length</secondary>
849         </indexterm>
850         <indexterm>
851          <primary>length</primary>
852          <secondary>character strings</secondary>
853          <see>character strings, length</see>
854         </indexterm>
855        </entry>
856        <entry><literal>char_length('jose')</literal></entry>
857        <entry><literal>4</literal></entry>
858       </row>
859
860       <row>
861        <entry><function>lower</function>(<parameter>string</parameter>)</entry>
862        <entry><type>text</type></entry>
863        <entry>Convert string to lower case.</entry>
864        <entry><literal>lower('TOM')</literal></entry>
865        <entry><literal>tom</literal></entry>
866       </row>
867
868       <row>
869        <entry><function>octet_length</function>(<parameter>string</parameter>)</entry>
870        <entry><type>integer</type></entry>
871        <entry>number of bytes in string</entry>
872        <entry><literal>octet_length('jose')</literal></entry>
873        <entry><literal>4</literal></entry>
874       </row>
875
876       <row>
877        <entry><function>overlay</function>(<parameter>string</parameter> placing <parameter>string</parameter> from <type>integer</type> <optional>for <type>integer</type></optional>)</entry>
878        <entry><type>text</type></entry>
879        <entry>
880         insert substring
881         <indexterm>
882          <primary>overlay</primary>
883         </indexterm>
884        </entry>
885        <entry><literal>overlay('Txxxxas' placing 'hom' from 2 for 4)</literal></entry>
886        <entry><literal>Thomas</literal></entry>
887       </row>
888
889       <row>
890        <entry><function>position</function>(<parameter>substring</parameter> in <parameter>string</parameter>)</entry>
891        <entry><type>integer</type></entry>
892        <entry>location of specified substring</entry>
893        <entry><literal>position('om' in 'Thomas')</literal></entry>
894        <entry><literal>3</literal></entry>
895       </row>
896
897       <row>
898        <entry><function>substring</function>(<parameter>string</parameter> <optional>from <type>integer</type></optional> <optional>for <type>integer</type></optional>)</entry>
899        <entry><type>text</type></entry>
900        <entry>
901         extract substring
902         <indexterm>
903          <primary>substring</primary>
904         </indexterm>
905        </entry>
906        <entry><literal>substring('Thomas' from 2 for 3)</literal></entry>
907        <entry><literal>hom</literal></entry>
908       </row>
909
910       <row>
911        <entry><function>substring</function>(<parameter>string</parameter> <optional>from <replaceable>pattern</replaceable></optional> <optional>for <replaceable>escape</replaceable></optional>)</entry>
912        <entry><type>text</type></entry>
913        <entry>
914         extract regular expression
915         <indexterm>
916          <primary>substring</primary>
917         </indexterm>
918        </entry>
919        <entry><literal>substring('Thomas' from 'mas$' for <optional>escape '\\'</optional>)</literal></entry>
920        <entry><literal>mas</literal></entry>
921       </row>
922
923       <row>
924        <entry>
925         <function>trim</function>(<optional>leading | trailing | both</optional>
926         <optional><parameter>characters</parameter></optional> from
927         <parameter>string</parameter>)
928        </entry>
929        <entry><type>text</type></entry>
930        <entry>
931         Removes the longest string containing only the
932         <parameter>characters</parameter> (a space by default) from the
933         beginning/end/both ends of the <parameter>string</parameter>.
934        </entry>
935        <entry><literal>trim(both 'x' from 'xTomxx')</literal></entry>
936        <entry><literal>Tom</literal></entry>
937       </row>
938
939       <row>
940        <entry><function>upper</function>(<parameter>string</parameter>)</entry>
941        <entry><type>text</type></entry>
942        <entry>Convert string to upper case.</entry>
943        <entry><literal>upper('tom')</literal></entry>
944        <entry><literal>TOM</literal></entry>
945       </row>
946      </tbody>
947     </tgroup>
948    </table>
949
950    <para>
951     Additional string manipulation functions are available and are
952     listed below.  Some of them are used internally to implement the
953     <acronym>SQL</acronym>-standard string functions listed above.
954    </para>
955
956    <table id="functions-string-other">
957     <title>Other String Functions</title>
958     <tgroup cols="5">
959      <thead>
960       <row>
961        <entry>Function</entry>
962        <entry>Return Type</entry>
963        <entry>Description</entry>
964        <entry>Example</entry>
965        <entry>Result</entry>
966       </row>
967      </thead>
968
969      <tbody>
970       <row>
971        <entry><function>ascii</function>(<type>text</type>)</entry>
972        <entry>integer</entry>
973        <entry>Returns the <acronym>ASCII</acronym> code of the first character of the argument.</entry>
974        <entry><literal>ascii('x')</literal></entry>
975        <entry><literal>120</literal></entry>
976       </row>
977
978       <row>
979        <entry><function>btrim</function>(<parameter>string</parameter> <type>text</type>, <parameter>trim</parameter> <type>text</type>)</entry>
980        <entry><type>text</type></entry>
981        <entry>
982         Remove (trim) the longest string consisting only of characters
983         in <parameter>trim</parameter> from the start and end of
984         <parameter>string</parameter>.
985        </entry>
986        <entry><literal>btrim('xyxtrimyyx','xy')</literal></entry>
987        <entry><literal>trim</literal></entry>
988       </row>
989
990       <row>
991        <entry><function>chr</function>(<type>integer</type>)</entry>
992        <entry><type>text</type></entry>
993        <entry>Returns the character with the given <acronym>ASCII</acronym> code.</entry>
994        <entry><literal>chr(65)</literal></entry>
995        <entry><literal>A</literal></entry>
996       </row>
997
998       <row>
999        <entry>
1000         <function>convert</function>(<parameter>string</parameter>
1001         <type>text</type>,
1002         <optional><parameter>src_encoding</parameter> <type>name</type>,</optional>
1003         <parameter>dest_encoding</parameter> <type>name</type>)
1004        </entry>
1005        <entry><type>text</type></entry>
1006        <entry>
1007         Converts string using <parameter>dest_encoding</parameter>.
1008         The original encoding is specified by
1009         <parameter>src_encoding</parameter>.  If
1010         <parameter>src_encoding</parameter> is omitted, database
1011         encoding is assumed.
1012        </entry>
1013        <entry><literal>convert('text_in_unicode', 'UNICODE', 'LATIN1')</literal></entry>
1014        <entry><literal>text_in_unicode</literal> represented in ISO 8859-1</entry>
1015       </row>
1016
1017       <row>
1018        <entry><function>initcap</function>(<type>text</type>)</entry>
1019        <entry><type>text</type></entry>
1020        <entry>Converts first letter of each word (whitespace separated) to upper case.</entry>
1021        <entry><literal>initcap('hi thomas')</literal></entry>
1022        <entry><literal>Hi Thomas</literal></entry>
1023       </row>
1024
1025       <row>
1026        <entry><function>length</function>(<parameter>string</parameter>)</entry>
1027        <entry><type>integer</type></entry>
1028        <entry>
1029         length of string
1030         <indexterm>
1031          <primary>character strings</primary>
1032          <secondary>length</secondary>
1033         </indexterm>
1034         <indexterm>
1035          <primary>length</primary>
1036          <secondary>character strings</secondary>
1037          <see>character strings, length</see>
1038         </indexterm>
1039        </entry>
1040        <entry><literal>length('jose')</literal></entry>
1041        <entry><literal>4</literal></entry>
1042       </row>
1043
1044       <row>
1045        <entry>
1046         <function>lpad</function>(<parameter>string</parameter> <type>text</type>,
1047         <parameter>length</parameter> <type>integer</type>
1048         <optional>, <parameter>fill</parameter> <type>text</type></optional>)
1049        </entry>
1050        <entry>text</entry>
1051        <entry>
1052         Fills up the <parameter>string</parameter> to length
1053         <parameter>length</parameter> by prepending the characters
1054         <parameter>fill</parameter> (a space by default).  If the
1055         <parameter>string</parameter> is already longer than
1056         <parameter>length</parameter> then it is truncated (on the
1057         right).
1058        </entry>
1059        <entry><literal>lpad('hi', 5, 'xy')</literal></entry>
1060        <entry><literal>xyxhi</literal></entry>
1061       </row>
1062
1063       <row>
1064        <entry><function>ltrim</function>(<parameter>string</parameter> <type>text</type>, <parameter>text</parameter> <type>text</type>)</entry>
1065        <entry><type>text</type></entry>
1066        <entry>
1067         Removes the longest string containing only characters from
1068         <parameter>trim</parameter> from the start of the string.
1069        </entry>
1070        <entry><literal>ltrim('zzzytrim','xyz')</literal></entry>
1071        <entry><literal>trim</literal></entry>
1072       </row>
1073
1074       <row>
1075        <entry><function>pg_client_encoding</function>()</entry>
1076        <entry><type>name</type></entry>
1077        <entry>
1078         Returns current client encoding name.
1079        </entry>
1080        <entry><literal>pg_client_encoding()</literal></entry>
1081        <entry><literal>SQL_ASCII</literal></entry>
1082       </row>
1083
1084       <row>
1085        <entry><function>repeat</function>(<type>text</type>, <type>integer</type>)</entry>
1086        <entry><type>text</type></entry>
1087        <entry>Repeat text a number of times.</entry>
1088        <entry><literal>repeat('Pg', 4)</literal></entry>
1089        <entry><literal>PgPgPgPg</literal></entry>
1090       </row>
1091
1092       <row>
1093        <entry>
1094         <function>rpad</function>(<parameter>string</parameter> <type>text</type>,
1095         <parameter>length</parameter> <type>integer</type>
1096         <optional>, <parameter>fill</parameter> <type>text</type></optional>)
1097        </entry>
1098        <entry><type>text</type></entry>
1099        <entry>
1100         Fills up the <parameter>string</parameter> to length
1101         <parameter>length</parameter> by appending the characters
1102         <parameter>fill</parameter> (a space by default).  If the
1103         <parameter>string</parameter> is already longer than
1104         <parameter>length</parameter> then it is truncated.
1105        </entry>
1106        <entry><literal>rpad('hi', 5, 'xy')</literal></entry>
1107        <entry><literal>hixyx</literal></entry>
1108       </row>
1109
1110       <row>
1111        <entry><function>rtrim</function>(<parameter>string</parameter>
1112         text, <parameter>trim</parameter> text)</entry>
1113        <entry><type>text</type></entry>
1114        <entry>
1115         Removes the longest string containing only characters from
1116         <parameter>trim</parameter> from the end of the string.
1117        </entry>
1118        <entry><literal>rtrim('trimxxxx','x')</literal></entry>
1119        <entry><literal>trim</literal></entry>
1120       </row>
1121
1122       <row>
1123        <entry><function>strpos</function>(<parameter>string</parameter>, <parameter>substring</parameter>)</entry>
1124        <entry><type>text</type></entry>
1125        <entry>
1126         Locates specified substring. (same as
1127         <literal>position(<parameter>substring</parameter> in
1128          <parameter>string</parameter>)</literal>, but note the reversed
1129         argument order)
1130        </entry>
1131        <entry><literal>strpos('high','ig')</literal></entry>
1132        <entry><literal>2</literal></entry>
1133       </row>
1134
1135       <row>
1136        <entry><function>substr</function>(<parameter>string</parameter>, <parameter>from</parameter> <optional>, <parameter>count</parameter></optional>)</entry>
1137        <entry><type>text</type></entry>
1138        <entry>
1139         Extracts specified substring. (same as
1140         <literal>substring(<parameter>string</parameter> from <parameter>from</parameter> for <parameter>count</parameter>)</literal>)
1141        </entry>
1142        <entry><literal>substr('alphabet', 3, 2)</literal></entry>
1143        <entry><literal>ph</literal></entry>
1144       </row>
1145
1146       <row>
1147        <entry><function>to_ascii</function>(<type>text</type>
1148         <optional>ptional>, <parameter>encoding</parameter></optional>)</entry>
1149        <entry><type>text</type></entry>
1150        <entry>Converts text from multibyte encoding to <acronym>ASCII</acronym>.</entry>
1151        <entry><literal>to_ascii('Karel')</literal></entry>
1152        <entry><literal>Karel</literal></entry>
1153       </row>
1154
1155       <row>
1156        <entry>
1157         <function>translate</function>(<parameter>string</parameter>
1158         <type>text</type>,
1159         <parameter>from</parameter> <type>text</type>,
1160         <parameter>to</parameter> <type>text</type>)
1161        </entry>
1162        <entry><type>text</type></entry>
1163        <entry>
1164         Any character in <parameter>string</parameter> that matches a
1165         character in the <parameter>from</parameter> set is replaced by
1166         the corresponding character in the <parameter>to</parameter>
1167         set.
1168        </entry>
1169        <entry><literal>translate('12345', '14', 'ax')</literal></entry>
1170        <entry><literal>a23x5</literal></entry>
1171       </row>       
1172       
1173       <row>
1174        <entry>
1175         <function>encode</function>(<parameter>data</parameter> <type>bytea</type>,
1176         <parameter>type</parameter> <type>text</type>)
1177        </entry>
1178        <entry><type>text</type></entry>
1179        <entry>
1180         Encodes binary data to <acronym>ASCII</acronym>-only representation.  Supported
1181         types are: 'base64', 'hex', 'escape'.
1182        </entry>
1183        <entry><literal>encode('123\\000\\001', 'base64')</literal></entry>
1184        <entry><literal>MTIzAAE=</literal></entry>
1185       </row>       
1186
1187       <row>
1188        <entry>
1189         <function>decode</function>(<parameter>string</parameter> <type>text</type>,
1190         <parameter>type</parameter> <type>text</type>)
1191        </entry>
1192        <entry><type>bytea</type></entry>
1193        <entry>
1194         Decodes binary data from <parameter>string</parameter> previously 
1195         encoded with encode().  Parameter type is same as in encode().
1196        </entry>
1197        <entry><literal>decode('MTIzAAE=', 'base64')</literal></entry>
1198        <entry><literal>123\000\001</literal></entry>
1199       </row>       
1200
1201      </tbody>
1202     </tgroup>
1203    </table>
1204
1205    <para>
1206     The <function>to_ascii</function> function supports conversion from
1207     LATIN1, LATIN2, WIN1250 (CP1250) only.
1208    </para>
1209   </sect1>
1210
1211
1212   <sect1 id="functions-binarystring">
1213    <title>Binary String Functions and Operators</title>
1214
1215    <para>
1216     This section describes functions and operators for examining and
1217     manipulating binary string values.  Strings in this context include
1218     values of the type <type>BYTEA</type>.
1219    </para>
1220
1221    <para>
1222     <acronym>SQL</acronym> defines some string functions with a
1223     special syntax where 
1224     certain keywords rather than commas are used to separate the
1225     arguments.  Details are in
1226     <xref linkend="functions-binarystring-sql">.
1227     Some functions are also implemented using the regular syntax for
1228     function invocation.
1229     (See <xref linkend="functions-binarystring-other">.)
1230    </para>
1231
1232    <table id="functions-binarystring-sql">
1233     <title><acronym>SQL</acronym> Binary String Functions and Operators</title>
1234     <tgroup cols="5">
1235      <thead>
1236       <row>
1237        <entry>Function</entry>
1238        <entry>Return Type</entry>
1239        <entry>Description</entry>
1240        <entry>Example</entry>
1241        <entry>Result</entry>  
1242       </row>
1243      </thead>
1244
1245      <tbody>
1246       <row>
1247        <entry> <parameter>string</parameter> <literal>||</literal>
1248         <parameter>string</parameter> </entry>
1249        <entry> <type>bytea</type> </entry>
1250        <entry>
1251         string concatenation
1252         <indexterm>
1253          <primary>binary strings</primary>
1254          <secondary>concatenation</secondary>
1255         </indexterm>
1256        </entry>
1257        <entry><literal>'\\\\Postgre'::bytea || '\\047SQL\\000'::bytea</literal></entry>
1258        <entry><literal>\\Postgre'SQL\000</literal></entry>
1259       </row>
1260
1261       <row>
1262        <entry><function>octet_length</function>(<parameter>string</parameter>)</entry>
1263        <entry><type>integer</type></entry>
1264        <entry>number of bytes in binary string</entry>
1265        <entry><literal>octet_length('jo\\000se'::bytea)</literal></entry>
1266        <entry><literal>5</literal></entry>
1267       </row>
1268
1269       <row>
1270        <entry><function>position</function>(<parameter>substring</parameter> in <parameter>string</parameter>)</entry>
1271        <entry><type>integer</type></entry>
1272        <entry>location of specified substring</entry>
1273       <entry><literal>position('\\000om'::bytea in 'Th\\000omas'::bytea)</literal></entry>
1274        <entry><literal>3</literal></entry>
1275       </row>
1276
1277       <row>
1278        <entry><function>substring</function>(<parameter>string</parameter> <optional>from <type>integer</type></optional> <optional>for <type>integer</type></optional>)</entry>
1279        <entry><type>bytea</type></entry>
1280        <entry>
1281         extract substring
1282         <indexterm>
1283          <primary>substring</primary>
1284         </indexterm>
1285        </entry>
1286        <entry><literal>substring('Th\\000omas'::bytea from 2 for 3)</literal></entry>
1287        <entry><literal>h\000o</literal></entry>
1288       </row>
1289
1290       <row>
1291        <entry>
1292         <function>trim</function>(<optional>both</optional>
1293         <parameter>characters</parameter> from
1294         <parameter>string</parameter>)
1295        </entry>
1296        <entry><type>bytea</type></entry>
1297        <entry>
1298         Removes the longest string containing only the
1299         <parameter>characters</parameter> from the
1300         beginning/end/both ends of the <parameter>string</parameter>.
1301        </entry>
1302        <entry><literal>trim('\\000'::bytea from '\\000Tom\\000'::bytea)</literal></entry>
1303        <entry><literal>Tom</literal></entry>
1304       </row>
1305      </tbody>
1306     </tgroup>
1307    </table>
1308
1309    <para>
1310     Additional binary string manipulation functions are available and are
1311     listed below.  Some of them are used internally to implement the
1312     <acronym>SQL</acronym>-standard string functions listed above.
1313    </para>
1314
1315    <table id="functions-binarystring-other">
1316     <title>Other Binary String Functions</title>
1317     <tgroup cols="5">
1318      <thead>
1319       <row>
1320        <entry>Function</entry>
1321        <entry>Return Type</entry>
1322        <entry>Description</entry>
1323        <entry>Example</entry>
1324        <entry>Result</entry>
1325       </row>
1326      </thead>
1327
1328      <tbody>
1329       <row>
1330        <entry><function>btrim</function>(<parameter>string</parameter>
1331         <type>bytea</type> <parameter>trim</parameter> <type>bytea</type>)</entry>
1332        <entry><type>bytea</type></entry>
1333        <entry>
1334         Remove (trim) the longest string consisting only of characters
1335         in <parameter>trim</parameter> from the start and end of
1336         <parameter>string</parameter>.
1337       </entry>
1338       <entry><literal>btrim('\\000trim\\000'::bytea,'\\000'::bytea)</literal></entry>
1339       <entry><literal>trim</literal></entry>
1340      </row>
1341
1342      <row>
1343       <entry><function>length</function>(<parameter>string</parameter>)</entry>
1344       <entry><type>integer</type></entry>
1345       <entry>
1346        length of binary string
1347        <indexterm>
1348         <primary>binary strings</primary>
1349         <secondary>length</secondary>
1350        </indexterm>
1351        <indexterm>
1352         <primary>length</primary>
1353         <secondary>binary strings</secondary>
1354         <see>binary strings, length</see>
1355        </indexterm>
1356       </entry>
1357       <entry><literal>length('jo\\000se'::bytea)</literal></entry>
1358       <entry><literal>5</literal></entry>
1359      </row>
1360
1361      <row>
1362       <entry>
1363        <function>encode</function>(<parameter>string</parameter> <type>bytea</type>,
1364               <parameter>type</parameter> <type>text</type>)
1365       </entry>
1366       <entry><type>text</type></entry>
1367       <entry>
1368        Encodes binary string to <acronym>ASCII</acronym>-only representation.  Supported
1369        types are: 'base64', 'hex', 'escape'.
1370       </entry>
1371       <entry><literal>encode('123\\000456'::bytea, 'escape')</literal></entry>
1372       <entry><literal>123\000456</literal></entry>
1373      </row>       
1374
1375      <row>
1376       <entry>
1377        <function>decode</function>(<parameter>string</parameter> <type>text</type>,
1378               <parameter>type</parameter> <type>text</type>)
1379       </entry>
1380       <entry><type>bytea</type></entry>
1381       <entry>
1382        Decodes binary string from <parameter>string</parameter> previously 
1383        encoded with encode().  Parameter type is same as in encode().
1384       </entry>
1385       <entry><literal>decode('123\\000456', 'escape')</literal></entry>
1386       <entry><literal>123\000456</literal></entry>
1387      </row>       
1388
1389     </tbody>
1390    </tgroup>
1391   </table>
1392
1393  </sect1>
1394
1395
1396  <sect1 id="functions-matching">
1397   <title>Pattern Matching</title>
1398
1399    <para>
1400     There are two separate approaches to pattern matching provided by
1401     <productname>PostgreSQL</productname>:  the traditional
1402     <acronym>SQL</acronym> 
1403     <function>LIKE</function> operator and the more recent
1404     <acronym>SQL99</acronym> 
1405     <function>SIMILAR TO</function> operator implementing
1406     <acronym>POSIX</acronym>-style regular expressions.
1407     Additionally, a pattern matching function,
1408     <function>SUBSTRING</function>, is available, as defined in
1409     <acronym>SQL99</acronym>.
1410    </para>
1411
1412    <tip>
1413     <para>
1414      If you have pattern matching needs that go beyond this,
1415      consider writing a user-defined function in Perl or Tcl.
1416     </para>
1417    </tip>
1418
1419    <para>
1420     Both <function>LIKE</function> and <function>SIMILAR TO</function>
1421     are SQL-standard operators which are also available in alternate
1422     forms as <productname>PostgreSQL</productname> operators; look at
1423     <literal>~</literal> and <literal>~~</literal> for examples.
1424    </para>
1425
1426   <sect2 id="functions-like">
1427    <title><function>LIKE</function></title>
1428
1429    <indexterm>
1430     <primary>like</primary>
1431    </indexterm>
1432
1433     <synopsis>
1434 <replaceable>string</replaceable> LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
1435 <replaceable>string</replaceable> NOT LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
1436     </synopsis>
1437
1438     <para>
1439      Every <replaceable>pattern</replaceable> defines a set of strings.
1440      The <function>LIKE</function> expression returns true if the
1441      <replaceable>string</replaceable> is contained in the set of
1442      strings represented by <replaceable>pattern</replaceable>.  (As
1443      expected, the <function>NOT LIKE</function> expression returns
1444      false if <function>LIKE</function> returns true, and vice versa.
1445      An equivalent expression is
1446      <literal>NOT (<replaceable>string</replaceable> LIKE
1447       <replaceable>pattern</replaceable>)</literal>.)
1448     </para>
1449
1450     <para>
1451      If <replaceable>pattern</replaceable> does not contain percent
1452      signs or underscore, then the pattern only represents the string
1453      itself; in that case <function>LIKE</function> acts like the
1454      equals operator.  An underscore (<literal>_</literal>) in
1455      <replaceable>pattern</replaceable> stands for (matches) any single
1456      character; a percent sign (<literal>%</literal>) matches any string
1457      of zero or more characters.
1458     </para>
1459
1460     <informalexample>
1461      <para>
1462       Some examples:
1463       <programlisting>
1464 'abc' LIKE 'abc'    <lineannotation>true</lineannotation>
1465 'abc' LIKE 'a%'     <lineannotation>true</lineannotation>
1466 'abc' LIKE '_b_'    <lineannotation>true</lineannotation>
1467 'abc' LIKE 'c'      <lineannotation>false</lineannotation>
1468       </programlisting>
1469      </para>
1470     </informalexample>
1471
1472    <para>
1473     <function>LIKE</function> pattern matches always cover the entire
1474     string.  To match a pattern anywhere within a string, the
1475     pattern must therefore start and end with a percent sign.
1476    </para>
1477
1478    <para>
1479     To match a literal underscore or percent sign without matching
1480     other characters, the respective character in
1481     <replaceable>pattern</replaceable> must be 
1482     preceded by the escape character.  The default escape
1483     character is the backslash but a different one may be selected by
1484     using the <literal>ESCAPE</literal> clause.  To match the escape
1485     character itself, write two escape characters.
1486    </para>
1487
1488    <para>
1489     Note that the backslash already has a special meaning in string
1490     literals, so to write a pattern constant that contains a backslash
1491     you must write two backslashes in the query.  Thus, writing a pattern
1492     that actually matches a literal backslash means writing four backslashes
1493     in the query.  You can avoid this by selecting a different escape
1494     character with <literal>ESCAPE</literal>; then backslash is not special
1495     to <function>LIKE</function> anymore. (But it is still special to the string
1496     literal parser, so you still need two of them.)
1497    </para>
1498
1499    <para>
1500     It's also possible to select no escape character by writing
1501     <literal>ESCAPE ''</literal>.  This effectively disables the
1502      escape mechanism and
1503      turns off the special meaning of underscore and percent signs in
1504     the pattern.
1505    </para>
1506
1507    <para>
1508     The keyword <token>ILIKE</token> can be used instead of
1509     <token>LIKE</token> to make the match case insensitive according
1510     to the active locale.  This is not in the <acronym>SQL</acronym> standard but is a
1511     <productname>PostgreSQL</productname> extension.
1512    </para>
1513
1514    <para>
1515     The operator <literal>~~</literal> is equivalent to
1516     <function>LIKE</function>, and <literal>~~*</literal> corresponds to
1517     <function>ILIKE</function>.  There are also
1518     <literal>!~~</literal> and <literal>!~~*</literal> operators that
1519     represent <function>NOT LIKE</function> and <function>NOT
1520     ILIKE</function>.  All of these operators are
1521     <productname>PostgreSQL</productname>-specific.
1522    </para>
1523   </sect2>
1524
1525
1526   <sect2 id="functions-regexp">
1527    <title><function>SIMILAR TO</function> and <acronym>POSIX</acronym>
1528      Regular Expressions</title>
1529
1530    <indexterm zone="functions-regexp">
1531     <primary>regular expressions</primary>
1532     <seealso>pattern matching</seealso>
1533    </indexterm>
1534
1535    <table>
1536     <title>Regular Expression Match Operators</title>
1537
1538     <tgroup cols="3">
1539      <thead>
1540       <row>
1541        <entry>Operator</entry>
1542        <entry>Description</entry>
1543        <entry>Example</entry>
1544       </row>
1545      </thead>
1546
1547       <tbody>
1548        <row>
1549         <entry> <literal>~</literal> </entry>
1550         <entry>Matches regular expression, case sensitive</entry>
1551         <entry><literal>'thomas' ~ '.*thomas.*'</literal></entry>
1552        </row>
1553
1554        <row>
1555         <entry> <literal>~*</literal> </entry>
1556         <entry>Matches regular expression, case insensitive</entry>
1557         <entry><literal>'thomas' ~* '.*Thomas.*'</literal></entry>
1558        </row>
1559
1560        <row>
1561         <entry> <literal>!~</literal> </entry>
1562         <entry>Does not match regular expression, case sensitive</entry>
1563         <entry><literal>'thomas' !~ '.*Thomas.*'</literal></entry>
1564        </row>
1565
1566        <row>
1567         <entry> <literal>!~*</literal> </entry>
1568         <entry>Does not match regular expression, case insensitive</entry>
1569         <entry><literal>'thomas' !~* '.*vadim.*'</literal></entry>
1570        </row>
1571
1572        <row>
1573         <entry> <literal>SIMILAR TO</literal> </entry>
1574         <entry>Matches regular expression, case sensitive</entry>
1575         <entry><literal>'thomas' SIMILAR TO '.*thomas.*'</literal></entry>
1576        </row>
1577       </tbody>
1578      </tgroup>
1579     </table>
1580
1581     <para>
1582      <acronym>POSIX</acronym> regular expressions provide a more
1583      powerful means for 
1584      pattern matching than the <function>LIKE</function> function.
1585      Many Unix tools such as <command>egrep</command>,
1586      <command>sed</command>, or <command>awk</command> use a pattern
1587      matching language that is similar to the one described here.
1588     </para>
1589
1590     <para>
1591      A regular expression is a character sequence that is an
1592      abbreviated definition of a set of strings (a <firstterm>regular
1593       set</firstterm>).  A string is said to match a regular expression
1594      if it is a member of the regular set described by the regular
1595      expression.  As with <function>LIKE</function>, pattern characters
1596      match string characters exactly unless they are special characters
1597      in the regular expression language --- but regular expressions use
1598      different special characters than <function>LIKE</function> does.
1599      Unlike <function>LIKE</function> patterns, a
1600      regular expression is allowed to match anywhere within a string, unless
1601      the regular expression is explicitly anchored to the beginning or
1602      end of the string.
1603     </para>
1604
1605     <informalexample>
1606      <para>
1607       Some examples:
1608       <programlisting>
1609 'abc' SIMILAR TO 'abc'    <lineannotation>true</lineannotation>
1610 'abc' SIMILAR TO '^a'     <lineannotation>true</lineannotation>
1611 'abc' SIMILAR TO '(b|d)'  <lineannotation>true</lineannotation>
1612 'abc' SIMILAR TO '^(b|c)' <lineannotation>false</lineannotation>
1613       </programlisting>
1614      </para>
1615     </informalexample>
1616
1617 <!-- derived from the re_format.7 man page -->
1618    <para>
1619     Regular expressions (<quote>RE</quote>s), as defined in
1620      <acronym>POSIX</acronym> 
1621     1003.2, come in two forms: modern REs (roughly those of
1622     <command>egrep</command>; 1003.2 calls these
1623     <quote>extended</quote> REs) and obsolete REs (roughly those of
1624     <command>ed</command>; 1003.2 <quote>basic</quote> REs).
1625     <productname>PostgreSQL</productname> implements the modern form.
1626    </para>
1627
1628    <para>
1629     A (modern) RE is one or more non-empty
1630     <firstterm>branches</firstterm>, separated by
1631     <literal>|</literal>.  It matches anything that matches one of the
1632     branches.
1633    </para>
1634
1635    <para>
1636     A branch is one or more <firstterm>pieces</firstterm>,
1637     concatenated.  It matches a match for the first, followed by a
1638     match for the second, etc.
1639    </para>
1640
1641    <para>
1642     A piece is an <firstterm>atom</firstterm> possibly followed by a
1643     single <literal>*</literal>, <literal>+</literal>,
1644     <literal>?</literal>, or <firstterm>bound</firstterm>.  An atom
1645     followed by <literal>*</literal> matches a sequence of 0 or more
1646     matches of the atom.  An atom followed by <literal>+</literal>
1647     matches a sequence of 1 or more matches of the atom.  An atom
1648     followed by <literal>?</literal> matches a sequence of 0 or 1
1649     matches of the atom.
1650    </para>
1651
1652    <para>
1653     A <firstterm>bound</firstterm> is <literal>{</literal> followed by
1654     an unsigned decimal integer, possibly followed by
1655     <literal>,</literal> possibly followed by another unsigned decimal
1656     integer, always followed by <literal>}</literal>.  The integers
1657     must lie between 0 and <symbol>RE_DUP_MAX</symbol> (255)
1658     inclusive, and if there are two of them, the first may not exceed
1659     the second.  An atom followed by a bound containing one integer
1660     <replaceable>i</replaceable> and no comma matches a sequence of
1661     exactly <replaceable>i</replaceable> matches of the atom.  An atom
1662     followed by a bound containing one integer
1663     <replaceable>i</replaceable> and a comma matches a sequence of
1664     <replaceable>i</replaceable> or more matches of the atom.  An atom
1665     followed by a bound containing two integers
1666     <replaceable>i</replaceable> and <replaceable>j</replaceable>
1667     matches a sequence of <replaceable>i</replaceable> through
1668     <replaceable>j</replaceable> (inclusive) matches of the atom.
1669    </para>
1670
1671    <note>
1672     <para>
1673      A repetition operator (<literal>?</literal>,
1674      <literal>*</literal>, <literal>+</literal>, or bounds) cannot
1675      follow another repetition operator.  A repetition operator cannot
1676      begin an expression or subexpression or follow
1677      <literal>^</literal> or <literal>|</literal>.
1678     </para>
1679    </note>
1680
1681    <para>
1682     An <firstterm>atom</firstterm> is a regular expression enclosed in
1683     <literal>()</literal> (matching a match for the regular
1684     expression), an empty set of <literal>()</literal> (matching the
1685     null string), a <firstterm>bracket expression</firstterm> (see
1686     below), <literal>.</literal> (matching any single character),
1687     <literal>^</literal> (matching the null string at the beginning of the
1688     input string), <literal>$</literal> (matching the null string at the end
1689     of the input string), a <literal>\</literal> followed by one of the
1690     characters <literal>^.[$()|*+?{\</literal> (matching that
1691     character taken as an ordinary character), a <literal>\</literal>
1692     followed by any other character (matching that character taken as
1693     an ordinary character, as if the <literal>\</literal> had not been
1694     present), or a single character with no other significance
1695     (matching that character).  A <literal>{</literal> followed by a
1696     character other than a digit is an ordinary character, not the
1697     beginning of a bound.  It is illegal to end an RE with
1698     <literal>\</literal>.
1699    </para>
1700
1701    <para>
1702     Note that the backslash (<literal>\</literal>) already has a special
1703     meaning in string
1704     literals, so to write a pattern constant that contains a backslash
1705     you must write two backslashes in the query.
1706    </para>
1707
1708    <para>
1709     A <firstterm>bracket expression</firstterm> is a list of
1710     characters enclosed in <literal>[]</literal>.  It normally matches
1711     any single character from the list (but see below).  If the list
1712     begins with <literal>^</literal>, it matches any single character
1713     (but see below) not from the rest of the list.  If two characters
1714     in the list are separated by <literal>-</literal>, this is
1715     shorthand for the full range of characters between those two
1716     (inclusive) in the collating sequence,
1717     e.g. <literal>[0-9]</literal> in <acronym>ASCII</acronym> matches
1718     any decimal digit.  It is illegal for two ranges to share an
1719     endpoint, e.g.  <literal>a-c-e</literal>.  Ranges are very
1720     collating-sequence-dependent, and portable programs should avoid
1721     relying on them.
1722    </para>
1723
1724    <para>
1725     To include a literal <literal>]</literal> in the list, make it the
1726     first character (following a possible <literal>^</literal>).  To
1727     include a literal <literal>-</literal>, make it the first or last
1728     character, or the second endpoint of a range.  To use a literal
1729     <literal>-</literal> as the first endpoint of a range, enclose it
1730     in <literal>[.</literal> and <literal>.]</literal> to make it a
1731     collating element (see below).  With the exception of these and
1732     some combinations using <literal>[</literal> (see next
1733     paragraphs), all other special characters, including
1734     <literal>\</literal>, lose their special significance within a
1735     bracket expression.
1736    </para>
1737
1738    <para>
1739     Within a bracket expression, a collating element (a character, a
1740     multiple-character sequence that collates as if it were a single
1741     character, or a collating-sequence name for either) enclosed in
1742     <literal>[.</literal> and <literal>.]</literal> stands for the
1743     sequence of characters of that collating element.  The sequence is
1744     a single element of the bracket expression's list.  A bracket
1745     expression containing a multiple-character collating element can thus
1746     match more than one character, e.g. if the collating sequence
1747     includes a <literal>ch</literal> collating element, then the RE
1748     <literal>[[.ch.]]*c</literal> matches the first five characters of
1749     <literal>chchcc</literal>.
1750    </para>
1751
1752    <para>
1753     Within a bracket expression, a collating element enclosed in
1754     <literal>[=</literal> and <literal>=]</literal> is an equivalence
1755     class, standing for the sequences of characters of all collating
1756     elements equivalent to that one, including itself.  (If there are
1757     no other equivalent collating elements, the treatment is as if the
1758     enclosing delimiters were <literal>[.</literal> and
1759     <literal>.]</literal>.)  For example, if <literal>o</literal> and
1760     <literal>^</literal> are the members of an equivalence class, then
1761     <literal>[[=o=]]</literal>, <literal>[[=^=]]</literal>, and
1762     <literal>[o^]</literal> are all synonymous.  An equivalence class
1763     may not be an endpoint of a range.
1764    </para>
1765
1766    <para>
1767     Within a bracket expression, the name of a character class
1768     enclosed in <literal>[:</literal> and <literal>:]</literal> stands
1769     for the list of all characters belonging to that class.  Standard
1770     character class names are: <literal>alnum</literal>,
1771     <literal>alpha</literal>, <literal>blank</literal>,
1772     <literal>cntrl</literal>, <literal>digit</literal>,
1773     <literal>graph</literal>, <literal>lower</literal>,
1774     <literal>print</literal>, <literal>punct</literal>,
1775     <literal>space</literal>, <literal>upper</literal>,
1776     <literal>xdigit</literal>.  These stand for the character classes
1777     defined in
1778     <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>.
1779     A locale may provide others.  A character class may not be used as
1780     an endpoint of a range.
1781    </para>
1782
1783    <para>
1784     There are two special cases of bracket expressions:  the bracket
1785     expressions <literal>[[:<:]]</literal> and
1786     <literal>[[:>:]]</literal> match the null string at the beginning
1787     and end of a word respectively.  A word is defined as a sequence
1788     of word characters which is neither preceded nor followed by word
1789     characters.  A word character is an alnum character (as defined by
1790     <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>)
1791     or an underscore.  This is an extension, compatible with but not
1792     specified by <acronym>POSIX</acronym> 1003.2, and should be used with caution in
1793     software intended to be portable to other systems.
1794    </para>
1795
1796    <para>
1797     In the event that an RE could match more than one substring of a
1798     given string, the RE matches the one starting earliest in the
1799     string.  If the RE could match more than one substring starting at
1800     that point, it matches the longest.  Subexpressions also match the
1801     longest possible substrings, subject to the constraint that the
1802     whole match be as long as possible, with subexpressions starting
1803     earlier in the RE taking priority over ones starting later.  Note
1804     that higher-level subexpressions thus take priority over their
1805     lower-level component subexpressions.
1806    </para>
1807
1808    <para>
1809     Match lengths are measured in characters, not collating
1810     elements.  A null string is considered longer than no match at
1811     all.  For example, <literal>bb*</literal> matches the three middle
1812     characters of <literal>abbbc</literal>,
1813     <literal>(wee|week)(knights|nights)</literal> matches all ten
1814     characters of <literal>weeknights</literal>, when
1815     <literal>(.*).*</literal> is matched against
1816     <literal>abc</literal> the parenthesized subexpression matches all
1817     three characters, and when <literal>(a*)*</literal> is matched
1818     against <literal>bc</literal> both the whole RE and the
1819     parenthesized subexpression match the null string.
1820    </para>
1821
1822    <para>
1823     If case-independent matching is specified, the effect is much as
1824     if all case distinctions had vanished from the alphabet.  When an
1825     alphabetic that exists in multiple cases appears as an ordinary
1826     character outside a bracket expression, it is effectively
1827     transformed into a bracket expression containing both cases,
1828     e.g. <literal>x</literal> becomes <literal>[xX]</literal>.  When
1829     it appears inside a bracket expression, all case counterparts of
1830     it are added to the bracket expression, so that (e.g.)
1831     <literal>[x]</literal> becomes <literal>[xX]</literal> and
1832     <literal>[^x]</literal> becomes <literal>[^xX]</literal>.
1833    </para>
1834
1835    <para>
1836     There is no particular limit on the length of REs, except insofar
1837     as memory is limited.  Memory usage is approximately linear in RE
1838     size, and largely insensitive to RE complexity, except for bounded
1839     repetitions.  Bounded repetitions are implemented by macro
1840     expansion, which is costly in time and space if counts are large
1841     or bounded repetitions are nested.  An RE like, say,
1842     <literal>((((a{1,100}){1,100}){1,100}){1,100}){1,100}</literal>
1843     will (eventually) run almost any existing machine out of swap
1844     space.
1845     <footnote>
1846      <para>
1847       This was written in 1994, mind you.  The
1848       numbers have probably changed, but the problem
1849       persists.
1850      </para>
1851     </footnote>
1852    </para>
1853 <!-- end re_format.7 man page -->
1854   </sect2>
1855
1856  </sect1>
1857
1858
1859   <sect1 id="functions-formatting">
1860    <title>Data Type Formatting Functions</title>
1861
1862    <indexterm zone="functions-formatting">
1863     <primary>formatting</primary>
1864    </indexterm>
1865
1866    <note>
1867     <title>Author</title>
1868     <para>
1869      Written by Karel Zak (<email>zakkr@zf.jcu.cz</email>) on 2000-01-24
1870     </para>
1871    </note>
1872
1873    <para>
1874     The <productname>PostgreSQL</productname> formatting functions
1875     provide a powerful set of tools for converting various data types
1876     (date/time, integer, floating point, numeric) to formatted strings
1877     and for converting from formatted strings to specific data types.
1878     These functions all follow a common calling convention: the first
1879     argument is the value to be formatted and the second argument is a
1880     template that defines the output or input format.
1881    </para>
1882
1883     <table tocentry="1">
1884      <title>Formatting Functions</title>
1885      <tgroup cols="4">
1886       <thead>
1887        <row>
1888         <entry>Function</entry>
1889         <entry>Returns</entry>
1890         <entry>Description</entry>
1891         <entry>Example</entry>
1892        </row>
1893       </thead>
1894       <tbody>
1895        <row>
1896         <entry><function>to_char</function>(<type>timestamp</type>, <type>text</type>)</entry>
1897         <entry><type>text</type></entry>
1898         <entry>convert time stamp to string</entry>
1899         <entry><literal>to_char(timestamp 'now','HH12:MI:SS')</literal></entry>
1900        </row>
1901        <row>
1902         <entry><function>to_char</function>(<type>interval</type>, <type>text</type>)</entry>
1903         <entry><type>text</type></entry>
1904         <entry>convert interval to string</entry>
1905         <entry><literal>to_char(interval '15h 2m 12s','HH24:MI:SS')</literal></entry>
1906        </row>
1907        <row>
1908         <entry><function>to_char</function>(<type>int</type>, <type>text</type>)</entry>
1909         <entry><type>text</type></entry>
1910         <entry>convert int4/int8 to string</entry>
1911         <entry><literal>to_char(125, '999')</literal></entry>
1912        </row>
1913        <row>
1914         <entry><function>to_char</function>(<type>double precision</type>,
1915         <type>text</type>)</entry>
1916         <entry><type>text</type></entry>
1917         <entry>convert real/double precision to string</entry>
1918         <entry><literal>to_char(125.8, '999D9')</literal></entry>
1919        </row>
1920        <row>
1921         <entry><function>to_char</function>(<type>numeric</type>, <type>text</type>)</entry>
1922         <entry><type>text</type></entry>
1923         <entry>convert numeric to string</entry>
1924         <entry><literal>to_char(numeric '-125.8', '999D99S')</literal></entry>
1925        </row>
1926        <row>
1927         <entry><function>to_date</function>(<type>text</type>, <type>text</type>)</entry>
1928         <entry><type>date</type></entry>
1929         <entry>convert string to date</entry>
1930         <entry><literal>to_date('05 Dec 2000', 'DD Mon YYYY')</literal></entry>
1931        </row>
1932        <row>
1933         <entry><function>to_timestamp</function>(<type>text</type>, <type>text</type>)</entry>
1934         <entry><type>timestamp</type></entry>
1935         <entry>convert string to time stamp</entry>
1936         <entry><literal>to_timestamp('05 Dec 2000', 'DD Mon YYYY')</literal></entry>
1937        </row>
1938        <row>
1939         <entry><function>to_number</function>(<type>text</type>, <type>text</type>)</entry>
1940         <entry><type>numeric</type></entry>
1941         <entry>convert string to numeric</entry>
1942         <entry><literal>to_number('12,454.8-', '99G999D9S')</literal></entry>
1943        </row>
1944       </tbody>
1945      </tgroup>
1946     </table>
1947
1948    <para>
1949     In an output template string, there are certain patterns that are
1950     recognized and replaced with appropriately-formatted data from the value
1951     to be formatted.  Any text that is not a template pattern is simply
1952     copied verbatim.  Similarly, in an input template string, template patterns
1953     identify the parts of the input data string to be looked at and the
1954     values to be found there.
1955    </para>
1956
1957     <table tocentry="1">
1958      <title>Template patterns for date/time conversions</title>
1959      <tgroup cols="2">
1960       <thead>
1961        <row>
1962         <entry>Pattern</entry>
1963         <entry>Description</entry>
1964        </row>
1965       </thead>
1966       <tbody>
1967        <row>
1968         <entry><literal>HH</literal></entry>
1969         <entry>hour of day (01-12)</entry>
1970        </row>
1971        <row>
1972         <entry><literal>HH12</literal></entry>
1973         <entry>hour of day (01-12)</entry>
1974        </row>       
1975        <row>
1976         <entry><literal>HH24</literal></entry>
1977         <entry>hour of day (00-23)</entry>
1978        </row>       
1979        <row>
1980         <entry><literal>MI</literal></entry>
1981         <entry>minute (00-59)</entry>
1982        </row>   
1983        <row>
1984         <entry><literal>SS</literal></entry>
1985         <entry>second (00-59)</entry>
1986        </row>
1987        <row>
1988         <entry><literal>MS</literal></entry>
1989         <entry>millisecond (000-999)</entry>
1990        </row>
1991        <row>
1992         <entry><literal>US</literal></entry>
1993         <entry>microsecond (000000-999999)</entry>
1994        </row>
1995        <row>
1996         <entry><literal>SSSS</literal></entry>
1997         <entry>seconds past midnight (0-86399)</entry>
1998        </row>
1999        <row>
2000         <entry><literal>AM</literal> or <literal>A.M.</literal> or
2001 <literal>li</literal>literal> or <literal>P.M.</literal></entry>
2002         <entry>meridian indicator (upper case)</entry>
2003        </row>
2004        <row>
2005         <entry><literal>am</literal> or <literal>a.m.</literal> or
2006 <literal>li</literal>literal> or <literal>p.m.</literal></entry>
2007         <entry>meridian indicator (lower case)</entry>
2008        </row>
2009        <row>
2010         <entry><literal>Y,YYY</literal></entry>
2011         <entry>year (4 and more digits) with comma</entry>
2012        </row>
2013        <row>
2014         <entry><literal>YYYY</literal></entry>
2015         <entry>year (4 and more digits)</entry>
2016        </row>
2017        <row>
2018         <entry><literal>YYY</literal></entry>
2019         <entry>last 3 digits of year</entry>
2020        </row>
2021        <row>
2022         <entry><literal>YY</literal></entry>
2023         <entry>last 2 digits of year</entry>
2024        </row>
2025        <row>
2026         <entry><literal>Y</literal></entry>
2027         <entry>last digit of year</entry>
2028        </row>
2029        <row>
2030         <entry><literal>BC</literal> or <literal>B.C.</literal> or
2031 <literal>li</literal>literal> or <literal>A.D.</literal></entry>
2032         <entry>era indicator (upper case)</entry>
2033        </row>
2034        <row>
2035         <entry><literal>bc</literal> or <literal>b.c.</literal> or
2036 <literal>li</literal>literal> or <literal>a.d.</literal></entry>
2037         <entry>era indicator (lower case)</entry>
2038        </row>
2039        <row>
2040         <entry><literal>MONTH</literal></entry>
2041         <entry>full upper case month name (blank-padded to 9 chars)</entry>
2042        </row>
2043        <row>
2044         <entry><literal>Month</literal></entry>
2045         <entry>full mixed case month name (blank-padded to 9 chars)</entry>
2046        </row>
2047        <row>
2048         <entry><literal>month</literal></entry>
2049         <entry>full lower case month name (blank-padded to 9 chars)</entry>
2050        </row>
2051        <row>
2052         <entry><literal>MON</literal></entry>
2053         <entry>abbreviated upper case month name (3 chars)</entry>
2054        </row>
2055        <row>
2056         <entry><literal>Mon</literal></entry>
2057         <entry>abbreviated mixed case month name (3 chars)</entry>
2058        </row>
2059        <row>
2060         <entry><literal>mon</literal></entry>
2061         <entry>abbreviated lower case month name (3 chars)</entry>
2062        </row>
2063        <row>
2064         <entry><literal>MM</literal></entry>
2065         <entry>month number (01-12)</entry>
2066        </row>
2067        <row>
2068         <entry><literal>DAY</literal></entry>
2069         <entry>full upper case day name (blank-padded to 9 chars)</entry>
2070        </row>
2071        <row>
2072         <entry><literal>Day</literal></entry>
2073         <entry>full mixed case day name (blank-padded to 9 chars)</entry>
2074        </row>
2075        <row>
2076         <entry><literal>day</literal></entry>
2077         <entry>full lower case day name (blank-padded to 9 chars)</entry>
2078        </row>
2079        <row>
2080         <entry><literal>DY</literal></entry>
2081         <entry>abbreviated upper case day name (3 chars)</entry>
2082        </row>
2083        <row>
2084         <entry><literal>Dy</literal></entry>
2085         <entry>abbreviated mixed case day name (3 chars)</entry>
2086        </row>
2087        <row>
2088         <entry><literal>dy</literal></entry>
2089         <entry>abbreviated lower case day name (3 chars)</entry>
2090        </row>
2091        <row>
2092         <entry><literal>DDD</literal></entry>
2093         <entry>day of year (001-366)</entry>
2094        </row>
2095        <row>
2096         <entry><literal>DD</literal></entry>
2097         <entry>day of month (01-31)</entry>
2098        </row>
2099        <row>
2100         <entry><literal>D</literal></entry>
2101         <entry>day of week (1-7; SUN=1)</entry>
2102        </row>
2103        <row>
2104         <entry><literal>W</literal></entry>
2105         <entry>week of month (1-5) where first week start on the first day of the month</entry>
2106        </row> 
2107        <row>
2108         <entry><literal>WW</literal></entry>
2109         <entry>week number of year (1-53) where first week start on the first day of the year</entry>
2110        </row>
2111        <row>
2112         <entry><literal>IW</literal></entry>
2113         <entry>ISO week number of year (The first Thursday of the new year is in week 1.)</entry>
2114        </row>
2115        <row>
2116         <entry><literal>CC</literal></entry>
2117         <entry>century (2 digits)</entry>
2118        </row>
2119        <row>
2120         <entry><literal>J</literal></entry>
2121         <entry>Julian Day (days since January 1, 4712 BC)</entry>
2122        </row>
2123        <row>
2124         <entry><literal>Q</literal></entry>
2125         <entry>quarter</entry>
2126        </row>
2127        <row>
2128         <entry><literal>RM</literal></entry>
2129         <entry>month in Roman Numerals (I-XII; I=January) - upper case</entry>
2130        </row>
2131        <row>
2132         <entry><literal>rm</literal></entry>
2133         <entry>month in Roman Numerals (I-XII; I=January) - lower case</entry>
2134        </row>
2135        <row>
2136         <entry><literal>TZ</literal></entry>
2137         <entry>timezone name - upper case</entry>
2138        </row>
2139        <row>
2140         <entry><literal>tz</literal></entry>
2141         <entry>timezone name - lower case</entry>
2142        </row>
2143       </tbody>
2144      </tgroup>
2145     </table>
2146
2147    <para>
2148     Certain modifiers may be applied to any template pattern to alter its
2149     behavior.  For example, <quote><literal>FMMonth</literal></quote>
2150     is the <quote><literal>Month</literal></quote> pattern with the
2151     <quote><literal>FM</literal></quote> prefix.
2152    </para>
2153
2154     <table tocentry="1">
2155      <title>Template pattern modifiers for date/time conversions</title>
2156      <tgroup cols="3">
2157       <thead>
2158        <row>
2159         <entry>Modifier</entry>
2160         <entry>Description</entry>
2161         <entry>Example</entry>
2162        </row>
2163       </thead>
2164       <tbody>
2165        <row>
2166         <entry><literal>FM</literal> prefix</entry>
2167         <entry>fill mode (suppress padding blanks and zeroes)</entry>
2168         <entry><literal>FMMonth</literal></entry>
2169        </row>
2170        <row>
2171         <entry><literal>TH</literal> suffix</entry>
2172         <entry>add upper-case ordinal number suffix</entry>
2173         <entry><literal>DDTH</literal></entry>
2174        </row>   
2175        <row>
2176         <entry><literal>th</literal> suffix</entry>
2177         <entry>add lower-case ordinal number suffix</entry>
2178         <entry><literal>DDth</literal></entry>
2179        </row>
2180        <row>
2181         <entry><literal>FX</literal> prefix</entry>
2182         <entry>Fixed format global option (see below)</entry>
2183         <entry><literal>FX Month DD Day</literal></entry>
2184        </row>   
2185        <row>
2186         <entry><literal>SP</literal> suffix</entry>
2187         <entry>spell mode (not yet implemented)</entry>
2188         <entry><literal>DDSP</literal></entry>
2189        </row>       
2190       </tbody>
2191      </tgroup>
2192     </table>
2193
2194    <para>
2195     Usage notes:
2196
2197     <itemizedlist>
2198      <listitem>
2199       <para>
2200        <literal>FM</literal> suppresses leading zeroes or trailing blanks
2201        that would otherwise be added to make the output of a pattern be
2202        fixed-width.
2203       </para>
2204      </listitem>
2205
2206      <listitem>
2207       <para>
2208        <function>to_timestamp</function> and <function>to_date</function>
2209        skip multiple blank spaces in the input string if the <literal>FX</literal> option 
2210        is not used. <literal>FX</literal> must be specified as the first item
2211        in the template; for example 
2212        <literal>to_timestamp('2000    JUN','YYYY MON')</literal> is right, but
2213        <literal>to_timestamp('2000    JUN','FXYYYY MON')</literal> returns an error,
2214        because <function>to_timestamp</function> expects one blank space only.
2215       </para>
2216      </listitem>
2217
2218      <listitem>
2219       <para>
2220        If a backslash (<quote><literal>\</literal></quote>) is desired
2221        in a string constant, a double backslash
2222        (<quote><literal>\\</literal></quote>) must be entered; for
2223        example <literal>'\\HH\\MI\\SS'</literal>.  This is true for
2224        any string constant in <productname>PostgreSQL</productname>.
2225       </para>
2226      </listitem>
2227
2228      <listitem>
2229       <para>
2230        Ordinary text is allowed in <function>to_char</function>
2231        templates and will be output literally.  You can put a substring
2232        in double quotes to force it to be interpreted as literal text
2233        even if it contains pattern keywords.  For example, in
2234        <literal>'"Hello Year: "YYYY'</literal>, the <literal>YYYY</literal>
2235        will be replaced by year data, but the single <literal>Y</literal>
2236        will not be.
2237       </para>
2238      </listitem>
2239
2240      <listitem>
2241       <para>
2242        If you want to have a double quote in the output you must
2243        precede it with a backslash, for example <literal>'\\"YYYY
2244        Month\\"'</literal>. <!-- "" font-lock sanity :-) -->
2245       </para>
2246      </listitem>
2247
2248      <listitem>
2249       <para>
2250        <literal>YYYY</literal> conversion from string to <type>timestamp</type> or
2251        <type>date</type> is restricted if you use a year with more than 4 digits. You must
2252        use some non-digit character or template after <literal>YYYY</literal>,
2253        otherwise the year is always interpreted as 4 digits. For example
2254        (with year 20000):
2255        <literal>to_date('200001131', 'YYYYMMDD')</literal> will be 
2256        interpreted as a 4-digit year; better is to use a non-digit 
2257        separator after the year, like
2258        <literal>to_date('20000-1131', 'YYYY-MMDD')</literal> or
2259        <literal>to_date('20000Nov31', 'YYYYMonDD')</literal>.
2260       </para>
2261      </listitem>
2262
2263      <listitem>
2264       <para>
2265        Millisecond <literal>MS</literal> and microsecond <literal>US</literal>
2266        values in a conversion from string to time stamp are used as part of the
2267        seconds after the decimal point. For example 
2268        <literal>to_timestamp('12:3', 'SS:MS')</literal> is not 3 milliseconds,
2269        but 300, because the conversion counts it as 12 + 0.3.
2270        This means for the format <literal>SS:MS</literal>, the input values
2271        <literal>12:3</literal>, <literal>12:30</literal>, and <literal>12:300</literal> specify the
2272        same number of milliseconds. To get three milliseconds, one must use
2273        <literal>12:003</literal>, which the conversion counts as
2274        12 + 0.003 = 12.003 seconds.
2275       </para>
2276
2277       <para>
2278        Here is a more 
2279        complex example: 
2280        <literal>to_timestamp('15:12:02.020.001230','HH:MI:SS.MS.US')</literal>
2281        is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds +
2282        1230 microseconds = 2.021230 seconds. 
2283       </para>
2284      </listitem>
2285     </itemizedlist>
2286    </para>
2287
2288     <table tocentry="1">
2289      <title>Template patterns for numeric conversions</title>
2290      <tgroup cols="2">
2291       <thead>
2292        <row>
2293         <entry>Pattern</entry>
2294         <entry>Description</entry>
2295        </row>
2296       </thead>
2297       <tbody>
2298        <row>
2299         <entry><literal>9</literal></entry>
2300         <entry>value with the specified number of digits</entry>
2301        </row>
2302        <row>
2303         <entry><literal>0</literal></entry>
2304         <entry>value with leading zeros</entry>
2305        </row>
2306        <row>
2307         <entry><literal>.</literal> (period)</entry>
2308         <entry>decimal point</entry>
2309        </row>       
2310        <row>
2311         <entry><literal>,</literal> (comma)</entry>
2312         <entry>group (thousand) separator</entry>
2313        </row>
2314        <row>
2315         <entry><literal>PR</literal></entry>
2316         <entry>negative value in angle brackets</entry>
2317        </row>
2318        <row>
2319         <entry><literal>S</literal></entry>
2320         <entry>negative value with minus sign (uses locale)</entry>
2321        </row>
2322        <row>
2323         <entry><literal>L</literal></entry>
2324         <entry>currency symbol (uses locale)</entry>
2325        </row>
2326        <row>
2327         <entry><literal>D</literal></entry>
2328         <entry>decimal point (uses locale)</entry>
2329        </row>
2330        <row>
2331         <entry><literal>G</literal></entry>
2332         <entry>group separator (uses locale)</entry>
2333        </row>
2334        <row>
2335         <entry><literal>MI</literal></entry>
2336         <entry>minus sign in specified position (if number < 0)</entry>
2337        </row>
2338        <row>
2339         <entry><literal>PL</literal></entry>
2340         <entry>plus sign in specified position (if number > 0)</entry>
2341        </row>
2342        <row>
2343         <entry><literal>SG</literal></entry>
2344         <entry>plus/minus sign in specified position</entry>
2345        </row>
2346        <row>
2347         <entry><literal>RN</literal></entry>
2348         <entry>roman numeral (input between 1 and 3999)</entry>
2349        </row>
2350        <row>
2351         <entry><literal>TH</literal> or <literal>th</literal></entry>
2352         <entry>convert to ordinal number</entry>
2353        </row>
2354        <row>
2355         <entry><literal>V</literal></entry>
2356         <entry>shift <replaceable>n</replaceable> digits (see
2357          notes)</entry>
2358        </row>
2359        <row>
2360         <entry><literal>EEEE</literal></entry>
2361         <entry>scientific notation (not implemented yet)</entry>
2362        </row>
2363       </tbody>
2364      </tgroup>
2365     </table>
2366
2367    <para>
2368     Usage notes:
2369
2370     <itemizedlist>
2371      <listitem>
2372       <para>
2373        A sign formatted using <literal>SG</literal>, <literal>PL</literal>, or
2374        <literal>MI</literal> is not an anchor in
2375        the number; for example,
2376        <literal>to_char(-12, 'S9999')</literal> produces <literal>'  -12'</literal>,
2377        but <literal>to_char(-12, 'MI9999')</literal> produces <literal>'-  12'</literal>.
2378        The Oracle implementation does not allow the use of
2379        <literal>MI</literal> ahead of <literal>9</literal>, but rather
2380        requires that <literal>9</literal> precede
2381        <literal>MI</literal>.
2382       </para>
2383      </listitem>
2384
2385      <listitem>
2386       <para>
2387        <literal>9</literal> specifies a value with the same number of 
2388        digits as there are <literal>9</literal>s. If a digit is
2389        not available use blank space.
2390       </para>
2391      </listitem>
2392
2393      <listitem>
2394       <para>
2395        <literal>TH</literal> does not convert values less than zero
2396        and does not convert decimal numbers.
2397       </para>
2398      </listitem>
2399
2400      <listitem>
2401       <para>
2402        <literal>PL</literal>, <literal>SG</literal>, and
2403        <literal>TH</literal> are <productname>PostgreSQL</productname>
2404        extensions. 
2405       </para>
2406      </listitem>
2407
2408      <listitem>
2409       <para>
2410        <literal>V</literal> effectively
2411        multiplies the input values by
2412        <literal>10^<replaceable>n</replaceable></literal>, where
2413        <replaceable>n</replaceable> is the number of digits following
2414        <literal>V</literal>. 
2415        <function>to_char</function> does not support the use of
2416        <literal>V</literal> combined with a decimal point.
2417        (E.g., <literal>99.9V99</literal> is not allowed.)
2418       </para>
2419      </listitem>
2420     </itemizedlist>
2421    </para>   
2422
2423     <table tocentry="1">
2424      <title><function>to_char</function> Examples</title>
2425      <tgroup cols="2">
2426       <thead>
2427        <row>
2428         <entry>Input</entry>
2429         <entry>Output</entry>
2430        </row>
2431       </thead>
2432       <tbody>
2433        <row>
2434         <entry><literal>to_char(now(),'Day, DD  HH12:MI:SS')</literal></entry>
2435         <entry><literal>'Tuesday  , 06  05:39:18'</literal></entry>
2436        </row>
2437        <row>
2438         <entry><literal>to_char(now(),'FMDay, FMDD  HH12:MI:SS')</literal></entry>
2439         <entry><literal>'Tuesday, 6  05:39:18'</literal></entry>
2440        </row>          
2441        <row>
2442         <entry><literal>to_char(-0.1,'99.99')</literal></entry>
2443         <entry><literal>' -.10'</literal></entry>
2444        </row>
2445        <row>
2446         <entry><literal>to_char(-0.1,'FM9.99')</literal></entry>
2447         <entry><literal>'-.1'</literal></entry>
2448        </row>
2449        <row>
2450         <entry><literal>to_char(0.1,'0.9')</literal></entry>
2451         <entry><literal>' 0.1'</literal></entry>
2452        </row>
2453        <row>
2454         <entry><literal>to_char(12,'9990999.9')</literal></entry>
2455         <entry><literal>'    0012.0'</literal></entry>
2456        </row>
2457        <row>
2458         <entry><literal>to_char(12,'FM9990999.9')</literal></entry>
2459         <entry><literal>'0012'</literal></entry>
2460        </row>
2461        <row>
2462         <entry><literal>to_char(485,'999')</literal></entry>
2463         <entry><literal>' 485'</literal></entry>
2464        </row>
2465        <row>
2466         <entry><literal>to_char(-485,'999')</literal></entry>
2467         <entry><literal>'-485'</literal></entry>
2468        </row>
2469        <row>
2470         <entry><literal>to_char(485,'9 9 9')</literal></entry>
2471         <entry><literal>' 4 8 5'</literal></entry>
2472        </row>
2473        <row>
2474         <entry><literal>to_char(1485,'9,999')</literal></entry>
2475         <entry><literal>' 1,485'</literal></entry>
2476        </row>
2477        <row>
2478         <entry><literal>to_char(1485,'9G999')</literal></entry>
2479         <entry><literal>' 1 485'</literal></entry>
2480        </row>
2481        <row>
2482         <entry><literal>to_char(148.5,'999.999')</literal></entry>
2483         <entry><literal>' 148.500'</literal></entry>
2484        </row>
2485        <row>
2486         <entry><literal>to_char(148.5,'999D999')</literal></entry>
2487         <entry><literal>' 148,500'</literal></entry>     
2488        </row>
2489        <row>
2490         <entry><literal>to_char(3148.5,'9G999D999')</literal></entry>
2491         <entry><literal>' 3 148,500'</literal></entry>
2492        </row>
2493        <row>
2494         <entry><literal>to_char(-485,'999S')</literal></entry>
2495         <entry><literal>'485-'</literal></entry>
2496        </row>
2497        <row>            
2498         <entry><literal>to_char(-485,'999MI')</literal></entry>
2499         <entry><literal>'485-'</literal></entry>        
2500        </row>
2501        <row>
2502         <entry><literal>to_char(485,'999MI')</literal></entry>
2503         <entry><literal>'485'</literal></entry>         
2504        </row>
2505        <row>
2506         <entry><literal>to_char(485,'PL999')</literal></entry>
2507         <entry><literal>'+485'</literal></entry>        
2508        </row>
2509        <row>            
2510         <entry><literal>to_char(485,'SG999')</literal></entry>
2511         <entry><literal>'+485'</literal></entry>        
2512        </row>
2513        <row>
2514         <entry><literal>to_char(-485,'SG999')</literal></entry>
2515         <entry><literal>'-485'</literal></entry>        
2516        </row>
2517        <row>
2518         <entry><literal>to_char(-485,'9SG99')</literal></entry>
2519         <entry><literal>'4-85'</literal></entry>        
2520        </row>
2521        <row>
2522         <entry><literal>to_char(-485,'999PR')</literal></entry>
2523         <entry><literal>'&lt;485&gt;'</literal></entry>         
2524        </row>
2525        <row>
2526         <entry><literal>to_char(485,'L999')</literal></entry>
2527         <entry><literal>'DM 485</literal></entry>        
2528        </row>
2529        <row>
2530         <entry><literal>to_char(485,'RN')</literal></entry>             
2531         <entry><literal>'        CDLXXXV'</literal></entry>
2532        </row>
2533        <row>
2534         <entry><literal>to_char(485,'FMRN')</literal></entry>   
2535         <entry><literal>'CDLXXXV'</literal></entry>
2536        </row>
2537        <row>
2538         <entry><literal>to_char(5.2,'FMRN')</literal></entry>
2539         <entry><literal>V</literal></entry>             
2540        </row>
2541        <row>
2542         <entry><literal>to_char(482,'999th')</literal></entry>
2543         <entry><literal>' 482nd'</literal></entry>                              
2544        </row>
2545        <row>
2546         <entry><literal>to_char(485, '"Good number:"999')</literal></entry>
2547         <entry><literal>'Good number: 485'</literal></entry>
2548        </row>
2549        <row>
2550         <entry><literal>to_char(485.8,'"Pre:"999" Post:" .999')</literal></entry>
2551         <entry><literal>'Pre: 485 Post: .800'</literal></entry>
2552        </row>
2553        <row>
2554         <entry><literal>to_char(12,'99V999')</literal></entry>          
2555         <entry><literal>' 12000'</literal></entry>
2556        </row>
2557        <row>
2558         <entry><literal>to_char(12.4,'99V999')</literal></entry>
2559         <entry><literal>' 12400'</literal></entry>
2560        </row>
2561        <row>            
2562         <entry><literal>to_char(12.45, '99V9')</literal></entry>
2563         <entry><literal>' 125'</literal></entry>
2564        </row>
2565       </tbody>
2566      </tgroup>
2567     </table>
2568
2569   </sect1>
2570
2571
2572   <sect1 id="functions-datetime">
2573    <title>Date/Time Functions and Operators</title>
2574
2575    <para>
2576     <xref linkend="functions-datetime-table"> shows the available
2577     functions for date/time value processing.  
2578     <xref linkend="operators-datetime-table"> illustrates the
2579     behaviors of the basic arithmetic
2580     operators (<literal>+</literal>, <literal>*</literal>, etc.).
2581     For formatting functions, refer to <xref
2582                                              linkend="functions-formatting">.  You should be familiar with the
2583     background information on date/time data types (see <xref
2584                                                               linkend="datatype-datetime">).
2585    </para>
2586
2587    <para>
2588     The date/time operators described below behave similarly for types
2589     involving time zones as well as those without.
2590
2591     <table id="operators-datetime-table">
2592      <title>Date/Time Operators</title>
2593
2594      <tgroup cols="3">
2595       <thead>
2596        <row>
2597         <entry>Name</entry>
2598         <entry>Example</entry>
2599         <entry>Result</entry>
2600        </row>
2601       </thead>
2602
2603       <tbody>
2604        <row>
2605         <entry> <literal>+</literal> </entry>
2606         <entry><type>timestamp</type> '2001-09-28 01:00' + <type>interval</type> '23 hours'</entry>
2607         <entry><type>timestamp</type> '2001-09-29 00:00'</entry>
2608        </row>
2609
2610        <row>
2611         <entry> <literal>+</literal> </entry>
2612         <entry><type>date</type> '2001-09-28' + <type>interval</type> '1 hour'</entry>
2613         <entry><type>timestamp</type> '2001-09-28 01:00'</entry>
2614        </row>
2615
2616        <row>
2617         <entry> <literal>+</literal> </entry>
2618         <entry><type>time</type> '01:00' + <type>interval</type> '3 hours'</entry>
2619         <entry><type>time</type> '04:00'</entry>
2620        </row>
2621
2622        <row>
2623         <entry> <literal>-</literal> </entry>
2624         <entry><type>timestamp</type> '2001-09-28 23:00' - <type>interval</type> '23 hours'</entry>
2625         <entry><type>timestamp</type> '2001-09-28'</entry>
2626        </row>
2627
2628        <row>
2629         <entry> <literal>-</literal> </entry>
2630         <entry><type>date</type> '2001-09-28' - <type>interval</type> '1 hour'</entry>
2631         <entry><type>timestamp</type> '2001-09-27 23:00'</entry>
2632        </row>
2633
2634        <row>
2635         <entry> <literal>-</literal> </entry>
2636         <entry><type>time</type> '05:00' - <type>interval</type> '2 hours'</entry>
2637         <entry><type>time</type> '03:00'</entry>
2638        </row>
2639
2640        <row>
2641         <entry> <literal>-</literal> </entry>
2642         <entry><type>interval</type> '2 hours' - <type>time</type> '05:00'</entry>
2643         <entry><type>time</type> '03:00:00'</entry>
2644        </row>
2645
2646        <row>
2647         <entry> <literal>*</literal> </entry>
2648         <entry><type>interval</type> '1 hour' * <type>int</type> '3'</entry>
2649         <entry><type>interval</type> '03:00'</entry>
2650        </row>
2651
2652        <row>
2653         <entry> <literal>/</literal> </entry>
2654         <entry><type>interval</type> '1 hour' / <type>int</type> '3'</entry>
2655         <entry><type>interval</type> '00:20'</entry>
2656        </row>
2657       </tbody>
2658      </tgroup>
2659     </table>
2660    </para>
2661
2662    <para>
2663     The date/time functions are summarized below, with additional
2664     details in subsequent sections.
2665
2666     <table id="functions-datetime-table">
2667      <title>Date/Time Functions</title>
2668      <tgroup cols="5">
2669       <thead>
2670        <row>
2671         <entry>Name</entry>
2672         <entry>Return Type</entry>
2673         <entry>Description</entry>
2674         <entry>Example</entry>
2675         <entry>Result</entry>
2676        </row>
2677       </thead>
2678
2679       <tbody>
2680        <row>
2681         <entry><function>age</function>(<type>timestamp</type>)</entry>
2682         <entry><type>interval</type></entry>
2683         <entry>Subtract from today</entry>
2684         <entry><literal>age(timestamp '1957-06-13')</literal></entry>
2685         <entry><literal>43 years 8 mons 3 days</literal></entry>
2686        </row>
2687
2688        <row>
2689         <entry><function>age</function>(<type>timestamp</type>, <type>timestamp</type>)</entry>
2690         <entry><type>interval</type></entry>
2691         <entry>Subtract arguments</entry>
2692         <entry><literal>age('2001-04-10', timestamp '1957-06-13')</literal></entry>
2693         <entry><literal>43 years 9 mons 27 days</literal></entry>
2694        </row>
2695
2696        <row>
2697         <entry><function>current_date</function></entry>
2698         <entry><type>date</type></entry>
2699         <entry>Today's date; see <link linkend="functions-datetime-current">below</link>
2700         </entry>
2701         <entry></entry>
2702         <entry></entry>
2703        </row>
2704
2705        <row>
2706         <entry><function>current_time</function></entry>
2707         <entry><type>time with time zone</type></entry>
2708         <entry>Time of day; see <link linkend="functions-datetime-current">below</link>
2709         </entry>
2710         <entry></entry>
2711         <entry></entry>
2712        </row>
2713
2714        <row>
2715         <entry><function>current_timestamp</function></entry>
2716         <entry><type>timestamp with time zone</type></entry>
2717         <entry>Date and time; see <link linkend="functions-datetime-current">below</link>
2718         </entry>
2719         <entry></entry>
2720         <entry></entry>
2721        </row>
2722
2723        <row>
2724         <entry><function>date_part</function>(<type>text</type>, <type>timestamp</type>)</entry>
2725         <entry><type>double precision</type></entry>
2726         <entry>Get subfield (equivalent to
2727          <function>extract</function>); see also <link
2728                                                 linkend="functions-datetime-datepart">below</link>
2729         </entry>
2730         <entry><literal>date_part('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
2731         <entry><literal>20</literal></entry>
2732        </row>
2733
2734        <row>
2735         <entry><function>date_part</function>(<type>text</type>, <type>interval</type>)</entry>
2736         <entry><type>double precision</type></entry>
2737         <entry>Get subfield (equivalent to
2738          <function>extract</function>); see also <link
2739                                                 linkend="functions-datetime-datepart">below</link>
2740         </entry>
2741         <entry><literal>date_part('month', interval '2 years 3 months')</literal></entry>
2742         <entry><literal>3</literal></entry>
2743        </row>
2744
2745        <row>
2746         <entry><function>date_trunc</function>(<type>text</type>, <type>timestamp</type>)</entry>
2747         <entry><type>timestamp</type></entry>
2748         <entry>Truncate to specified precision; see also <link
2749                                                         linkend="functions-datetime-trunc">below</link>
2750         </entry>
2751         <entry><literal>date_trunc('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
2752         <entry><literal>2001-02-16 20:00:00+00</literal></entry>
2753        </row>
2754
2755        <row>
2756         <entry><function>extract</function>(<parameter>field</parameter> from
2757          <type>timestamp</type>)</entry>
2758         <entry><type>double precision</type></entry>
2759         <entry>Get subfield; see also <link
2760                                      linkend="functions-datetime-extract">below</link>
2761         </entry>
2762         <entry><literal>extract(hour from timestamp '2001-02-16 20:38:40')</literal></entry>
2763         <entry><literal>20</literal></entry>
2764        </row>
2765
2766        <row>
2767         <entry><function>extract</function>(<parameter>field</parameter> from
2768          <type>interval</type>)</entry>
2769         <entry><type>double precision</type></entry>
2770         <entry>Get subfield; see also <link
2771                                      linkend="functions-datetime-extract">below</link>
2772         </entry>
2773         <entry><literal>extract(month from interval '2 years 3 months')</literal></entry>
2774         <entry><literal>3</literal></entry>
2775        </row>
2776
2777        <row>
2778         <entry><function>isfinite</function>(<type>timestamp</type>)</entry>
2779         <entry><type>boolean</type></entry>
2780         <entry>Test for finite time stamp (neither invalid nor infinity)</entry>
2781         <entry><literal>isfinite(timestamp '2001-02-16 21:28:30')</literal></entry>
2782         <entry><literal>true</literal></entry>
2783        </row>
2784
2785        <row>
2786         <entry><function>isfinite</function>(<type>interval</type>)</entry>
2787         <entry><type>boolean</type></entry>
2788         <entry>Test for finite interval</entry>
2789         <entry><literal>isfinite(interval '4 hours')</literal></entry>
2790         <entry><literal>true</literal></entry>
2791        </row>
2792
2793        <row>
2794         <entry><function>localtime</function></entry>
2795         <entry><type>time</type></entry>
2796         <entry>Time of day; see <link linkend="functions-datetime-current">below</link>
2797         </entry>
2798         <entry></entry>
2799         <entry></entry>
2800        </row>
2801
2802        <row>
2803         <entry><function>localtimestamp</function></entry>
2804         <entry><type>timestamp</type></entry>
2805         <entry>Date and time; see <link linkend="functions-datetime-current">below</link>
2806         </entry>
2807         <entry></entry>
2808         <entry></entry>
2809        </row>
2810
2811        <row>
2812         <entry><function>now</function>()</entry>
2813         <entry><type>timestamp</type></entry>
2814         <entry>Current date and time (equivalent to
2815          <function>current_timestamp</function>); see <link
2816                                                      linkend="functions-datetime-current">below</link>
2817         </entry>
2818         <entry></entry>
2819         <entry></entry>
2820        </row>
2821
2822        <row>
2823         <entry><function>timeofday()</function></entry>
2824         <entry><type>text</type></entry>
2825         <entry>Current date and time; see <link
2826                                          linkend="functions-datetime-current">below</link>
2827         </entry>
2828         <entry><literal>timeofday()</literal></entry>
2829         <entry><literal>Wed Feb 21 17:01:13.000126 2001 EST</literal></entry>
2830        </row>
2831
2832       </tbody>
2833      </tgroup>
2834     </table>
2835    </para>
2836
2837   <sect2 id="functions-datetime-extract">
2838    <title><function>EXTRACT</function>, <function>date_part</function></title>
2839
2840 <synopsis>
2841 EXTRACT (<replaceable>field</replaceable> FROM <replaceable>source</replaceable>)
2842 </synopsis>
2843
2844    <para>
2845     The <function>extract</function> function retrieves sub-fields
2846     from date/time values, such as year or hour.
2847     <replaceable>source</replaceable> is a value expression that
2848     evaluates to type <type>timestamp</type> or <type>interval</type>.
2849     (Expressions of type <type>date</type> or <type>time</type> will
2850     be cast to <type>timestamp</type> and can therefore be used as
2851     well.)  <replaceable>field</replaceable> is an identifier or
2852     string that selects what field to extract from the source value.
2853     The <function>extract</function> function returns values of type
2854     <type>double precision</type>.
2855     The following are valid values:
2856
2857     <!-- alphabetical -->
2858     <variablelist>
2859      <varlistentry>
2860       <term><literal>century</literal></term>
2861       <listitem>
2862        <para>
2863         The year field divided by 100
2864        </para>
2865
2866        <informalexample>
2867 <screen>
2868 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
2869 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
2870 </screen>
2871        </informalexample>
2872
2873        <para>
2874         Note that the result for the century field is simply the year field
2875         divided by 100, and not the conventional definition which puts most
2876         years in the 1900's in the twentieth century.
2877        </para>
2878       </listitem>
2879      </varlistentry>
2880
2881      <varlistentry>
2882       <term><literal>day</literal></term>
2883       <listitem>
2884        <para>
2885         The day (of the month) field (1 - 31)
2886        </para>
2887
2888        <informalexample>
2889 <screen>
2890 SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
2891 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
2892 </screen>
2893        </informalexample>
2894       </listitem>
2895      </varlistentry>
2896
2897      <varlistentry>
2898       <term><literal>decade</literal></term>
2899       <listitem>
2900        <para>
2901         The year field divided by 10
2902        </para>
2903
2904        <informalexample>
2905 <screen>
2906 SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
2907 <lineannotation>Result: </lineannotation><computeroutput>200</computeroutput>
2908 </screen>
2909        </informalexample>
2910       </listitem>
2911      </varlistentry>
2912
2913      <varlistentry>
2914       <term><literal>dow</literal></term>
2915       <listitem>
2916        <para>
2917         The day of the week (0 - 6; Sunday is 0) (for
2918         <type>timestamp</type> values only)
2919        </para>
2920
2921        <informalexample>
2922 <screen>
2923 SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
2924 <lineannotation>Result: </lineannotation><computeroutput>5</computeroutput>
2925 </screen>
2926        </informalexample>
2927       </listitem>
2928      </varlistentry>
2929
2930      <varlistentry>
2931       <term><literal>doy</literal></term>
2932       <listitem>
2933        <para>
2934         The day of the year (1 - 365/366) (for <type>timestamp</type> values only)
2935        </para>
2936        <informalexample>
2937 <screen>
2938 SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
2939 <lineannotation>Result: </lineannotation><computeroutput>47</computeroutput>
2940 </screen>
2941        </informalexample>
2942       </listitem>
2943      </varlistentry>
2944
2945      <varlistentry>
2946       <term><literal>epoch</literal></term>
2947       <listitem>
2948        <para>
2949         For <type>date</type> and <type>timestamp</type> values, the
2950         number of seconds since 1970-01-01 00:00:00-00 (Result may be
2951         negative.); for <type>interval</type> values, the total number
2952         of seconds in the interval
2953        </para>
2954
2955        <informalexample>
2956 <screen>
2957 SELECT EXTRACT(EPOCH FROM TIMESTAMP '2001-02-16 20:38:40');
2958 <lineannotation>Result: </lineannotation><computeroutput>982352320</computeroutput>
2959
2960 SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
2961 <lineannotation>Result: </lineannotation><computeroutput>442800</computeroutput>
2962 </screen>
2963        </informalexample>
2964       </listitem>
2965      </varlistentry>
2966
2967      <varlistentry>
2968       <term><literal>hour</literal></term>
2969       <listitem>
2970        <para>
2971         The hour field (0 - 23)
2972        </para>
2973
2974        <informalexample>
2975 <screen>
2976 SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
2977 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
2978 </screen>
2979        </informalexample>
2980       </listitem>
2981      </varlistentry>
2982
2983      <varlistentry>
2984       <term><literal>microseconds</literal></term>
2985       <listitem>
2986        <para>
2987         The seconds field, including fractional parts, multiplied by 1
2988         000 000.  Note that this includes full seconds.
2989        </para>
2990
2991        <informalexample>
2992 <screen>
2993 SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
2994 <lineannotation>Result: </lineannotation><computeroutput>28500000</computeroutput>
2995 </screen>
2996        </informalexample>
2997       </listitem>
2998      </varlistentry>
2999
3000      <varlistentry>
3001       <term><literal>millennium</literal></term>
3002       <listitem>
3003        <para>
3004         The year field divided by 1000
3005        </para>
3006
3007        <informalexample>
3008 <screen>
3009 SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
3010 <lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
3011 </screen>
3012        </informalexample>
3013
3014        <para>
3015         Note that the result for the millennium field is simply the year field
3016         divided by 1000, and not the conventional definition which puts
3017         years in the 1900's in the second millennium.
3018        </para>
3019       </listitem>
3020      </varlistentry>
3021
3022      <varlistentry>
3023       <term><literal>milliseconds</literal></term>
3024       <listitem>
3025        <para>
3026         The seconds field, including fractional parts, multiplied by
3027         1000.  Note that this includes full seconds.
3028        </para>
3029
3030        <informalexample>
3031 <screen>
3032 SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
3033 <lineannotation>Result: </lineannotation><computeroutput>28500</computeroutput>
3034 </screen>
3035        </informalexample>
3036       </listitem>
3037      </varlistentry>
3038
3039      <varlistentry>
3040       <term><literal>minute</literal></term>
3041       <listitem>
3042        <para>
3043         The minutes field (0 - 59)
3044        </para>
3045
3046        <informalexample>
3047 <screen>
3048 SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
3049 <lineannotation>Result: </lineannotation><computeroutput>38</computeroutput>
3050 </screen>
3051        </informalexample>
3052       </listitem>
3053      </varlistentry>
3054
3055      <varlistentry>
3056       <term><literal>month</literal></term>
3057       <listitem>
3058        <para>
3059         For <type>timestamp</type> values, the number of the month
3060         within the year (1 - 12) ; for <type>interval</type> values
3061         the number of months, modulo 12 (0 - 11)
3062        </para>
3063
3064        <informalexample>
3065 <screen>
3066 SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
3067 <lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
3068
3069 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
3070 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
3071
3072 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
3073 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
3074 </screen>
3075        </informalexample>
3076       </listitem>
3077      </varlistentry>
3078
3079      <varlistentry>
3080       <term><literal>quarter</literal></term>
3081       <listitem>
3082        <para>
3083         The quarter of the year (1 - 4) that the day is in (for
3084         <type>timestamp</type> values only)
3085        </para>
3086
3087        <informalexample>
3088 <screen>
3089 SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
3090 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
3091 </screen>
3092        </informalexample>
3093       </listitem>
3094      </varlistentry>
3095
3096      <varlistentry>
3097       <term><literal>second</literal></term>
3098       <listitem>
3099        <para>
3100         The seconds field, including fractional parts (0 -
3101         59<footnote><simpara>60 if leap seconds are
3102         implemented by the operating system</simpara></footnote>)
3103        </para>
3104
3105        <informalexample>
3106 <screen>
3107 SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
3108 <lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
3109
3110 SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
3111 <lineannotation>Result: </lineannotation><computeroutput>28.5</computeroutput>
3112 </screen>
3113        </informalexample>
3114       </listitem>
3115      </varlistentry>
3116 <!--
3117      <varlistentry>
3118       <term><literal>timezone</literal></term>
3119       <listitem>
3120        <para>
3121         The time zone offset. XXX But in what units?
3122        </para>
3123       </listitem>
3124      </varlistentry>
3125 -->
3126
3127      <varlistentry>
3128       <term><literal>timezone_hour</literal></term>
3129       <listitem>
3130        <para>
3131         The hour component of the time zone offset.
3132        </para>
3133       </listitem>
3134      </varlistentry>
3135
3136      <varlistentry>
3137       <term><literal>timezone_minute</literal></term>
3138       <listitem>
3139        <para>
3140         The minute component of the time zone offset.
3141        </para>
3142       </listitem>
3143      </varlistentry>
3144
3145      <varlistentry>
3146       <term><literal>week</literal></term>
3147       <listitem>
3148        <para>
3149         From a <type>timestamp</type> value, calculate the number of
3150         the week of the year that the day is in.  By definition
3151         (<acronym>ISO</acronym> 8601), the first week of a year
3152         contains January 4 of that year.  (The <acronym>ISO</acronym>
3153         week starts on Monday.)  In other words, the first Thursday of
3154         a year is in week 1 of that year.
3155        </para>
3156
3157        <informalexample>
3158 <screen>
3159 SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
3160 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
3161 </screen>
3162        </informalexample>
3163       </listitem>
3164      </varlistentry>
3165
3166      <varlistentry>
3167       <term><literal>year</literal></term>
3168       <listitem>
3169        <para>
3170         The year field
3171        </para>
3172
3173        <informalexample>
3174 <screen>
3175 SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
3176 <lineannotation>Result: </lineannotation><computeroutput>2001</computeroutput>
3177 </screen>
3178        </informalexample>
3179       </listitem>
3180      </varlistentry>
3181
3182     </variablelist>
3183
3184    </para>
3185
3186    <para>
3187     The <function>extract</function> function is primarily intended
3188     for computational processing.  For formatting date/time values for
3189     display, see <xref linkend="functions-formatting">.
3190    </para>
3191
3192    <anchor id="functions-datetime-datepart">
3193    <para>
3194     The <function>date_part</function> function is modeled on the traditional
3195     <productname>Ingres</productname> equivalent to the
3196     <acronym>SQL</acronym>-function <function>extract</function>:
3197 <synopsis>
3198 date_part('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
3199 </synopsis>
3200     Note that here the <replaceable>field</replaceable> value needs to
3201     be a string.  The valid field values for
3202     <function>date_part</function> are the same as for
3203     <function>extract</function>.
3204    </para>
3205
3206    <informalexample>
3207 <screen>
3208 SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
3209 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
3210
3211 SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
3212 <lineannotation>Result: </lineannotation><computeroutput>4</computeroutput>
3213 </screen>
3214    </informalexample>
3215
3216   </sect2>
3217
3218   <sect2 id="functions-datetime-trunc">
3219    <title><function>date_trunc</function></title>
3220
3221    <para>
3222     The function <function>date_trunc</function> is conceptually
3223     similar to the <function>trunc</function> function for numbers.
3224    </para>
3225
3226    <para>
3227 <synopsis>
3228 date_trunc('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
3229 </synopsis>
3230     <replaceable>source</replaceable> is a value expression of type
3231     <type>timestamp</type> (values of type <type>date</type> and
3232     <type>time</type> are cast automatically).
3233     <replaceable>field</replaceable> selects to which precision to
3234     truncate the time stamp value.  The return value is of type
3235     <type>timestamp</type> with all fields that are less than the
3236     selected one set to zero (or one, for day and month).
3237    </para>
3238
3239    <para>
3240     Valid values for <replaceable>field</replaceable> are:
3241     <simplelist>
3242      <member>microseconds</member>
3243      <member>milliseconds</member>
3244      <member>second</member>
3245      <member>minute</member>
3246      <member>hour</member>
3247      <member>day</member>
3248      <member>month</member>
3249      <member>year</member>
3250      <member>decade</member>
3251      <member>century</member>
3252      <member>millennium</member>
3253     </simplelist>
3254    </para>
3255
3256    <informalexample>
3257     <para>
3258 <screen>
3259 SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
3260 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 20:00:00+00</computeroutput>
3261
3262 SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
3263 <lineannotation>Result: </lineannotation><computeroutput>2001-01-01 00:00:00+00</computeroutput>
3264 </screen>
3265     </para>
3266    </informalexample>
3267   </sect2>
3268
3269   <sect2 id="functions-datetime-current">
3270    <title>Current Date/Time</title>
3271
3272    <indexterm>
3273     <primary>date</primary>
3274     <secondary>current</secondary>
3275    </indexterm>
3276
3277    <indexterm>
3278     <primary>time</primary>
3279     <secondary>current</secondary>
3280    </indexterm>
3281
3282    <para>
3283     The following functions are available to obtain the current date and/or
3284     time:
3285      <synopsis>
3286 CURRENT_DATE
3287 CURRENT_TIME
3288 CURRENT_TIMESTAMP
3289 CURRENT_TIME ( <replaceable>precision</replaceable> )
3290 CURRENT_TIMESTAMP ( <replaceable>precision</replaceable> )
3291 LOCALTIME
3292 LOCALTIMESTAMP
3293 LOCALTIME ( <replaceable>precision</replaceable> )
3294 LOCALTIMESTAMP ( <replaceable>precision</replaceable> )
3295      </synopsis>
3296      <function>CURRENT_TIME</function>,
3297      <function>CURRENT_TIMESTAMP</function>,
3298      <function>LOCALTIME</function>, and
3299      <function>LOCALTIMESTAMP</function>
3300      can optionally be given
3301      a precision parameter, which causes the result to be rounded
3302      to that many fractional digits.  Without a precision parameter,
3303      the result is given to the full available precision.
3304     </para>
3305
3306     <note>
3307      <para>
3308       Prior to <productname>PostgreSQL</productname> 7.2, the precision
3309       parameters were unimplemented, and the result was always given
3310       in integer seconds.
3311      </para>
3312     </note>
3313
3314     <informalexample>
3315      <screen>
3316 SELECT CURRENT_TIME;
3317 <computeroutput>14:39:53.662522-05</computeroutput>
3318
3319 SELECT CURRENT_DATE;
3320 <computeroutput>2001-12-23</computeroutput>
3321
3322 SELECT CURRENT_TIMESTAMP;
3323 <computeroutput>2001-12-23 14:39:53.662522-05</computeroutput>
3324
3325 SELECT CURRENT_TIMESTAMP(2);
3326 <computeroutput>2001-12-23 14:39:53.66-05</computeroutput>
3327
3328 SELECT LOCALTIMESTAMP;
3329 <computeroutput>2001-12-23 14:39:53.662522</computeroutput>
3330 </screen>
3331    </informalexample>
3332
3333    <para>
3334     The function <function>now()</function> is the traditional
3335     <productname>PostgreSQL</productname> equivalent to
3336     <function>CURRENT_TIMESTAMP</function>.
3337    </para>
3338
3339    <para>
3340     There is also <function>timeofday()</function>, which for historical
3341     reasons returns a text string rather than a <type>timestamp</type> value:
3342    </para>
3343
3344    <informalexample>
3345 <screen>
3346 SELECT timeofday();
3347  Sat Feb 17 19:07:32.000126 2001 EST
3348 </screen>
3349    </informalexample>
3350
3351    <para>
3352     It is quite important to realize that
3353     <function>CURRENT_TIMESTAMP</function> and related functions all return
3354     the time as of the start of the current transaction; their values do not
3355     increment while a transaction is running.  But
3356     <function>timeofday()</function> returns the actual current time.
3357    </para>
3358
3359    <para>
3360     All the date/time data types also accept the special literal value
3361     <literal>now</literal> to specify the current date and time.  Thus,
3362     the following three all return the same result:
3363 <programlisting>
3364 SELECT CURRENT_TIMESTAMP;
3365 SELECT now();
3366 SELECT TIMESTAMP 'now';
3367 </programlisting>
3368     <note>
3369      <para>
3370       You do not want to use the third form when specifying a DEFAULT
3371       value while creating a table.  The system will convert <literal>now</literal>
3372       to a <type>timestamp</type> as soon as the constant is parsed, so that when
3373       the default value is needed,
3374       the time of the table creation would be used!  The first two
3375       forms will not be evaluated until the default value is used,
3376       because they are function calls.  Thus they will give the desired
3377       behavior of defaulting to the time of row insertion.
3378      </para>
3379     </note>
3380    </para>
3381   </sect2>
3382  </sect1>
3383
3384   
3385  <sect1 id="functions-geometry">
3386    <title>Geometric Functions and Operators</title>
3387
3388    <para>
3389     The geometric types <type>point</type>, <type>box</type>,
3390     <type>lseg</type>, <type>line</type>, <type>path</type>,
3391     <type>polygon</type>, and <type>circle</type> have a large set of
3392     native support functions and operators.
3393    </para>
3394
3395    <table>
3396      <title>Geometric Operators</title>
3397      <tgroup cols="3">
3398       <thead>
3399        <row>
3400         <entry>Operator</entry>
3401         <entry>Description</entry>
3402         <entry>Usage</entry>
3403        </row>
3404       </thead>
3405       <tbody>
3406        <row>
3407         <entry> + </entry>
3408         <entry>Translation</entry>
3409         <entry><literal>box '((0,0),(1,1))' + point '(2.0,0)'</literal></entry>
3410        </row>
3411        <row>
3412         <entry> - </entry>
3413         <entry>Translation</entry>
3414         <entry><literal>box '((0,0),(1,1))' - point '(2.0,0)'</literal></entry>
3415        </row>
3416        <row>
3417         <entry> * </entry>
3418         <entry>Scaling/rotation</entry>
3419         <entry><literal>box '((0,0),(1,1))' * point '(2.0,0)'</literal></entry>
3420        </row>
3421        <row>
3422         <entry> / </entry>
3423         <entry>Scaling/rotation</entry>
3424         <entry><literal>box '((0,0),(2,2))' / point '(2.0,0)'</literal></entry>
3425        </row>
3426        <row>
3427         <entry> # </entry>
3428         <entry>Intersection</entry>
3429         <entry><literal>'((1,-1),(-1,1))' # '((1,1),(-1,-1))'</literal></entry>
3430        </row>
3431        <row>
3432         <entry> # </entry>
3433         <entry>Number of points in polygon</entry>
3434         <entry><literal># '((1,0),(0,1),(-1,0))'</literal></entry>
3435        </row>
3436        <row>
3437         <entry> ## </entry>
3438         <entry>Point of closest proximity</entry>
3439         <entry><literal>point '(0,0)' ## lseg '((2,0),(0,2))'</literal></entry>
3440        </row>
3441        <row>
3442         <entry> &amp;&amp; </entry>
3443         <entry>Overlaps?</entry>
3444         <entry><literal>box '((0,0),(1,1))' &amp;&amp; box '((0,0),(2,2))'</literal></entry>
3445        </row>
3446        <row>
3447         <entry> &amp;&lt; </entry>
3448         <entry>Overlaps to left?</entry>
3449         <entry><literal>box '((0,0),(1,1))' &amp;&lt; box '((0,0),(2,2))'</literal></entry>
3450        </row>
3451        <row>
3452         <entry> &amp;&gt; </entry>
3453         <entry>Overlaps to right?</entry>
3454         <entry><literal>box '((0,0),(3,3))' &amp;&gt; box '((0,0),(2,2))'</literal></entry>
3455        </row>
3456        <row>
3457         <entry> &lt;-&gt; </entry>
3458         <entry>Distance between</entry>
3459         <entry><literal>circle '((0,0),1)' &lt;-&gt; circle '((5,0),1)'</literal></entry>
3460        </row>
3461        <row>
3462         <entry> &lt;&lt; </entry>
3463         <entry>Left of?</entry>
3464         <entry><literal>circle '((0,0),1)' &lt;&lt; circle '((5,0),1)'</literal></entry>
3465        </row>
3466        <row>
3467         <entry> &lt;^ </entry>
3468         <entry>Is below?</entry>
3469         <entry><literal>circle '((0,0),1)' &lt;^ circle '((0,5),1)'</literal></entry>
3470        </row>
3471        <row>
3472         <entry> &gt;&gt; </entry>
3473         <entry>Is right of?</entry>
3474         <entry><literal>circle '((5,0),1)' &gt;&gt; circle '((0,0),1)'</literal></entry>
3475        </row>
3476        <row>
3477         <entry> &gt;^ </entry>
3478         <entry>Is above?</entry>
3479         <entry><literal>circle '((0,5),1)' >^ circle '((0,0),1)'</literal></entry>
3480        </row>
3481        <row>
3482         <entry> ?# </entry>
3483         <entry>Intersects or overlaps</entry>
3484         <entry><literal>lseg '((-1,0),(1,0))' ?# box '((-2,-2),(2,2))'</literal></entry>
3485        </row>
3486        <row>
3487         <entry> ?- </entry>
3488         <entry>Is horizontal?</entry>
3489         <entry><literal>point '(1,0)' ?- point '(0,0)'</literal></entry>
3490        </row>
3491        <row>
3492         <entry> ?-| </entry>
3493         <entry>Is perpendicular?</entry>
3494         <entry><literal>lseg '((0,0),(0,1))' ?-| lseg '((0,0),(1,0))'</literal></entry>
3495        </row>
3496        <row>
3497         <entry> @-@  </entry>
3498         <entry>Length or circumference</entry>
3499         <entry><literal>@-@ path '((0,0),(1,0))'</literal></entry>
3500        </row>
3501        <row>
3502         <entry> ?| </entry>
3503         <entry>Is vertical?</entry>
3504         <entry><literal>point '(0,1)' ?| point '(0,0)'</literal></entry>
3505        </row>
3506        <row>
3507         <entry> ?|| </entry>
3508         <entry>Is parallel?</entry>
3509         <entry><literal>lseg '((-1,0),(1,0))' ?|| lseg '((-1,2),(1,2))'</literal></entry>
3510        </row>
3511        <row>
3512         <entry> @ </entry>
3513         <entry>Contained or on</entry>
3514         <entry><literal>point '(1,1)' @ circle '((0,0),2)'</literal></entry>
3515        </row>
3516        <row>
3517         <entry> @@ </entry>
3518         <entry>Center of</entry>
3519         <entry><literal>@@ circle '((0,0),10)'</literal></entry>
3520        </row>
3521        <row>
3522         <entry> ~= </entry>
3523         <entry>Same as</entry>
3524         <entry><literal>polygon '((0,0),(1,1))' ~= polygon '((1,1),(0,0))'</literal></entry>
3525        </row>
3526       </tbody>
3527      </tgroup>
3528    </table>
3529
3530    <table>
3531      <title>Geometric Functions</title>
3532      <tgroup cols="4">
3533       <thead>
3534        <row>
3535         <entry>Function</entry>
3536         <entry>Returns</entry>
3537         <entry>Description</entry>
3538         <entry>Example</entry>
3539        </row>
3540       </thead>
3541       <tbody>
3542        <row>
3543         <entry><function>area</function>(object)</entry>
3544         <entry><type>double precision</type></entry>
3545         <entry>area of item</entry>
3546         <entry><literal>area(box '((0,0),(1,1))')</literal></entry>
3547        </row>
3548        <row>
3549         <entry><function>box</function>(box, box)</entry>
3550         <entry><type>box</type></entry>
3551         <entry>intersection box</entry>
3552         <entry><literal>box(box '((0,0),(1,1))',box '((0.5,0.5),(2,2))')</literal></entry>
3553        </row>
3554        <row>
3555         <entry><function>center</function>(object)</entry>
3556         <entry><type>point</type></entry>
3557         <entry>center of item</entry>
3558         <entry><literal>center(box '((0,0),(1,2))')</literal></entry>
3559        </row>
3560        <row>
3561         <entry><function>diameter</function>(circle)</entry>
3562         <entry><type>double precision</type></entry>
3563         <entry>diameter of circle</entry>
3564         <entry><literal>diameter(circle '((0,0),2.0)')</literal></entry>
3565        </row>
3566        <row>
3567         <entry><function>height</function>(box)</entry>
3568         <entry><type>double precision</type></entry>
3569         <entry>vertical size of box</entry>
3570         <entry><literal>height(box '((0,0),(1,1))')</literal></entry>
3571        </row>
3572        <row>
3573         <entry><function>isclosed</function>(path)</entry>
3574         <entry><type>boolean</type></entry>
3575         <entry>a closed path?</entry>
3576         <entry><literal>isclosed(path '((0,0),(1,1),(2,0))')</literal></entry>
3577        </row>
3578        <row>
3579         <entry><function>isopen</function>(path)</entry>
3580         <entry><type>boolean</type></entry>
3581         <entry>an open path?</entry>
3582         <entry><literal>isopen(path '[(0,0),(1,1),(2,0)]')</literal></entry>
3583        </row>
3584        <row>
3585         <entry><function>length</function>(object)</entry>
3586         <entry><type>double precision</type></entry>
3587         <entry>length of item</entry>
3588         <entry><literal>length(path '((-1,0),(1,0))')</literal></entry>
3589        </row>
3590        <row>
3591         <entry><function>pclose</function>(path)</entry>
3592         <entry><type>path</type></entry>
3593         <entry>convert path to closed</entry>
3594         <entry><literal>popen(path '[(0,0),(1,1),(2,0)]')</literal></entry>
3595        </row>
3596 <![IGNORE[
3597 <!-- Not defined by this name. Implements the intersection operator '#' -->
3598        <row>
3599         <entry><function>point</function>(lseg,lseg)</entry>
3600         <entry><type>point</type></entry>
3601         <entry>intersection</entry>
3602         <entry><literal>point(lseg '((-1,0),(1,0))',lseg '((-2,-2),(2,2))')</literal></entry>
3603        </row>
3604 ]]>
3605        <row>
3606         <entry><function>npoint</function>(path)</entry>
3607         <entry><type>integer</type></entry>
3608         <entry>number of points</entry>
3609         <entry><literal>npoints(path '[(0,0),(1,1),(2,0)]')</literal></entry>
3610        </row>
3611        <row>
3612         <entry><function>popen</function>(path)</entry>
3613         <entry><type>path</type></entry>
3614         <entry>convert path to open path</entry>
3615         <entry><literal>popen(path '((0,0),(1,1),(2,0))')</literal></entry>
3616        </row>
3617        <row>
3618         <entry><function>radius</function>(circle)</entry>
3619         <entry><type>double precision</type></entry>
3620         <entry>radius of circle</entry>
3621         <entry><literal>radius(circle '((0,0),2.0)')</literal></entry>
3622        </row>
3623        <row>
3624         <entry><function>width</function>(box)</entry>
3625         <entry><type>double precision</type></entry>
3626         <entry>horizontal size</entry>
3627         <entry><literal>width(box '((0,0),(1,1))')</literal></entry>
3628        </row>
3629       </tbody>
3630      </tgroup>
3631    </table>
3632
3633
3634    <table>
3635      <title>Geometric Type Conversion Functions</title>
3636      <tgroup cols="4">
3637       <thead>
3638        <row>
3639         <entry>Function</entry>
3640         <entry>Returns</entry>
3641         <entry>Description</entry>
3642         <entry>Example</entry>
3643        </row>
3644       </thead>
3645       <tbody>
3646        <row>
3647         <entry><function>box</function>(<type>circle</type>)</entry>
3648         <entry><type>box</type></entry>
3649         <entry>circle to box</entry>
3650         <entry><literal>box(circle '((0,0),2.0)')</literal></entry>
3651        </row>
3652        <row>
3653         <entry><function>box</function>(<type>point</type>, <type>point</type>)</entry>
3654         <entry><type>box</type></entry>
3655         <entry>points to box</entry>
3656         <entry><literal>box(point '(0,0)', point '(1,1)')</literal></entry>
3657        </row>
3658        <row>
3659         <entry><function>box</function>(<type>polygon</type>)</entry>
3660         <entry><type>box</type></entry>
3661         <entry>polygon to box</entry>
3662         <entry><literal>box(polygon '((0,0),(1,1),(2,0))')</literal></entry>
3663        </row>
3664        <row>
3665         <entry><function>circle</function>(<type>box</type>)</entry>
3666         <entry><type>circle</type></entry>
3667         <entry>to circle</entry>
3668         <entry><literal>circle(box '((0,0),(1,1))')</literal></entry>
3669        </row>
3670        <row>
3671         <entry><function>circle</function>(<type>point</type>, <type>double precision</type>)</entry>
3672         <entry><type>circle</type></entry>
3673         <entry>point to circle</entry>
3674         <entry><literal>circle(point '(0,0)', 2.0)</literal></entry>
3675        </row>
3676        <row>
3677         <entry><function>lseg</function>(<type>box</type>)</entry>
3678         <entry><type>lseg</type></entry>
3679         <entry>box diagonal to <type>lseg</type></entry>
3680         <entry><literal>lseg(box '((-1,0),(1,0))')</literal></entry>
3681        </row>
3682        <row>
3683         <entry><function>lseg</function>(<type>point</type>, <type>point</type>)</entry>
3684         <entry><type>lseg</type></entry>
3685         <entry>points to <type>lseg</type></entry>
3686         <entry><literal>lseg(point '(-1,0)', point '(1,0)')</literal></entry>
3687        </row>
3688        <row>
3689         <entry><function>path</function>(<type>polygon</type>)</entry>
3690         <entry><type>point</type></entry>
3691         <entry>polygon to path</entry>
3692         <entry><literal>path(polygon '((0,0),(1,1),(2,0))')</literal></entry>
3693        </row>
3694        <row>
3695         <entry><function>point</function>(<type>circle</type>)</entry>
3696         <entry><type>point</type></entry>
3697         <entry>center</entry>
3698         <entry><literal>point(circle '((0,0),2.0)')</literal></entry>
3699        </row>
3700        <row>
3701         <entry><function>point</function>(<type>lseg</type>, <type>lseg</type>)</entry>
3702         <entry><type>point</type></entry>
3703         <entry>intersection</entry>
3704         <entry><literal>point(lseg '((-1,0),(1,0))', lseg '((-2,-2),(2,2))')</literal></entry>
3705        </row>
3706        <row>
3707         <entry><function>point</function>(<type>polygon</type>)</entry>
3708         <entry><type>point</type></entry>
3709         <entry>center</entry>
3710         <entry><literal>point(polygon '((0,0),(1,1),(2,0))')</literal></entry>
3711        </row>
3712        <row>
3713         <entry><function>polygon</function>(<type>box</type>)</entry>
3714         <entry><type>polygon</type></entry>
3715         <entry>12 point polygon</entry>
3716         <entry><literal>polygon(box '((0,0),(1,1))')</literal></entry>
3717        </row>
3718        <row>
3719         <entry><function>polygon</function>(<type>circle</type>)</entry>
3720         <entry><type>polygon</type></entry>
3721         <entry>12-point polygon</entry>
3722         <entry><literal>polygon(circle '((0,0),2.0)')</literal></entry>
3723        </row>
3724        <row>
3725         <entry><function>polygon</function>(<replaceable class="parameter">npts</replaceable>, <type>circle</type>)</entry>
3726         <entry><type>polygon</type></entry>
3727         <entry><replaceable class="parameter">npts</replaceable> polygon</entry>
3728         <entry><literal>polygon(12, circle '((0,0),2.0)')</literal></entry>
3729        </row>
3730        <row>
3731         <entry><function>polygon</function>(<type>path</type>)</entry>
3732         <entry><type>polygon</type></entry>
3733         <entry>path to polygon</entry>
3734         <entry><literal>polygon(path '((0,0),(1,1),(2,0))')</literal></entry>
3735        </row>
3736       </tbody>
3737      </tgroup>
3738    </table>
3739
3740   </sect1>
3741
3742
3743   <sect1 id="functions-net">
3744    <title>Network Address Type Functions</title>
3745
3746
3747     <table tocentry="1" id="cidr-inet-operators-table">
3748      <title><type>cidr</type> and <type>inet</type> Operators</title>
3749      <tgroup cols="3">
3750       <thead>
3751        <row>
3752         <entry>Operator</entry>
3753         <entry>Description</entry>
3754         <entry>Usage</entry>
3755        </row>
3756       </thead>
3757       <tbody>
3758        <row>
3759         <entry> &lt; </entry>
3760         <entry>Less than</entry>
3761         <entry><literal>inet '192.168.1.5' &lt; inet '192.168.1.6'</literal></entry>
3762        </row>
3763        <row>
3764         <entry> &lt;= </entry>
3765         <entry>Less than or equal</entry>
3766         <entry><literal>inet '192.168.1.5' &lt;= inet '192.168.1.5'</literal></entry>
3767        </row>
3768        <row>
3769         <entry> = </entry>
3770         <entry>Equals</entry>
3771         <entry><literal>inet '192.168.1.5' = inet '192.168.1.5'</literal></entry>
3772        </row>
3773        <row>
3774         <entry> &gt;= </entry>
3775         <entry>Greater or equal</entry>
3776         <entry><literal>inet '192.168.1.5' &gt;= inet '192.168.1.5'</literal></entry>
3777        </row>
3778        <row>
3779         <entry> &gt; </entry>
3780         <entry>Greater</entry>
3781         <entry><literal>inet '192.168.1.5' &gt; inet '192.168.1.4'</literal></entry>
3782        </row>
3783        <row>
3784         <entry> &lt;&gt; </entry>
3785         <entry>Not equal</entry>
3786         <entry><literal>inet '192.168.1.5' &lt;&gt; inet '192.168.1.4'</literal></entry>
3787        </row>
3788        <row>
3789         <entry> &lt;&lt; </entry>
3790         <entry>is contained within</entry>
3791         <entry><literal>inet '192.168.1.5' &lt;&lt; inet '192.168.1/24'</literal></entry>
3792        </row>
3793        <row>
3794         <entry> &lt;&lt;= </entry>
3795         <entry>is contained within or equals</entry>
3796         <entry><literal>inet '192.168.1/24' &lt;&lt;= inet '192.168.1/24'</literal></entry>
3797        </row>
3798        <row>
3799         <entry> &gt;&gt; </entry>
3800         <entry>contains</entry>
3801         <entry><literal>inet'192.168.1/24' &gt;&gt; inet '192.168.1.5'</literal></entry>
3802        </row>
3803        <row>
3804         <entry> &gt;&gt;= </entry>
3805         <entry>contains or equals</entry>
3806         <entry><literal>inet '192.168.1/24' &gt;&gt;= inet '192.168.1/24'</literal></entry>
3807        </row>
3808       </tbody>
3809      </tgroup>
3810     </table>
3811
3812     <para>
3813      All of the operators for <type>inet</type> can be applied to
3814      <type>cidr</type> values as well.  The operators
3815      <literal>&lt;&lt;</literal>, <literal>&lt;&lt;=</literal>,
3816      <literal>&gt;&gt;</literal>, <literal>&gt;&gt;=</literal>
3817      test for subnet inclusion: they consider only the network parts
3818      of the two addresses, ignoring any host part, and determine whether
3819      one network part is identical to or a subnet of the other.
3820     </para>
3821
3822
3823     <table tocentry="1" id="cidr-inet-functions">
3824      <title><type>cidr</type> and <type>inet</type> Functions</title>
3825      <tgroup cols="5">
3826       <thead>
3827        <row>
3828         <entry>Function</entry>
3829         <entry>Returns</entry>
3830         <entry>Description</entry>
3831         <entry>Example</entry>
3832         <entry>Result</entry>
3833        </row>
3834       </thead>
3835       <tbody>
3836        <row>
3837         <entry><function>broadcast</function>(<type>inet</type>)</entry>
3838         <entry><type>inet</type></entry>
3839         <entry>broadcast address for network</entry>
3840         <entry><literal>broadcast('192.168.1.5/24')</literal></entry>
3841         <entry><literal>192.168.1.255/24</literal></entry>
3842        </row>
3843        <row>
3844         <entry><function>host</function>(<type>inet</type>)</entry>
3845         <entry><type>text</type></entry>
3846         <entry>extract IP address as text</entry>
3847         <entry><literal>host('192.168.1.5/24')</literal></entry>
3848         <entry><literal>192.168.1.5</literal></entry>
3849        </row>
3850        <row>
3851         <entry><function>masklen</function>(<type>inet</type>)</entry>
3852         <entry><type>integer</type></entry>
3853         <entry>extract netmask length</entry>
3854         <entry><literal>masklen('192.168.1.5/24')</literal></entry>
3855         <entry><literal>24</literal></entry>
3856        </row>
3857        <row>
3858         <entry><function>set_masklen</function>(<type>inet</type>,<type>integer</type>)</entry>
3859         <entry><type>inet</type></entry>
3860         <entry>set netmask length for <type>inet</type> value</entry>
3861         <entry><literal>set_masklen('192.168.1.5/24',16)</literal></entry>
3862         <entry><literal>192.168.1.5/16</literal></entry>
3863        </row>
3864        <row>
3865         <entry><function>netmask</function>(<type>inet</type>)</entry>
3866         <entry><type>inet</type></entry>
3867         <entry>construct netmask for network</entry>
3868         <entry><literal>netmask('192.168.1.5/24')</literal></entry>
3869         <entry><literal>255.255.255.0</literal></entry>
3870        </row>
3871        <row>
3872         <entry><function>network</function>(<type>inet</type>)</entry>
3873         <entry><type>cidr</type></entry>
3874         <entry>extract network part of address</entry>
3875         <entry><literal>network('192.168.1.5/24')</literal></entry>
3876         <entry><literal>192.168.1.0/24</literal></entry>
3877        </row>
3878        <row>
3879         <entry><function>text</function>(<type>inet</type>)</entry>
3880         <entry><type>text</type></entry>
3881         <entry>extract IP address and masklen as text</entry>
3882         <entry><literal>text(inet '192.168.1.5')</literal></entry>
3883         <entry><literal>192.168.1.5/32</literal></entry>
3884        </row>
3885        <row>
3886         <entry><function>abbrev</function>(<type>inet</type>)</entry>
3887         <entry><type>text</type></entry>
3888         <entry>extract abbreviated display as text</entry>
3889         <entry><literal>abbrev(cidr '10.1.0.0/16')</literal></entry>
3890         <entry><literal>10.1/16</literal></entry>
3891        </row>
3892       </tbody>
3893      </tgroup>
3894     </table>
3895
3896    <para>
3897     All of the functions for <type>inet</type> can be applied to
3898     <type>cidr</type> values as well.  The <function>host</function>(),
3899     <function>text</function>(), and <function>abbrev</function>() functions are primarily
3900     intended to offer alternative display formats. You can cast a text
3901     field to inet using normal casting syntax: <literal>inet(expression)</literal> or 
3902     <literal>colname::inet</literal>.
3903    </para>
3904
3905     <table tocentry="1" id="macaddr-functions">
3906      <title><type>macaddr</type> Functions</title>
3907      <tgroup cols="5">
3908       <thead>
3909        <row>
3910         <entry>Function</entry>
3911         <entry>Returns</entry>
3912         <entry>Description</entry>
3913         <entry>Example</entry>
3914         <entry>Result</entry>
3915        </row>
3916       </thead>
3917       <tbody>
3918        <row>
3919         <entry><function>trunc</function>(<type>macaddr</type>)</entry>
3920         <entry><type>macaddr</type></entry>
3921         <entry>set last 3 bytes to zero</entry>
3922         <entry><literal>trunc(macaddr '12:34:56:78:90:ab')</literal></entry>
3923         <entry><literal>12:34:56:00:00:00</literal></entry>
3924        </row>
3925       </tbody>
3926      </tgroup>
3927     </table>
3928
3929    <para>
3930     The function <function>trunc</function>(<type>macaddr</type>) returns a MAC
3931     address with the last 3 bytes set to 0.  This can be used to
3932     associate the remaining prefix with a manufacturer.  The directory
3933     <filename>contrib/mac</filename> in the source distribution contains some
3934     utilities to create and maintain such an association table.
3935    </para>
3936
3937    <para>
3938     The <type>macaddr</type> type also supports the standard relational
3939     operators (<literal>&gt;</literal>, <literal>&lt;=</literal>, etc.) for
3940     lexicographical ordering.
3941    </para>
3942
3943   </sect1>
3944
3945
3946  <sect1 id="functions-sequence">
3947   <title>Sequence-Manipulation Functions</title>
3948
3949   <indexterm>
3950    <primary>sequences</primary>
3951   </indexterm>
3952   <indexterm>
3953    <primary>nextval</primary>
3954   </indexterm>
3955   <indexterm>
3956    <primary>currval</primary>
3957   </indexterm>
3958   <indexterm>
3959    <primary>setval</primary>
3960   </indexterm>
3961
3962    <table>
3963     <title>Sequence Functions</title>
3964     <tgroup cols="3">
3965      <thead>
3966       <row><entry>Function</entry> <entry>Returns</entry> <entry>Description</entry></row>
3967      </thead>
3968
3969      <tbody>
3970       <row>
3971         <entry><function>nextval</function>(<type>text</type>)</entry>
3972         <entry><type>bigint</type></entry>
3973         <entry>Advance sequence and return new value</entry>
3974       </row>
3975       <row>
3976         <entry><function>currval</function>(<type>text</type>)</entry>
3977         <entry><type>bigint</type></entry>
3978         <entry>Return value most recently obtained with <function>nextval</function></entry>
3979       </row>
3980       <row>
3981         <entry><function>setval</function>(<type>text</type>,<type>bigint</type>)</entry>
3982         <entry><type>bigint</type></entry>
3983         <entry>Set sequence's current value</entry>
3984       </row>
3985       <row>
3986         <entry><function>setval</function>(<type>text</type>,<type>bigint</type>,<type>boolean</type>)</entry>
3987         <entry><type>bigint</type></entry>
3988         <entry>Set sequence's current value and <literal>is_called</literal> flag</entry>
3989       </row>
3990      </tbody>
3991     </tgroup>
3992    </table>
3993
3994   <para>
3995    This section describes <productname>PostgreSQL</productname>'s functions
3996    for operating on <firstterm>sequence objects</firstterm>.
3997    Sequence objects (also called sequence generators or
3998    just sequences) are special single-row tables created with
3999    <command>CREATE SEQUENCE</command>.  A sequence object is usually used to
4000    generate unique identifiers for rows of a table.  The sequence functions
4001    provide simple, multiuser-safe methods for obtaining successive
4002    sequence values from sequence objects.
4003   </para>
4004
4005   <para>
4006    For largely historical reasons, the sequence to be operated on by
4007    a sequence-function call is specified by a text-string argument.
4008    To achieve some compatibility with the handling of ordinary SQL
4009    names, the sequence functions convert their argument to lower case
4010    unless the string is double-quoted.  Thus
4011 <programlisting>
4012 nextval('foo')      <lineannotation>operates on sequence </><literal>foo</literal>
4013 nextval('FOO')      <lineannotation>operates on sequence </><literal>foo</literal>
4014 nextval('"Foo"')    <lineannotation>operates on sequence </><literal>Foo</literal>
4015 </programlisting>
4016    The sequence name can be schema-qualified if necessary:
4017 <programlisting>
4018 nextval('myschema.foo') <lineannotation>operates on </><literal>myschema.foo</literal>
4019 nextval('"myschema".foo') <lineannotation>same as above</lineannotation>
4020 nextval('foo')      <lineannotation>searches search path for
4021      </><literal>foo</literal>
4022 </programlisting>
4023    Of course, the text argument can be the result of an expression,
4024    not only a simple literal, which is occasionally useful.
4025   </para>
4026
4027   <para>
4028    The available sequence functions are:
4029
4030     <variablelist>
4031      <varlistentry>
4032       <term><function>nextval</function></term>
4033       <listitem>
4034        <para>
4035         Advance the sequence object to its next value and return that
4036         value.  This is done atomically: even if multiple server processes
4037         execute <function>nextval</function> concurrently, each will safely receive
4038         a distinct sequence value.
4039        </para>
4040       </listitem>
4041      </varlistentry>
4042
4043      <varlistentry>
4044       <term><function>currval</function></term>
4045       <listitem>
4046        <para>
4047         Return the value most recently obtained by <function>nextval</function>
4048         for this sequence in the current server process.  (An error is
4049         reported if <function>nextval</function> has never been called for this
4050         sequence in this process.)  Notice that because this is returning
4051         a process-local value, it gives a predictable answer even if other
4052         server processes are executing <function>nextval</function> meanwhile.
4053        </para>
4054       </listitem>
4055      </varlistentry>
4056
4057      <varlistentry>
4058       <term><function>setval</function></term>
4059       <listitem>
4060        <para>
4061         Reset the sequence object's counter value.  The two-parameter
4062         form sets the sequence's <literal>last_value</literal> field to the specified
4063         value and sets its <literal>is_called</literal> field to <literal>true</literal>,
4064         meaning that the next <function>nextval</function> will advance the sequence
4065         before returning a value.  In the three-parameter form,
4066         <literal>is_called</literal> may be set either <literal>true</literal> or
4067         <literal>false</literal>.  If it's set to <literal>false</literal>,
4068         the next <function>nextval</function> will return exactly the specified
4069         value, and sequence advancement commences with the following
4070         <function>nextval</function>.  For example,
4071        </para>
4072
4073        <informalexample>
4074 <screen>
4075 SELECT setval('foo', 42);           <lineannotation>Next nextval() will return 43</lineannotation>
4076 SELECT setval('foo', 42, true);     <lineannotation>Same as above</lineannotation>
4077 SELECT setval('foo', 42, false);    <lineannotation>Next nextval() will return 42</lineannotation>
4078 </screen>
4079        </informalexample>
4080
4081        <para>
4082         The result returned by <function>setval</function> is just the value of its
4083         second argument.
4084        </para>
4085       </listitem>
4086      </varlistentry>
4087     </variablelist>
4088   </para>
4089
4090   <important>
4091    <para>
4092     To avoid blocking of concurrent transactions that obtain numbers from the
4093     same sequence, a <function>nextval</function> operation is never rolled back;
4094     that is, once a value has been fetched it is considered used, even if the
4095     transaction that did the <function>nextval</function> later aborts.  This means
4096     that aborted transactions may leave unused <quote>holes</quote> in the
4097     sequence of assigned values.  <function>setval</function> operations are never
4098     rolled back, either.
4099    </para>
4100   </important>
4101
4102   <para>
4103    If a sequence object has been created with default parameters,
4104    <function>nextval()</function> calls on it will return successive values
4105    beginning with one.  Other behaviors can be obtained by using
4106    special parameters in the <command>CREATE SEQUENCE</command> command;
4107    see its command reference page for more information.
4108   </para>
4109
4110  </sect1>
4111
4112
4113  <sect1 id="functions-conditional">
4114   <title>Conditional Expressions</title>
4115
4116   <indexterm>
4117    <primary>case</primary>
4118   </indexterm>
4119
4120   <indexterm>
4121    <primary>conditionals</primary>
4122   </indexterm>
4123
4124   <para>
4125    This section describes the <acronym>SQL</acronym>-compliant conditional expressions
4126    available in <productname>PostgreSQL</productname>.
4127   </para>
4128
4129   <tip>
4130    <para>
4131     If your needs go beyond the capabilities of these conditional
4132     expressions you might want to consider writing a stored procedure
4133     in a more expressive programming language.
4134    </para>
4135   </tip>
4136
4137   <bridgehead renderas="sect2">CASE</bridgehead>
4138
4139 <synopsis>
4140 CASE WHEN <replaceable>condition</replaceable> THEN <replaceable>result</replaceable>
4141      <optional>WHEN ...</optional>
4142      <optional>ELSE <replaceable>result</replaceable></optional>
4143 END
4144 </synopsis>
4145
4146   <para>
4147    The <acronym>SQL</acronym> <token>CASE</token> expression is a
4148    generic conditional expression, similar to if/else statements in
4149    other languages.  <token>CASE</token> clauses can be used wherever
4150    an expression is valid.  <replaceable>condition</replaceable> is an
4151    expression that returns a <type>boolean</type> result.  If the result is true
4152    then the value of the <token>CASE</token> expression is
4153    <replaceable>result</replaceable>.  If the result is false any
4154    subsequent <token>WHEN</token> clauses are searched in the same
4155    manner.  If no <token>WHEN</token>
4156    <replaceable>condition</replaceable> is true then the value of the
4157    case expression is the <replaceable>result</replaceable> in the
4158    <token>ELSE</token> clause.  If the <token>ELSE</token> clause is
4159    omitted and no condition matches, the result is NULL.
4160   </para>
4161
4162   <informalexample>
4163    <para>
4164     An example:
4165 <screen>
4166 <prompt>=&gt;</prompt> <userinput>SELECT * FROM test;</userinput>
4167 <computeroutput>
4168  a
4169 ---
4170  1
4171  2
4172  3
4173 </computeroutput>
4174
4175 <prompt>=&gt;</prompt> <userinput>SELECT a,
4176           CASE WHEN a=1 THEN 'one'
4177                WHEN a=2 THEN 'two'
4178                ELSE 'other'
4179           END
4180     FROM test;</userinput>
4181 <computeroutput>
4182  a | case
4183 ---+-------
4184  1 | one
4185  2 | two
4186  3 | other
4187 </computeroutput>
4188 </screen>
4189    </para>
4190   </informalexample>
4191
4192   <para>
4193    The data types of all the <replaceable>result</replaceable>
4194    expressions must be coercible to a single output type.
4195    See <xref linkend="typeconv-union-case"> for more detail.
4196   </para>
4197
4198 <synopsis>
4199 CASE <replaceable>expression</replaceable>
4200     WHEN <replaceable>value</replaceable> THEN <replaceable>result</replaceable>
4201     <optional>WHEN ...</optional>
4202     <optional>ELSE <replaceable>result</replaceable></optional>
4203 END
4204 </synopsis>
4205
4206   <para>
4207    This <quote>simple</quote> <token>CASE</token> expression is a
4208    specialized variant of the general form above.  The
4209    <replaceable>expression</replaceable> is computed and compared to
4210    all the <replaceable>value</replaceable>s in the
4211    <token>WHEN</token> clauses until one is found that is equal.  If
4212    no match is found, the <replaceable>result</replaceable> in the
4213    <token>ELSE</token> clause (or NULL) is returned.  This is similar
4214    to the <function>switch</function> statement in C.
4215   </para>
4216
4217   <informalexample>
4218    <para>
4219     The example above can be written using the simple
4220     <token>CASE</token> syntax:
4221 <screen>
4222 <prompt>=&gt;</prompt> <userinput>SELECT a,
4223           CASE a WHEN 1 THEN 'one'
4224                  WHEN 2 THEN 'two'
4225                  ELSE 'other'
4226           END
4227     FROM test;</userinput>
4228 <computeroutput>
4229  a | case
4230 ---+-------
4231  1 | one
4232  2 | two
4233  3 | other
4234 </computeroutput>
4235 </screen>
4236     </para>
4237    </informalexample>
4238
4239    <bridgehead renderas="sect2">COALESCE</bridgehead>
4240
4241 <synopsis>
4242 <function>COALESCE</function>(<replaceable>value</replaceable><optional
4243      >, ...</optional>)
4244 </synopsis>
4245
4246   <para>
4247    The <function>COALESCE</function> function returns the first of its
4248    arguments that is not NULL.  This is often useful to substitute a
4249    default value for NULL values when data is retrieved for display,
4250    for example:
4251 <programlisting>
4252 SELECT COALESCE(description, short_description, '(none)') ...
4253 </programlisting>
4254   </para>
4255
4256  <bridgehead renderas="sect2">NULLIF</bridgehead>
4257
4258   <indexterm>
4259    <primary>nullif</primary>
4260   </indexterm>
4261
4262 <synopsis>
4263 <function>NULLIF</function>(<replaceable>value1</replaceable>,
4264     <replaceable>value2</replaceable>)
4265 </synopsis>
4266
4267   <para>
4268    The <function>NULLIF</function> function returns NULL if and only
4269    if <replaceable>value1</replaceable> and
4270    <replaceable>value2</replaceable> are equal.  Otherwise it returns
4271    <replaceable>value1</replaceable>.  This can be used to perform the
4272    inverse operation of the <function>COALESCE</function> example
4273    given above:
4274 <programlisting>
4275 SELECT NULLIF(value, '(none)') ...
4276 </programlisting>
4277   </para>
4278
4279   <tip>
4280    <para>
4281     <function>COALESCE</function> and <function>NULLIF</function> are
4282     just shorthand for <token>CASE</token> expressions.  They are actually
4283     converted into <token>CASE</token> expressions at a very early stage
4284     of processing, and subsequent processing thinks it is dealing with
4285     <token>CASE</token>.  Thus an incorrect <function>COALESCE</function> or
4286     <function>NULLIF</function> usage may draw an error message that
4287     refers to <token>CASE</token>.
4288    </para>
4289   </tip>
4290
4291  </sect1>
4292
4293
4294   <sect1 id="functions-misc">
4295    <title>Miscellaneous Functions</title>
4296
4297    <table>
4298     <title>Session Information Functions</title>
4299     <tgroup cols="3">
4300      <thead>
4301       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4302      </thead>
4303
4304      <tbody>
4305       <row>
4306        <entry><function>current_user</function></entry>
4307        <entry><type>name</type></entry>
4308        <entry>user name of current execution context</entry>
4309       </row>
4310       <row>
4311        <entry><function>session_user</function></entry>
4312        <entry><type>name</type></entry>
4313        <entry>session user name</entry>
4314       </row>
4315       <row>
4316        <entry><function>user</function></entry>
4317        <entry><type>name</type></entry>
4318        <entry>equivalent to <function>current_user</function></entry>
4319       </row>
4320       <row>
4321        <entry><function>current_schema()</function></entry>
4322        <entry><type>name</type></entry>
4323        <entry>name of current schema</entry>
4324       </row>
4325       <row>
4326        <entry><function>current_schemas()</function></entry>
4327        <entry><type>name[]</type></entry>
4328        <entry>names of schemas in search path</entry>
4329       </row>
4330      </tbody>
4331     </tgroup>
4332    </table>
4333
4334    <indexterm zone="functions-misc">
4335     <primary>user</primary>
4336     <secondary>current</secondary>
4337    </indexterm>
4338
4339    <indexterm zone="functions-misc">
4340     <primary>schema</primary>
4341     <secondary>current</secondary>
4342    </indexterm>
4343
4344    <indexterm zone="functions-misc">
4345     <primary>search path</primary>
4346     <secondary>current</secondary>
4347    </indexterm>
4348
4349    <para>
4350     The <function>session_user</function> is the user that initiated a
4351     database connection; it is fixed for the duration of that
4352     connection. The <function>current_user</function> is the user identifier
4353     that is applicable for permission checking. Normally, it is equal
4354     to the session user, but it changes during the execution of
4355     functions with the attribute <literal>SECURITY DEFINER</literal>.
4356     In Unix parlance, the session user is the <quote>real user</quote> and
4357     the current user is the <quote>effective user</quote>.
4358    </para>
4359
4360    <note>
4361     <para>
4362      <function>current_user</function>, <function>session_user</function>, and
4363      <function>user</function> have special syntactic status in <acronym>SQL</acronym>:
4364      they must be called without trailing parentheses.
4365     </para>
4366    </note>
4367
4368    <note>
4369     <title>Deprecated</title>
4370     <para>
4371      The function <function>getpgusername()</function> is an obsolete equivalent
4372      of <function>current_user</function>.
4373     </para>
4374    </note>
4375
4376    <para>
4377     <function>current_schema</function> returns the name of the schema that is
4378     at the front of the search path (or NULL if the search path is
4379     empty).  This is the schema that will be used for any tables or
4380     other named objects that are created without specifying a target schema.
4381     <function>current_schemas</function> returns an array of the names of all
4382     schemas presently in the search path.  Note that these functions show
4383     only schemas that are explicitly part of the path; when a system schema
4384     is being searched implicitly, it is not listed.
4385    </para>
4386
4387    <table>
4388     <title>System Information Functions</title>
4389     <tgroup cols="3">
4390      <thead>
4391       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4392      </thead>
4393
4394      <tbody>
4395       <row>
4396        <entry><function>version</function></entry>
4397        <entry><type>text</type></entry>
4398        <entry>PostgreSQL version information</entry>
4399       </row>
4400      </tbody>
4401     </tgroup>
4402    </table>
4403
4404    <indexterm zone="functions-misc">
4405     <primary>version</primary>
4406    </indexterm>
4407
4408    <para>
4409     <function>version()</function> returns a string describing the PostgreSQL
4410     server's version.
4411    </para>
4412
4413    <table>
4414     <title>Access Privilege Inquiry Functions</title>
4415     <tgroup cols="3">
4416      <thead>
4417       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4418      </thead>
4419
4420      <tbody>
4421       <row>
4422        <entry><function>has_table_privilege</function>(<parameter>user</parameter>,
4423                                   <parameter>table</parameter>,
4424                                   <parameter>access</parameter>)
4425        </entry>
4426        <entry><type>boolean</type></entry>
4427        <entry>does user have access to table</entry>
4428       </row>
4429       <row>
4430        <entry><function>has_table_privilege</function>(<parameter>table</parameter>,
4431                                   <parameter>access</parameter>)
4432        </entry>
4433        <entry><type>boolean</type></entry>
4434        <entry>does current user have access to table</entry>
4435       </row>
4436      </tbody>
4437     </tgroup>
4438    </table>
4439
4440    <indexterm zone="functions-misc">
4441     <primary>has_table_privilege</primary>
4442    </indexterm>
4443
4444    <para>
4445     <function>has_table_privilege</function> determines whether a user
4446     can access a table in a particular way.  The user can be
4447     specified by name or by ID
4448     (<classname>pg_user</classname>.<structfield>usesysid</structfield>), or if the argument is
4449     omitted
4450     <function>current_user</function> is assumed.  The table can be specified
4451     by name or by OID.  (Thus, there are actually six variants of
4452     <function>has_table_privilege</function>, which can be distinguished by
4453     the number and types of their arguments.)  When specifying by name,
4454     the name can be schema-qualified if necessary.
4455     The desired access type
4456     is specified by a text string, which must evaluate to one of the
4457     values <literal>SELECT</literal>, <literal>INSERT</literal>, <literal>UPDATE</literal>,
4458     <literal>DELETE</literal>, <literal>RULE</literal>, <literal>REFERENCES</literal>, or
4459     <literal>TRIGGER</literal>.  (Case of the string is not significant, however.)
4460     An example is:
4461 <programlisting>
4462 SELECT has_table_privilege('myschema.mytable', 'select');
4463 </programlisting>
4464    </para>
4465
4466    <table>
4467     <title>Catalog Information Functions</title>
4468     <tgroup cols="3">
4469      <thead>
4470       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4471      </thead>
4472
4473      <tbody>
4474       <row>
4475        <entry><function>pg_get_viewdef</function>(<parameter>viewname</parameter>)</entry>
4476        <entry><type>text</type></entry>
4477        <entry>Get CREATE VIEW command for view</entry>
4478       </row>
4479       <row>
4480        <entry><function>pg_get_viewdef</function>(<parameter>viewOID</parameter>)</entry>
4481        <entry><type>text</type></entry>
4482        <entry>Get CREATE VIEW command for view</entry>
4483       </row>
4484       <row>
4485        <entry><function>pg_get_ruledef</function>(<parameter>ruleOID</parameter>)</entry>
4486        <entry><type>text</type></entry>
4487        <entry>Get CREATE RULE command for rule</entry>
4488       </row>
4489       <row>
4490        <entry><function>pg_get_indexdef</function>(<parameter>indexOID</parameter>)</entry>
4491        <entry><type>text</type></entry>
4492        <entry>Get CREATE INDEX command for index</entry>
4493       </row>
4494       <row>
4495        <entry><function>pg_get_userbyid</function>(<parameter>userid</parameter>)</entry>
4496        <entry><type>name</type></entry>
4497        <entry>Get user name given ID</entry>
4498       </row>
4499      </tbody>
4500     </tgroup>
4501    </table>
4502
4503    <indexterm zone="functions-misc">
4504     <primary>pg_get_viewdef</primary>
4505    </indexterm>
4506
4507    <indexterm zone="functions-misc">
4508     <primary>pg_get_ruledef</primary>
4509    </indexterm>
4510
4511    <indexterm zone="functions-misc">
4512     <primary>pg_get_indexdef</primary>
4513    </indexterm>
4514
4515    <indexterm zone="functions-misc">
4516     <primary>pg_get_userbyid</primary>
4517    </indexterm>
4518
4519    <para>
4520     These functions extract information from the system catalogs.
4521     <function>pg_get_viewdef()</function>, <function>pg_get_ruledef()</function>, and
4522     <function>pg_get_indexdef()</function> respectively reconstruct the creating
4523     command for a view, rule, or index.  (Note that this is a decompiled
4524     reconstruction, not the verbatim text of the command.)
4525     <function>pg_get_userbyid()</function> extracts a user's name given a
4526     <structfield>usesysid</structfield> value.
4527    </para>
4528
4529    <table>
4530     <title>Comment Information Functions</title>
4531     <tgroup cols="3">
4532      <thead>
4533       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4534      </thead>
4535
4536      <tbody>
4537       <row>
4538        <entry><function>obj_description</function>(<parameter>objectOID</parameter>, <parameter>tablename</parameter>)</entry>
4539        <entry><type>text</type></entry>
4540        <entry>Get comment for a database object</entry>
4541       </row>
4542       <row>
4543        <entry><function>obj_description</function>(<parameter>objectOID</parameter>)</entry>
4544        <entry><type>text</type></entry>
4545        <entry>Get comment for a database object (<emphasis>deprecated</emphasis>)</entry>
4546       </row>
4547       <row>
4548        <entry><function>col_description</function>(<parameter>tableOID</parameter>, <parameter>columnnumber</parameter>)</entry>
4549        <entry><type>text</type></entry>
4550        <entry>Get comment for a table column</entry>
4551       </row>
4552      </tbody>
4553     </tgroup>
4554    </table>
4555
4556    <indexterm zone="functions-misc">
4557     <primary>obj_description</primary>
4558    </indexterm>
4559
4560    <indexterm zone="functions-misc">
4561     <primary>col_description</primary>
4562    </indexterm>
4563
4564    <para>
4565     These functions extract comments previously stored with the
4566     <command>COMMENT</command> command.  <literal>NULL</literal> is returned if
4567     no comment can be found matching the specified parameters.
4568    </para>
4569
4570    <para>
4571     The two-parameter form of <function>obj_description()</function> returns the
4572     comment for a database object specified by its OID and the name of the
4573     containing system catalog.  For example,
4574     <literal>obj_description(123456,'pg_class')</literal>
4575     would retrieve the comment for a table with OID 123456.
4576     The one-parameter form of <function>obj_description()</function> requires only
4577     the object OID.  It is now deprecated since there is no guarantee that
4578     OIDs are unique across different system catalogs; therefore, the wrong
4579     comment could be returned.
4580    </para>
4581
4582    <para>
4583     <function>col_description()</function> returns the comment for a table column,
4584     which is specified by the OID of its table and its column number.
4585     <function>obj_description()</function> cannot be used for table columns since
4586     columns do not have OIDs of their own.
4587    </para>
4588
4589   </sect1>
4590
4591
4592  <sect1 id="functions-aggregate">
4593   <title>Aggregate Functions</title>
4594
4595   <note>
4596    <title>Author</title>
4597    <para>
4598     Written by Isaac Wilcox <email>isaac@azartmedia.com</email> on 2000-06-16
4599    </para>
4600   </note>
4601
4602   <para>
4603    <firstterm>Aggregate functions</firstterm> compute a single result
4604    value from a set of input values.  The special syntax
4605    considerations for aggregate functions are explained in <xref
4606                                                                  linkend="syntax-aggregates">.  Consult the <citetitle>PostgreSQL
4607    Tutorial</citetitle> for additional introductory information.
4608   </para>
4609
4610   <table tocentry="1">
4611    <title>Aggregate Functions</title>
4612
4613    <tgroup cols="3">
4614     <thead>
4615      <row>
4616       <entry>Function</entry>
4617       <entry>Description</entry>
4618       <entry>Notes</entry>
4619      </row>
4620     </thead>
4621
4622     <tbody>
4623      <row>
4624       <entry>avg(<replaceable class="parameter">expression</replaceable>)</entry>
4625       <entry>the average (arithmetic mean) of all input values</entry>
4626       <entry>
4627        <indexterm>
4628         <primary>average</primary>
4629         <secondary>function</secondary>
4630        </indexterm>
4631        Finding the average value is available on the following data
4632        types: <type>smallint</type>, <type>integer</type>,
4633        <type>bigint</type>, <type>real</type>, <type>double
4634        precision</type>, <type>numeric</type>, <type>interval</type>.
4635        The result is of type <type>numeric</type> for any integer type
4636        input, <type>double precision</type> for floating-point input,
4637        otherwise the same as the input data type.
4638       </entry>
4639      </row>
4640
4641      <row>
4642       <entry><function>count</function>(*)</entry>
4643       <entry>number of input values</entry>
4644       <entry>The return value is of type <type>bigint</type>.</entry>
4645      </row>
4646
4647      <row>
4648       <entry><function>count</function>(<replaceable class="parameter">expression</replaceable>)</entry>
4649       <entry>
4650        Counts the input values for which the value of <replaceable
4651                                                                    class="parameter">expression</replaceable> is not NULL.
4652       </entry>
4653       <entry>The return value is of type <type>bigint</type>.</entry>
4654      </row>
4655
4656      <row>
4657       <entry><function>max</function>(<replaceable class="parameter">expression</replaceable>)</entry>
4658       <entry>the maximum value of <replaceable class="parameter">expression</replaceable> across all input values</entry>
4659       <entry>
4660        Available for all numeric, string, and date/time types.  The
4661        result has the same type as the input expression.
4662       </entry>
4663      </row>
4664
4665      <row>
4666       <entry><function>min</function>(<replaceable class="parameter">expression</replaceable>)</entry>
4667       <entry>the minimum value of <replaceable class="parameter">expression</replaceable> across all input values</entry>
4668       <entry>
4669        Available for all numeric, string, and date/time types.  The
4670        result has the same type as the input expression.
4671       </entry>
4672      </row>
4673
4674      <row>
4675       <entry><function>stddev</function>(<replaceable
4676                                                       class="parameter">expression</replaceable>)</entry>
4677       <entry>the sample standard deviation of the input values</entry>
4678       <entry>
4679        <indexterm>
4680         <primary>standard deviation</primary>
4681        </indexterm>
4682        Finding the standard deviation is available on the following
4683        data types: <type>smallint</type>, <type>integer</type>,
4684        <type>bigint</type>, <type>real</type>, <type>double
4685        precision</type>, <type>numeric</type>.  The result is of type
4686        <type>double precision</type> for floating-point input,
4687        otherwise <type>numeric</type>.
4688       </entry>
4689      </row>
4690
4691      <row>
4692       <entry><function>sum</function>(<replaceable class="parameter">expression</replaceable>)</entry>
4693       <entry>sum of <replaceable class="parameter">expression</replaceable> across all input values</entry>
4694       <entry>
4695        Summation is available on the following data types:
4696        <type>smallint</type>, <type>integer</type>,
4697        <type>bigint</type>, <type>real</type>, <type>double
4698        precision</type>, <type>numeric</type>, <type>interval</type>.
4699        The result is of type <type>bigint</type> for <type>smallint</type>
4700        or <type>integer</type> input, <type>numeric</type> for
4701        <type>bigint</type> 
4702        input, <type>double precision</type> for floating-point input,
4703        otherwise the same as the input data type.
4704       </entry>
4705      </row>
4706
4707      <row>
4708       <entry><function>variance</function>(<replaceable
4709                                                         class="parameter">expression</replaceable>)</entry>
4710       <entry>the sample variance of the input values</entry>
4711       <entry>
4712        <indexterm>
4713         <primary>variance</primary>
4714        </indexterm>
4715        The variance is the square of the standard deviation.  The
4716        supported data types and result types are the same as for
4717        standard deviation.
4718       </entry>
4719      </row>
4720
4721     </tbody>
4722    </tgroup>
4723   </table>
4724
4725   <para>
4726    It should be noted that except for <function>COUNT</function>,
4727    these functions return NULL when no rows are selected.  In
4728    particular, <function>SUM</function> of no rows returns NULL, not
4729    zero as one might expect.  <function>COALESCE</function> may be
4730    used to substitute zero for NULL when necessary.
4731   </para>
4732
4733  </sect1>
4734
4735
4736  <sect1 id="functions-subquery">
4737   <title>Subquery Expressions</title>
4738
4739   <indexterm>
4740    <primary>exists</primary>
4741   </indexterm>
4742
4743   <indexterm>
4744    <primary>in</primary>
4745   </indexterm>
4746
4747   <indexterm>
4748    <primary>not in</primary>
4749   </indexterm>
4750
4751   <indexterm>
4752    <primary>any</primary>
4753   </indexterm>
4754
4755   <indexterm>
4756    <primary>all</primary>
4757   </indexterm>
4758
4759   <indexterm>
4760    <primary>some</primary>
4761   </indexterm>
4762
4763   <indexterm>
4764    <primary>subqueries</primary>
4765   </indexterm>
4766
4767   <para>
4768    This section describes the <acronym>SQL</acronym>-compliant subquery
4769    expressions available in <productname>PostgreSQL</productname>.
4770    All of the expression forms documented in this section return
4771    Boolean (true/false) results.
4772   </para>
4773
4774   <bridgehead renderas="sect2">EXISTS</bridgehead>
4775
4776 <synopsis>
4777 EXISTS ( <replaceable>subquery</replaceable> )
4778 </synopsis>
4779
4780   <para>
4781    The argument of <token>EXISTS</token> is an arbitrary SELECT statement,
4782    or <firstterm>subquery</firstterm>.  The
4783    subquery is evaluated to determine whether it returns any rows.
4784    If it returns at least one row, the result of <token>EXISTS</token> is
4785    TRUE; if the subquery returns no rows, the result of <token>EXISTS</token> 
4786    is FALSE.
4787   </para>
4788
4789   <para>
4790    The subquery can refer to variables from the surrounding query,
4791    which will act as constants during any one evaluation of the subquery.
4792   </para>
4793
4794   <para>
4795    The subquery will generally only be executed far enough to determine
4796    whether at least one row is returned, not all the way to completion.
4797    It is unwise to write a subquery that has any side-effects (such as
4798    calling sequence functions); whether the side-effects occur or not
4799    may be difficult to predict.
4800   </para>
4801
4802   <para>
4803    Since the result depends only on whether any rows are returned,
4804    and not on the contents of those rows, the output list of the
4805    subquery is normally uninteresting.  A common coding convention is
4806    to write all EXISTS tests in the form
4807    <literal>EXISTS(SELECT 1 WHERE ...)</literal>.  There are exceptions to
4808    this rule however, such as subqueries that use <token>INTERSECT</token>.
4809   </para>
4810
4811   <para>
4812    This simple example is like an inner join on col2, but it produces at
4813    most one output row for each tab1 row, even if there are multiple matching
4814    tab2 rows:
4815 <screen>
4816 SELECT col1 FROM tab1
4817     WHERE EXISTS(SELECT 1 FROM tab2 WHERE col2 = tab1.col2);
4818 </screen>
4819   </para>
4820
4821    <bridgehead renderas="sect2">IN (scalar form)</bridgehead>
4822
4823 <synopsis>
4824 <replaceable>expression</replaceable> IN
4825  <replaceable>ble>value</replaceable><optional>, ...</optional>)
4826 </synopsis>
4827
4828   <para>
4829    The right-hand side of this form of <token>IN</token> is a parenthesized list
4830    of scalar expressions.  The result is TRUE if the left-hand expression's
4831    result is equal to any of the right-hand expressions.  This is a shorthand
4832    notation for
4833
4834 <synopsis>
4835 <replaceable>expression</replaceable> = <replaceable>value1</replaceable>
4836 OR
4837 <replaceable>expression</replaceable> = <replaceable>value2</replaceable>
4838 OR
4839 ...
4840 </synopsis>
4841
4842    Note that if the left-hand expression yields NULL, or if there are
4843    no equal right-hand values and at least one right-hand expression yields
4844    NULL, the result of the <token>IN</token> construct will be NULL, not FALSE.
4845    This is in accordance with SQL's normal rules for Boolean combinations
4846    of NULL values.
4847   </para>
4848
4849   <note>
4850   <para>
4851    This form of <token>IN</token> is not truly a subquery expression, but it
4852    seems best to document it in the same place as subquery <token>IN</token>.
4853   </para>
4854   </note>
4855
4856    <bridgehead renderas="sect2">IN (subquery form)</bridgehead>
4857
4858 <synopsis>
4859 <replaceable>expression</replaceable> IN (<replaceable>subquery</replaceable>)
4860 </synopsis>
4861
4862   <para>
4863    The right-hand side of this form of <token>IN</token> is a parenthesized
4864    subquery, which must return exactly one column.  The left-hand expression
4865    is evaluated and compared to each row of the subquery result.
4866    The result of <token>IN</token> is TRUE if any equal subquery row is found.
4867    The result is FALSE if no equal row is found (including the special
4868    case where the subquery returns no rows).
4869   </para>
4870
4871   <para>
4872    Note that if the left-hand expression yields NULL, or if there are
4873    no equal right-hand values and at least one right-hand row yields
4874    NULL, the result of the <token>IN</token> construct will be NULL, not FALSE.
4875    This is in accordance with SQL's normal rules for Boolean combinations
4876    of NULL values.
4877   </para>
4878
4879   <para>
4880    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
4881    be evaluated completely.
4882   </para>
4883
4884 <synopsis>
4885 (<replaceable>expression</replaceable>,
4886 <replaceable>ble>expres</replaceable><optional>nal>,</optional>nal>)
4887     IN (<replaceable>subquery</replaceable>)
4888 </synopsis>
4889
4890   <para>
4891    The right-hand side of this form of <token>IN</token> is a parenthesized
4892    subquery, which must return exactly as many columns as there are
4893    expressions in the left-hand list.  The left-hand expressions are
4894    evaluated and compared row-wise to each row of the subquery result.
4895    The result of <token>IN</token> is TRUE if any equal subquery row is found.
4896    The result is FALSE if no equal row is found (including the special
4897    case where the subquery returns no rows).
4898   </para>
4899
4900   <para>
4901    As usual, NULLs in the expressions or subquery rows are combined per
4902    the normal rules of SQL Boolean expressions.  Two rows are considered
4903    equal if all their corresponding members are non-null and equal; the rows
4904    are unequal if any corresponding members are non-null and unequal;
4905    otherwise the result of that row comparison is unknown (NULL).
4906    If all the row results are either unequal or NULL, with at least one NULL,
4907    then the result of <token>IN</token> is NULL.
4908   </para>
4909
4910    <bridgehead renderas="sect2">NOT IN (scalar form)</bridgehead>
4911
4912 <synopsis>
4913 <replaceable>expression</replaceable> NOT IN
4914  <replaceable>ble>value</replaceable><optional>, ...</optional>)
4915 </synopsis>
4916
4917   <para>
4918    The right-hand side of this form of <token>NOT IN</token> is a parenthesized list
4919    of scalar expressions.  The result is TRUE if the left-hand expression's
4920    result is unequal to all of the right-hand expressions.  This is a shorthand
4921    notation for
4922
4923 <synopsis>
4924 <replaceable>expression</replaceable> &lt;&gt; <replaceable>value1</replaceable>
4925 AND
4926 <replaceable>expression</replaceable> &lt;&gt; <replaceable>value2</replaceable>
4927 AND
4928 ...
4929 </synopsis>
4930
4931    Note that if the left-hand expression yields NULL, or if there are
4932    no equal right-hand values and at least one right-hand expression yields
4933    NULL, the result of the <token>NOT IN</token> construct will be NULL, not TRUE
4934    as one might naively expect.
4935    This is in accordance with SQL's normal rules for Boolean combinations
4936    of NULL values.
4937   </para>
4938
4939   <tip>
4940   <para>
4941    <literal>x NOT IN y</literal> is equivalent to <literal>NOT (x IN y)</literal> in all
4942    cases.  However, NULLs are much more likely to trip up the novice when
4943    working with <token>NOT IN</token> than when working with <token>IN</token>.
4944    It's best to express your condition positively if possible.
4945   </para>
4946   </tip>
4947
4948    <bridgehead renderas="sect2">NOT IN (subquery form)</bridgehead>
4949
4950 <synopsis>
4951 <replaceable>expression</replaceable> NOT IN (<replaceable>subquery</replaceable>)
4952 </synopsis>
4953
4954   <para>
4955    The right-hand side of this form of <token>NOT IN</token> is a parenthesized
4956    subquery, which must return exactly one column.  The left-hand expression
4957    is evaluated and compared to each row of the subquery result.
4958    The result of <token>NOT IN</token> is TRUE if only unequal subquery rows
4959    are found (including the special case where the subquery returns no rows).
4960    The result is FALSE if any equal row is found.
4961   </para>
4962
4963   <para>
4964    Note that if the left-hand expression yields NULL, or if there are
4965    no equal right-hand values and at least one right-hand row yields
4966    NULL, the result of the <token>NOT IN</token> construct will be NULL, not TRUE.
4967    This is in accordance with SQL's normal rules for Boolean combinations
4968    of NULL values.
4969   </para>
4970
4971   <para>
4972    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
4973    be evaluated completely.
4974   </para>
4975
4976 <synopsis>
4977 (<replaceable>expression</replaceable>,
4978 <replaceable>ble>expres</replaceable><optional>nal>,</optional>nal>)
4979     NOT IN (<replaceable>subquery</replaceable>)
4980 </synopsis>
4981
4982   <para>
4983    The right-hand side of this form of <token>NOT IN</token> is a parenthesized
4984    subquery, which must return exactly as many columns as there are
4985    expressions in the left-hand list.  The left-hand expressions are
4986    evaluated and compared row-wise to each row of the subquery result.
4987    The result of <token>NOT IN</token> is TRUE if only unequal subquery rows
4988    are found (including the special case where the subquery returns no rows).
4989    The result is FALSE if any equal row is found.
4990   </para>
4991
4992   <para>
4993    As usual, NULLs in the expressions or subquery rows are combined per
4994    the normal rules of SQL Boolean expressions.  Two rows are considered
4995    equal if all their corresponding members are non-null and equal; the rows
4996    are unequal if any corresponding members are non-null and unequal;
4997    otherwise the result of that row comparison is unknown (NULL).
4998    If all the row results are either unequal or NULL, with at least one NULL,
4999    then the result of <token>NOT IN</token> is NULL.
5000   </para>
5001
5002    <bridgehead renderas="sect2">ANY</bridgehead>
5003
5004 <synopsis>
5005 <replaceable>expression</replaceable>
5006 <replaceable>ble>oper</replaceable>ble> ANY (<replaceable>subquery</replaceable>)
5007 <replaceable>expression</replaceable>
5008 <replaceable>ble>oper</replaceable>ble> SOME (<replaceable>subquery</replaceable>)
5009 </synopsis>
5010
5011   <para>
5012    The right-hand side of this form of <token>ANY</token> is a parenthesized
5013    subquery, which must return exactly one column.  The left-hand expression
5014    is evaluated and compared to each row of the subquery result using the
5015    given <replaceable>operator</replaceable>, which must yield a Boolean
5016    result.
5017    The result of <token>ANY</token> is TRUE if any true result is obtained.
5018    The result is FALSE if no true result is found (including the special
5019    case where the subquery returns no rows).
5020   </para>
5021
5022   <para>
5023    <token>SOME</token> is a synonym for <token>ANY</token>.
5024    <token>IN</token> is equivalent to <literal>= ANY</literal>.
5025   </para>
5026
5027   <para>
5028    Note that if there are no successes and at least one right-hand row yields
5029    NULL for the operator's result, the result of the <token>ANY</token> construct
5030    will be NULL, not FALSE.
5031    This is in accordance with SQL's normal rules for Boolean combinations
5032    of NULL values.
5033   </para>
5034
5035   <para>
5036    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
5037    be evaluated completely.
5038   </para>
5039
5040 <synopsis>
5041 (<replaceable>expression</replaceable>,
5042 <replaceable>ble>expres</replaceable><optional>nal>,</optional>optiona<replaceable>aceable></replaceable>aceable> ANY (<replaceable>subquery</replaceable>)
5043 (<replaceable>expression</replaceable>,
5044 <replaceable>ble>expres</replaceable><optional>nal>,</optional>optiona<replaceable>aceable></replaceable>aceable> SOME (<replaceable>subquery</replaceable>)
5045 </synopsis>
5046
5047   <para>
5048    The right-hand side of this form of <token>ANY</token> is a parenthesized
5049    subquery, which must return exactly as many columns as there are
5050    expressions in the left-hand list.  The left-hand expressions are
5051    evaluated and compared row-wise to each row of the subquery result,
5052    using the given <replaceable>operator</replaceable>.  Presently,
5053    only <literal>=</literal> and <literal>&lt;&gt;</literal> operators are allowed
5054    in row-wise <token>ANY</token> queries.
5055    The result of <token>ANY</token> is TRUE if any equal or unequal row is
5056    found, respectively.
5057    The result is FALSE if no such row is found (including the special
5058    case where the subquery returns no rows).
5059   </para>
5060
5061   <para>
5062    As usual, NULLs in the expressions or subquery rows are combined per
5063    the normal rules of SQL Boolean expressions.  Two rows are considered
5064    equal if all their corresponding members are non-null and equal; the rows
5065    are unequal if any corresponding members are non-null and unequal;
5066    otherwise the result of that row comparison is unknown (NULL).
5067    If there is at least one NULL row result, then the result of <token>ANY</token>
5068    cannot be FALSE; it will be TRUE or NULL. 
5069   </para>
5070
5071    <bridgehead renderas="sect2">ALL</bridgehead>
5072
5073 <synopsis>
5074 <replaceable>expression</replaceable>
5075 <replaceable>ble>oper</replaceable>ble> ALL (<replaceable>subquery</replaceable>)
5076 </synopsis>
5077
5078   <para>
5079    The right-hand side of this form of <token>ALL</token> is a parenthesized
5080    subquery, which must return exactly one column.  The left-hand expression
5081    is evaluated and compared to each row of the subquery result using the
5082    given <replaceable>operator</replaceable>, which must yield a Boolean
5083    result.
5084    The result of <token>ALL</token> is TRUE if all rows yield TRUE
5085    (including the special case where the subquery returns no rows).
5086    The result is FALSE if any false result is found.
5087   </para>
5088
5089   <para>
5090    <token>NOT IN</token> is equivalent to <literal>&lt;&gt; ALL</literal>.
5091   </para>
5092
5093   <para>
5094    Note that if there are no failures but at least one right-hand row yields
5095    NULL for the operator's result, the result of the <token>ALL</token> construct
5096    will be NULL, not TRUE.
5097    This is in accordance with SQL's normal rules for Boolean combinations
5098    of NULL values.
5099   </para>
5100
5101   <para>
5102    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
5103    be evaluated completely.
5104   </para>
5105
5106    <synopsis>
5107 (<replaceable>expression</replaceable>, <replaceable>expression</replaceable><optional>, ...</optional>) <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
5108    </synopsis>
5109
5110   <para>
5111    The right-hand side of this form of <token>ALL</token> is a parenthesized
5112    subquery, which must return exactly as many columns as there are
5113    expressions in the left-hand list.  The left-hand expressions are
5114    evaluated and compared row-wise to each row of the subquery result,
5115    using the given <replaceable>operator</replaceable>.  Presently,
5116    only <literal>=</literal> and <literal>&lt;&gt;</literal> operators are allowed
5117    in row-wise <token>ALL</token> queries.
5118    The result of <token>ALL</token> is TRUE if all subquery rows are equal
5119    or unequal, respectively (including the special
5120    case where the subquery returns no rows).
5121    The result is FALSE if any row is found to be unequal or equal,
5122    respectively.
5123   </para>
5124
5125   <para>
5126    As usual, NULLs in the expressions or subquery rows are combined per
5127    the normal rules of SQL Boolean expressions.  Two rows are considered
5128    equal if all their corresponding members are non-null and equal; the rows
5129    are unequal if any corresponding members are non-null and unequal;
5130    otherwise the result of that row comparison is unknown (NULL).
5131    If there is at least one NULL row result, then the result of <token>ALL</token>
5132    cannot be TRUE; it will be FALSE or NULL. 
5133   </para>
5134
5135    <bridgehead renderas="sect2">Row-wise comparison</bridgehead>
5136
5137    <synopsis>
5138 (<replaceable>expression</replaceable>, <replaceable>expression</replaceable><optional>, ...</optional>) <replaceable>operator</replaceable> (<replaceable>subquery</replaceable>)
5139 (<replaceable>expression</replaceable>, <replaceable>expression</replaceable><optional>, ...</optional>) <replaceable>operator</replaceable> (<replaceable>expression</replaceable> <replaceable>expression</replaceable><optional>, ...</optional>)
5140    </synopsis>
5141
5142   <para>
5143    The left-hand side is a list of scalar expressions.  The right-hand side
5144    can be either a list of scalar expressions of the same length, or a
5145    parenthesized subquery, which must return exactly as many columns as there
5146    are expressions on the left-hand side.  Furthermore, the subquery cannot
5147    return more than one row.  (If it returns zero rows, the result is taken to
5148    be NULL.)  The left-hand side is evaluated and compared row-wise to the
5149    single subquery result row, or to the right-hand expression list.
5150    Presently, only <literal>=</literal> and <literal>&lt;&gt;</literal> operators are allowed
5151    in row-wise comparisons.
5152    The result is TRUE if the two rows are equal or unequal, respectively.
5153   </para>
5154
5155   <para>
5156    As usual, NULLs in the expressions or subquery rows are combined per
5157    the normal rules of SQL Boolean expressions.  Two rows are considered
5158    equal if all their corresponding members are non-null and equal; the rows
5159    are unequal if any corresponding members are non-null and unequal;
5160    otherwise the result of the row comparison is unknown (NULL).
5161   </para>
5162
5163  </sect1>
5164
5165 </chapter>
5166
5167 <!-- Keep this comment at the end of the file
5168 Local variables:
5169 mode:sgml
5170 sgml-omittag:nil
5171 sgml-shorttag:t
5172 sgml-minimize-attributes:nil
5173 sgml-always-quote-attributes:t
5174 sgml-indent-step:1
5175 sgml-indent-data:t
5176 sgml-parent-document:nil
5177 sgml-default-dtd-file:"./reference.ced"
5178 sgml-exposed-tags:nil
5179 sgml-local-catalogs:("/usr/lib/sgml/catalog")
5180 sgml-local-ecat-files:nil
5181 End:
5182 -->