]> granicus.if.org Git - postgresql/blob - doc/src/sgml/func.sgml
1e7e5bcde61eb815ea6b3a280919322cfca372eb
[postgresql] / doc / src / sgml / func.sgml
1 <!--
2 $Header: /cvsroot/pgsql/doc/src/sgml/func.sgml,v 1.101 2002/06/11 16:00:17 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</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</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>now</function>()</entry>
2795         <entry><type>timestamp</type></entry>
2796         <entry>Current date and time (equivalent to
2797          <function>current_timestamp</function>); see <link
2798                                                      linkend="functions-datetime-current">below</link>
2799         </entry>
2800         <entry></entry>
2801         <entry></entry>
2802        </row>
2803
2804        <row>
2805         <entry><function>timeofday()</function></entry>
2806         <entry><type>text</type></entry>
2807         <entry>Current date and time; see <link
2808                                          linkend="functions-datetime-current">below</link>
2809         </entry>
2810         <entry><literal>timeofday()</literal></entry>
2811         <entry><literal>Wed Feb 21 17:01:13.000126 2001 EST</literal></entry>
2812        </row>
2813
2814       </tbody>
2815      </tgroup>
2816     </table>
2817    </para>
2818
2819   <sect2 id="functions-datetime-extract">
2820    <title><function>EXTRACT</function>, <function>date_part</function></title>
2821
2822 <synopsis>
2823 EXTRACT (<replaceable>field</replaceable> FROM <replaceable>source</replaceable>)
2824 </synopsis>
2825
2826    <para>
2827     The <function>extract</function> function retrieves sub-fields
2828     from date/time values, such as year or hour.
2829     <replaceable>source</replaceable> is a value expression that
2830     evaluates to type <type>timestamp</type> or <type>interval</type>.
2831     (Expressions of type <type>date</type> or <type>time</type> will
2832     be cast to <type>timestamp</type> and can therefore be used as
2833     well.)  <replaceable>field</replaceable> is an identifier or
2834     string that selects what field to extract from the source value.
2835     The <function>extract</function> function returns values of type
2836     <type>double precision</type>.
2837     The following are valid values:
2838
2839     <!-- alphabetical -->
2840     <variablelist>
2841      <varlistentry>
2842       <term><literal>century</literal></term>
2843       <listitem>
2844        <para>
2845         The year field divided by 100
2846        </para>
2847
2848        <informalexample>
2849 <screen>
2850 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
2851 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
2852 </screen>
2853        </informalexample>
2854
2855        <para>
2856         Note that the result for the century field is simply the year field
2857         divided by 100, and not the conventional definition which puts most
2858         years in the 1900's in the twentieth century.
2859        </para>
2860       </listitem>
2861      </varlistentry>
2862
2863      <varlistentry>
2864       <term><literal>day</literal></term>
2865       <listitem>
2866        <para>
2867         The day (of the month) field (1 - 31)
2868        </para>
2869
2870        <informalexample>
2871 <screen>
2872 SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
2873 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
2874 </screen>
2875        </informalexample>
2876       </listitem>
2877      </varlistentry>
2878
2879      <varlistentry>
2880       <term><literal>decade</literal></term>
2881       <listitem>
2882        <para>
2883         The year field divided by 10
2884        </para>
2885
2886        <informalexample>
2887 <screen>
2888 SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
2889 <lineannotation>Result: </lineannotation><computeroutput>200</computeroutput>
2890 </screen>
2891        </informalexample>
2892       </listitem>
2893      </varlistentry>
2894
2895      <varlistentry>
2896       <term><literal>dow</literal></term>
2897       <listitem>
2898        <para>
2899         The day of the week (0 - 6; Sunday is 0) (for
2900         <type>timestamp</type> values only)
2901        </para>
2902
2903        <informalexample>
2904 <screen>
2905 SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
2906 <lineannotation>Result: </lineannotation><computeroutput>5</computeroutput>
2907 </screen>
2908        </informalexample>
2909       </listitem>
2910      </varlistentry>
2911
2912      <varlistentry>
2913       <term><literal>doy</literal></term>
2914       <listitem>
2915        <para>
2916         The day of the year (1 - 365/366) (for <type>timestamp</type> values only)
2917        </para>
2918        <informalexample>
2919 <screen>
2920 SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
2921 <lineannotation>Result: </lineannotation><computeroutput>47</computeroutput>
2922 </screen>
2923        </informalexample>
2924       </listitem>
2925      </varlistentry>
2926
2927      <varlistentry>
2928       <term><literal>epoch</literal></term>
2929       <listitem>
2930        <para>
2931         For <type>date</type> and <type>timestamp</type> values, the
2932         number of seconds since 1970-01-01 00:00:00-00 (Result may be
2933         negative.); for <type>interval</type> values, the total number
2934         of seconds in the interval
2935        </para>
2936
2937        <informalexample>
2938 <screen>
2939 SELECT EXTRACT(EPOCH FROM TIMESTAMP '2001-02-16 20:38:40');
2940 <lineannotation>Result: </lineannotation><computeroutput>982352320</computeroutput>
2941
2942 SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
2943 <lineannotation>Result: </lineannotation><computeroutput>442800</computeroutput>
2944 </screen>
2945        </informalexample>
2946       </listitem>
2947      </varlistentry>
2948
2949      <varlistentry>
2950       <term><literal>hour</literal></term>
2951       <listitem>
2952        <para>
2953         The hour field (0 - 23)
2954        </para>
2955
2956        <informalexample>
2957 <screen>
2958 SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
2959 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
2960 </screen>
2961        </informalexample>
2962       </listitem>
2963      </varlistentry>
2964
2965      <varlistentry>
2966       <term><literal>microseconds</literal></term>
2967       <listitem>
2968        <para>
2969         The seconds field, including fractional parts, multiplied by 1
2970         000 000.  Note that this includes full seconds.
2971        </para>
2972
2973        <informalexample>
2974 <screen>
2975 SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
2976 <lineannotation>Result: </lineannotation><computeroutput>28500000</computeroutput>
2977 </screen>
2978        </informalexample>
2979       </listitem>
2980      </varlistentry>
2981
2982      <varlistentry>
2983       <term><literal>millennium</literal></term>
2984       <listitem>
2985        <para>
2986         The year field divided by 1000
2987        </para>
2988
2989        <informalexample>
2990 <screen>
2991 SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
2992 <lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
2993 </screen>
2994        </informalexample>
2995
2996        <para>
2997         Note that the result for the millennium field is simply the year field
2998         divided by 1000, and not the conventional definition which puts
2999         years in the 1900's in the second millennium.
3000        </para>
3001       </listitem>
3002      </varlistentry>
3003
3004      <varlistentry>
3005       <term><literal>milliseconds</literal></term>
3006       <listitem>
3007        <para>
3008         The seconds field, including fractional parts, multiplied by
3009         1000.  Note that this includes full seconds.
3010        </para>
3011
3012        <informalexample>
3013 <screen>
3014 SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
3015 <lineannotation>Result: </lineannotation><computeroutput>28500</computeroutput>
3016 </screen>
3017        </informalexample>
3018       </listitem>
3019      </varlistentry>
3020
3021      <varlistentry>
3022       <term><literal>minute</literal></term>
3023       <listitem>
3024        <para>
3025         The minutes field (0 - 59)
3026        </para>
3027
3028        <informalexample>
3029 <screen>
3030 SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
3031 <lineannotation>Result: </lineannotation><computeroutput>38</computeroutput>
3032 </screen>
3033        </informalexample>
3034       </listitem>
3035      </varlistentry>
3036
3037      <varlistentry>
3038       <term><literal>month</literal></term>
3039       <listitem>
3040        <para>
3041         For <type>timestamp</type> values, the number of the month
3042         within the year (1 - 12) ; for <type>interval</type> values
3043         the number of months, modulo 12 (0 - 11)
3044        </para>
3045
3046        <informalexample>
3047 <screen>
3048 SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
3049 <lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
3050
3051 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
3052 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
3053
3054 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
3055 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
3056 </screen>
3057        </informalexample>
3058       </listitem>
3059      </varlistentry>
3060
3061      <varlistentry>
3062       <term><literal>quarter</literal></term>
3063       <listitem>
3064        <para>
3065         The quarter of the year (1 - 4) that the day is in (for
3066         <type>timestamp</type> values only)
3067        </para>
3068
3069        <informalexample>
3070 <screen>
3071 SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
3072 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
3073 </screen>
3074        </informalexample>
3075       </listitem>
3076      </varlistentry>
3077
3078      <varlistentry>
3079       <term><literal>second</literal></term>
3080       <listitem>
3081        <para>
3082         The seconds field, including fractional parts (0 -
3083         59<footnote><simpara>60 if leap seconds are
3084         implemented by the operating system</simpara></footnote>)
3085        </para>
3086
3087        <informalexample>
3088 <screen>
3089 SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
3090 <lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
3091
3092 SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
3093 <lineannotation>Result: </lineannotation><computeroutput>28.5</computeroutput>
3094 </screen>
3095        </informalexample>
3096       </listitem>
3097      </varlistentry>
3098 <!--
3099      <varlistentry>
3100       <term><literal>timezone</literal></term>
3101       <listitem>
3102        <para>
3103         The time zone offset. XXX But in what units?
3104        </para>
3105       </listitem>
3106      </varlistentry>
3107 -->
3108
3109      <varlistentry>
3110       <term><literal>timezone_hour</literal></term>
3111       <listitem>
3112        <para>
3113         The hour component of the time zone offset.
3114        </para>
3115       </listitem>
3116      </varlistentry>
3117
3118      <varlistentry>
3119       <term><literal>timezone_minute</literal></term>
3120       <listitem>
3121        <para>
3122         The minute component of the time zone offset.
3123        </para>
3124       </listitem>
3125      </varlistentry>
3126
3127      <varlistentry>
3128       <term><literal>week</literal></term>
3129       <listitem>
3130        <para>
3131         From a <type>timestamp</type> value, calculate the number of
3132         the week of the year that the day is in.  By definition
3133         (<acronym>ISO</acronym> 8601), the first week of a year
3134         contains January 4 of that year.  (The <acronym>ISO</acronym>
3135         week starts on Monday.)  In other words, the first Thursday of
3136         a year is in week 1 of that year.
3137        </para>
3138
3139        <informalexample>
3140 <screen>
3141 SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
3142 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
3143 </screen>
3144        </informalexample>
3145       </listitem>
3146      </varlistentry>
3147
3148      <varlistentry>
3149       <term><literal>year</literal></term>
3150       <listitem>
3151        <para>
3152         The year field
3153        </para>
3154
3155        <informalexample>
3156 <screen>
3157 SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
3158 <lineannotation>Result: </lineannotation><computeroutput>2001</computeroutput>
3159 </screen>
3160        </informalexample>
3161       </listitem>
3162      </varlistentry>
3163
3164     </variablelist>
3165
3166    </para>
3167
3168    <para>
3169     The <function>extract</function> function is primarily intended
3170     for computational processing.  For formatting date/time values for
3171     display, see <xref linkend="functions-formatting">.
3172    </para>
3173
3174    <anchor id="functions-datetime-datepart">
3175    <para>
3176     The <function>date_part</function> function is modeled on the traditional
3177     <productname>Ingres</productname> equivalent to the
3178     <acronym>SQL</acronym>-function <function>extract</function>:
3179 <synopsis>
3180 date_part('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
3181 </synopsis>
3182     Note that here the <replaceable>field</replaceable> value needs to
3183     be a string.  The valid field values for
3184     <function>date_part</function> are the same as for
3185     <function>extract</function>.
3186    </para>
3187
3188    <informalexample>
3189 <screen>
3190 SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
3191 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
3192
3193 SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
3194 <lineannotation>Result: </lineannotation><computeroutput>4</computeroutput>
3195 </screen>
3196    </informalexample>
3197
3198   </sect2>
3199
3200   <sect2 id="functions-datetime-trunc">
3201    <title><function>date_trunc</function></title>
3202
3203    <para>
3204     The function <function>date_trunc</function> is conceptually
3205     similar to the <function>trunc</function> function for numbers.
3206    </para>
3207
3208    <para>
3209 <synopsis>
3210 date_trunc('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
3211 </synopsis>
3212     <replaceable>source</replaceable> is a value expression of type
3213     <type>timestamp</type> (values of type <type>date</type> and
3214     <type>time</type> are cast automatically).
3215     <replaceable>field</replaceable> selects to which precision to
3216     truncate the time stamp value.  The return value is of type
3217     <type>timestamp</type> with all fields that are less than the
3218     selected one set to zero (or one, for day and month).
3219    </para>
3220
3221    <para>
3222     Valid values for <replaceable>field</replaceable> are:
3223     <simplelist>
3224      <member>microseconds</member>
3225      <member>milliseconds</member>
3226      <member>second</member>
3227      <member>minute</member>
3228      <member>hour</member>
3229      <member>day</member>
3230      <member>month</member>
3231      <member>year</member>
3232      <member>decade</member>
3233      <member>century</member>
3234      <member>millennium</member>
3235     </simplelist>
3236    </para>
3237
3238    <informalexample>
3239     <para>
3240 <screen>
3241 SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
3242 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 20:00:00+00</computeroutput>
3243
3244 SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
3245 <lineannotation>Result: </lineannotation><computeroutput>2001-01-01 00:00:00+00</computeroutput>
3246 </screen>
3247     </para>
3248    </informalexample>
3249   </sect2>
3250
3251   <sect2 id="functions-datetime-current">
3252    <title>Current Date/Time</title>
3253
3254    <indexterm>
3255     <primary>date</primary>
3256     <secondary>current</secondary>
3257    </indexterm>
3258
3259    <indexterm>
3260     <primary>time</primary>
3261     <secondary>current</secondary>
3262    </indexterm>
3263
3264    <para>
3265     The following functions are available to obtain the current date and/or
3266     time:
3267 <synopsis>
3268 CURRENT_DATE
3269 CURRENT_TIME
3270 CURRENT_TIMESTAMP
3271 CURRENT_TIME ( <replaceable>precision</replaceable> )
3272 CURRENT_TIMESTAMP ( <replaceable>precision</replaceable> )
3273 </synopsis>
3274     <function>CURRENT_TIME</function> and
3275     <function>CURRENT_TIMESTAMP</function> can optionally be given
3276     a precision parameter, which causes the result to be rounded
3277     to that many fractional digits.  Without a precision parameter,
3278     the result is given to full available precision.
3279    </para>
3280
3281    <note>
3282     <para>
3283      Prior to <productname>PostgreSQL</productname> 7.2, the precision parameters
3284      were unimplemented, and the result was always given in integer
3285      seconds.
3286     </para>
3287    </note>
3288
3289    <note>
3290     <para>
3291      The <acronym>SQL99</acronym> standard requires these functions to
3292      be written without any parentheses, unless a precision parameter
3293      is given.  As of <productname>PostgreSQL</productname> 7.2, an empty pair of
3294      parentheses can be written, but this is deprecated and may be
3295      removed in a future release.
3296     </para>
3297    </note>
3298
3299    <informalexample>
3300 <screen>
3301 SELECT CURRENT_TIME;
3302 <computeroutput>14:39:53.662522-05</computeroutput>
3303
3304 SELECT CURRENT_DATE;
3305 <computeroutput>2001-12-23</computeroutput>
3306
3307 SELECT CURRENT_TIMESTAMP;
3308 <computeroutput>2001-12-23 14:39:53.662522-05</computeroutput>
3309
3310 SELECT CURRENT_TIMESTAMP(2);
3311 <computeroutput>2001-12-23 14:39:53.66-05</computeroutput>
3312 </screen>
3313    </informalexample>
3314
3315    <para>
3316     The function <function>now()</function> is the traditional
3317     <productname>PostgreSQL</productname> equivalent to
3318     <function>CURRENT_TIMESTAMP</function>.
3319    </para>
3320
3321    <para>
3322     There is also <function>timeofday()</function>, which for historical
3323     reasons returns a text string rather than a <type>timestamp</type> value:
3324    </para>
3325
3326    <informalexample>
3327 <screen>
3328 SELECT timeofday();
3329  Sat Feb 17 19:07:32.000126 2001 EST
3330 </screen>
3331    </informalexample>
3332
3333    <para>
3334     It is quite important to realize that
3335     <function>CURRENT_TIMESTAMP</function> and related functions all return
3336     the time as of the start of the current transaction; their values do not
3337     increment while a transaction is running.  But
3338     <function>timeofday()</function> returns the actual current time.
3339    </para>
3340
3341    <para>
3342     All the date/time data types also accept the special literal value
3343     <literal>now</literal> to specify the current date and time.  Thus,
3344     the following three all return the same result:
3345 <programlisting>
3346 SELECT CURRENT_TIMESTAMP;
3347 SELECT now();
3348 SELECT TIMESTAMP 'now';
3349 </programlisting>
3350     <note>
3351      <para>
3352       You do not want to use the third form when specifying a DEFAULT
3353       value while creating a table.  The system will convert <literal>now</literal>
3354       to a <type>timestamp</type> as soon as the constant is parsed, so that when
3355       the default value is needed,
3356       the time of the table creation would be used!  The first two
3357       forms will not be evaluated until the default value is used,
3358       because they are function calls.  Thus they will give the desired
3359       behavior of defaulting to the time of row insertion.
3360      </para>
3361     </note>
3362    </para>
3363   </sect2>
3364  </sect1>
3365
3366   
3367  <sect1 id="functions-geometry">
3368    <title>Geometric Functions and Operators</title>
3369
3370    <para>
3371     The geometric types <type>point</type>, <type>box</type>,
3372     <type>lseg</type>, <type>line</type>, <type>path</type>,
3373     <type>polygon</type>, and <type>circle</type> have a large set of
3374     native support functions and operators.
3375    </para>
3376
3377    <table>
3378      <title>Geometric Operators</title>
3379      <tgroup cols="3">
3380       <thead>
3381        <row>
3382         <entry>Operator</entry>
3383         <entry>Description</entry>
3384         <entry>Usage</entry>
3385        </row>
3386       </thead>
3387       <tbody>
3388        <row>
3389         <entry> + </entry>
3390         <entry>Translation</entry>
3391         <entry><literal>box '((0,0),(1,1))' + point '(2.0,0)'</literal></entry>
3392        </row>
3393        <row>
3394         <entry> - </entry>
3395         <entry>Translation</entry>
3396         <entry><literal>box '((0,0),(1,1))' - point '(2.0,0)'</literal></entry>
3397        </row>
3398        <row>
3399         <entry> * </entry>
3400         <entry>Scaling/rotation</entry>
3401         <entry><literal>box '((0,0),(1,1))' * point '(2.0,0)'</literal></entry>
3402        </row>
3403        <row>
3404         <entry> / </entry>
3405         <entry>Scaling/rotation</entry>
3406         <entry><literal>box '((0,0),(2,2))' / point '(2.0,0)'</literal></entry>
3407        </row>
3408        <row>
3409         <entry> # </entry>
3410         <entry>Intersection</entry>
3411         <entry><literal>'((1,-1),(-1,1))' # '((1,1),(-1,-1))'</literal></entry>
3412        </row>
3413        <row>
3414         <entry> # </entry>
3415         <entry>Number of points in polygon</entry>
3416         <entry><literal># '((1,0),(0,1),(-1,0))'</literal></entry>
3417        </row>
3418        <row>
3419         <entry> ## </entry>
3420         <entry>Point of closest proximity</entry>
3421         <entry><literal>point '(0,0)' ## lseg '((2,0),(0,2))'</literal></entry>
3422        </row>
3423        <row>
3424         <entry> &amp;&amp; </entry>
3425         <entry>Overlaps?</entry>
3426         <entry><literal>box '((0,0),(1,1))' &amp;&amp; box '((0,0),(2,2))'</literal></entry>
3427        </row>
3428        <row>
3429         <entry> &amp;&lt; </entry>
3430         <entry>Overlaps to left?</entry>
3431         <entry><literal>box '((0,0),(1,1))' &amp;&lt; box '((0,0),(2,2))'</literal></entry>
3432        </row>
3433        <row>
3434         <entry> &amp;&gt; </entry>
3435         <entry>Overlaps to right?</entry>
3436         <entry><literal>box '((0,0),(3,3))' &amp;&gt; box '((0,0),(2,2))'</literal></entry>
3437        </row>
3438        <row>
3439         <entry> &lt;-&gt; </entry>
3440         <entry>Distance between</entry>
3441         <entry><literal>circle '((0,0),1)' &lt;-&gt; circle '((5,0),1)'</literal></entry>
3442        </row>
3443        <row>
3444         <entry> &lt;&lt; </entry>
3445         <entry>Left of?</entry>
3446         <entry><literal>circle '((0,0),1)' &lt;&lt; circle '((5,0),1)'</literal></entry>
3447        </row>
3448        <row>
3449         <entry> &lt;^ </entry>
3450         <entry>Is below?</entry>
3451         <entry><literal>circle '((0,0),1)' &lt;^ circle '((0,5),1)'</literal></entry>
3452        </row>
3453        <row>
3454         <entry> &gt;&gt; </entry>
3455         <entry>Is right of?</entry>
3456         <entry><literal>circle '((5,0),1)' &gt;&gt; circle '((0,0),1)'</literal></entry>
3457        </row>
3458        <row>
3459         <entry> &gt;^ </entry>
3460         <entry>Is above?</entry>
3461         <entry><literal>circle '((0,5),1)' >^ circle '((0,0),1)'</literal></entry>
3462        </row>
3463        <row>
3464         <entry> ?# </entry>
3465         <entry>Intersects or overlaps</entry>
3466         <entry><literal>lseg '((-1,0),(1,0))' ?# box '((-2,-2),(2,2))'</literal></entry>
3467        </row>
3468        <row>
3469         <entry> ?- </entry>
3470         <entry>Is horizontal?</entry>
3471         <entry><literal>point '(1,0)' ?- point '(0,0)'</literal></entry>
3472        </row>
3473        <row>
3474         <entry> ?-| </entry>
3475         <entry>Is perpendicular?</entry>
3476         <entry><literal>lseg '((0,0),(0,1))' ?-| lseg '((0,0),(1,0))'</literal></entry>
3477        </row>
3478        <row>
3479         <entry> @-@  </entry>
3480         <entry>Length or circumference</entry>
3481         <entry><literal>@-@ path '((0,0),(1,0))'</literal></entry>
3482        </row>
3483        <row>
3484         <entry> ?| </entry>
3485         <entry>Is vertical?</entry>
3486         <entry><literal>point '(0,1)' ?| point '(0,0)'</literal></entry>
3487        </row>
3488        <row>
3489         <entry> ?|| </entry>
3490         <entry>Is parallel?</entry>
3491         <entry><literal>lseg '((-1,0),(1,0))' ?|| lseg '((-1,2),(1,2))'</literal></entry>
3492        </row>
3493        <row>
3494         <entry> @ </entry>
3495         <entry>Contained or on</entry>
3496         <entry><literal>point '(1,1)' @ circle '((0,0),2)'</literal></entry>
3497        </row>
3498        <row>
3499         <entry> @@ </entry>
3500         <entry>Center of</entry>
3501         <entry><literal>@@ circle '((0,0),10)'</literal></entry>
3502        </row>
3503        <row>
3504         <entry> ~= </entry>
3505         <entry>Same as</entry>
3506         <entry><literal>polygon '((0,0),(1,1))' ~= polygon '((1,1),(0,0))'</literal></entry>
3507        </row>
3508       </tbody>
3509      </tgroup>
3510    </table>
3511
3512    <table>
3513      <title>Geometric Functions</title>
3514      <tgroup cols="4">
3515       <thead>
3516        <row>
3517         <entry>Function</entry>
3518         <entry>Returns</entry>
3519         <entry>Description</entry>
3520         <entry>Example</entry>
3521        </row>
3522       </thead>
3523       <tbody>
3524        <row>
3525         <entry><function>area</function>(object)</entry>
3526         <entry><type>double precision</type></entry>
3527         <entry>area of item</entry>
3528         <entry><literal>area(box '((0,0),(1,1))')</literal></entry>
3529        </row>
3530        <row>
3531         <entry><function>box</function>(box, box)</entry>
3532         <entry><type>box</type></entry>
3533         <entry>intersection box</entry>
3534         <entry><literal>box(box '((0,0),(1,1))',box '((0.5,0.5),(2,2))')</literal></entry>
3535        </row>
3536        <row>
3537         <entry><function>center</function>(object)</entry>
3538         <entry><type>point</type></entry>
3539         <entry>center of item</entry>
3540         <entry><literal>center(box '((0,0),(1,2))')</literal></entry>
3541        </row>
3542        <row>
3543         <entry><function>diameter</function>(circle)</entry>
3544         <entry><type>double precision</type></entry>
3545         <entry>diameter of circle</entry>
3546         <entry><literal>diameter(circle '((0,0),2.0)')</literal></entry>
3547        </row>
3548        <row>
3549         <entry><function>height</function>(box)</entry>
3550         <entry><type>double precision</type></entry>
3551         <entry>vertical size of box</entry>
3552         <entry><literal>height(box '((0,0),(1,1))')</literal></entry>
3553        </row>
3554        <row>
3555         <entry><function>isclosed</function>(path)</entry>
3556         <entry><type>boolean</type></entry>
3557         <entry>a closed path?</entry>
3558         <entry><literal>isclosed(path '((0,0),(1,1),(2,0))')</literal></entry>
3559        </row>
3560        <row>
3561         <entry><function>isopen</function>(path)</entry>
3562         <entry><type>boolean</type></entry>
3563         <entry>an open path?</entry>
3564         <entry><literal>isopen(path '[(0,0),(1,1),(2,0)]')</literal></entry>
3565        </row>
3566        <row>
3567         <entry><function>length</function>(object)</entry>
3568         <entry><type>double precision</type></entry>
3569         <entry>length of item</entry>
3570         <entry><literal>length(path '((-1,0),(1,0))')</literal></entry>
3571        </row>
3572        <row>
3573         <entry><function>pclose</function>(path)</entry>
3574         <entry><type>path</type></entry>
3575         <entry>convert path to closed</entry>
3576         <entry><literal>popen(path '[(0,0),(1,1),(2,0)]')</literal></entry>
3577        </row>
3578 <![IGNORE[
3579 <!-- Not defined by this name. Implements the intersection operator '#' -->
3580        <row>
3581         <entry><function>point</function>(lseg,lseg)</entry>
3582         <entry><type>point</type></entry>
3583         <entry>intersection</entry>
3584         <entry><literal>point(lseg '((-1,0),(1,0))',lseg '((-2,-2),(2,2))')</literal></entry>
3585        </row>
3586 ]]>
3587        <row>
3588         <entry><function>npoint</function>(path)</entry>
3589         <entry><type>integer</type></entry>
3590         <entry>number of points</entry>
3591         <entry><literal>npoints(path '[(0,0),(1,1),(2,0)]')</literal></entry>
3592        </row>
3593        <row>
3594         <entry><function>popen</function>(path)</entry>
3595         <entry><type>path</type></entry>
3596         <entry>convert path to open path</entry>
3597         <entry><literal>popen(path '((0,0),(1,1),(2,0))')</literal></entry>
3598        </row>
3599        <row>
3600         <entry><function>radius</function>(circle)</entry>
3601         <entry><type>double precision</type></entry>
3602         <entry>radius of circle</entry>
3603         <entry><literal>radius(circle '((0,0),2.0)')</literal></entry>
3604        </row>
3605        <row>
3606         <entry><function>width</function>(box)</entry>
3607         <entry><type>double precision</type></entry>
3608         <entry>horizontal size</entry>
3609         <entry><literal>width(box '((0,0),(1,1))')</literal></entry>
3610        </row>
3611       </tbody>
3612      </tgroup>
3613    </table>
3614
3615
3616    <table>
3617      <title>Geometric Type Conversion Functions</title>
3618      <tgroup cols="4">
3619       <thead>
3620        <row>
3621         <entry>Function</entry>
3622         <entry>Returns</entry>
3623         <entry>Description</entry>
3624         <entry>Example</entry>
3625        </row>
3626       </thead>
3627       <tbody>
3628        <row>
3629         <entry><function>box</function>(<type>circle</type>)</entry>
3630         <entry><type>box</type></entry>
3631         <entry>circle to box</entry>
3632         <entry><literal>box(circle '((0,0),2.0)')</literal></entry>
3633        </row>
3634        <row>
3635         <entry><function>box</function>(<type>point</type>, <type>point</type>)</entry>
3636         <entry><type>box</type></entry>
3637         <entry>points to box</entry>
3638         <entry><literal>box(point '(0,0)', point '(1,1)')</literal></entry>
3639        </row>
3640        <row>
3641         <entry><function>box</function>(<type>polygon</type>)</entry>
3642         <entry><type>box</type></entry>
3643         <entry>polygon to box</entry>
3644         <entry><literal>box(polygon '((0,0),(1,1),(2,0))')</literal></entry>
3645        </row>
3646        <row>
3647         <entry><function>circle</function>(<type>box</type>)</entry>
3648         <entry><type>circle</type></entry>
3649         <entry>to circle</entry>
3650         <entry><literal>circle(box '((0,0),(1,1))')</literal></entry>
3651        </row>
3652        <row>
3653         <entry><function>circle</function>(<type>point</type>, <type>double precision</type>)</entry>
3654         <entry><type>circle</type></entry>
3655         <entry>point to circle</entry>
3656         <entry><literal>circle(point '(0,0)', 2.0)</literal></entry>
3657        </row>
3658        <row>
3659         <entry><function>lseg</function>(<type>box</type>)</entry>
3660         <entry><type>lseg</type></entry>
3661         <entry>box diagonal to <type>lseg</type></entry>
3662         <entry><literal>lseg(box '((-1,0),(1,0))')</literal></entry>
3663        </row>
3664        <row>
3665         <entry><function>lseg</function>(<type>point</type>, <type>point</type>)</entry>
3666         <entry><type>lseg</type></entry>
3667         <entry>points to <type>lseg</type></entry>
3668         <entry><literal>lseg(point '(-1,0)', point '(1,0)')</literal></entry>
3669        </row>
3670        <row>
3671         <entry><function>path</function>(<type>polygon</type>)</entry>
3672         <entry><type>point</type></entry>
3673         <entry>polygon to path</entry>
3674         <entry><literal>path(polygon '((0,0),(1,1),(2,0))')</literal></entry>
3675        </row>
3676        <row>
3677         <entry><function>point</function>(<type>circle</type>)</entry>
3678         <entry><type>point</type></entry>
3679         <entry>center</entry>
3680         <entry><literal>point(circle '((0,0),2.0)')</literal></entry>
3681        </row>
3682        <row>
3683         <entry><function>point</function>(<type>lseg</type>, <type>lseg</type>)</entry>
3684         <entry><type>point</type></entry>
3685         <entry>intersection</entry>
3686         <entry><literal>point(lseg '((-1,0),(1,0))', lseg '((-2,-2),(2,2))')</literal></entry>
3687        </row>
3688        <row>
3689         <entry><function>point</function>(<type>polygon</type>)</entry>
3690         <entry><type>point</type></entry>
3691         <entry>center</entry>
3692         <entry><literal>point(polygon '((0,0),(1,1),(2,0))')</literal></entry>
3693        </row>
3694        <row>
3695         <entry><function>polygon</function>(<type>box</type>)</entry>
3696         <entry><type>polygon</type></entry>
3697         <entry>12 point polygon</entry>
3698         <entry><literal>polygon(box '((0,0),(1,1))')</literal></entry>
3699        </row>
3700        <row>
3701         <entry><function>polygon</function>(<type>circle</type>)</entry>
3702         <entry><type>polygon</type></entry>
3703         <entry>12-point polygon</entry>
3704         <entry><literal>polygon(circle '((0,0),2.0)')</literal></entry>
3705        </row>
3706        <row>
3707         <entry><function>polygon</function>(<replaceable class="parameter">npts</replaceable>, <type>circle</type>)</entry>
3708         <entry><type>polygon</type></entry>
3709         <entry><replaceable class="parameter">npts</replaceable> polygon</entry>
3710         <entry><literal>polygon(12, circle '((0,0),2.0)')</literal></entry>
3711        </row>
3712        <row>
3713         <entry><function>polygon</function>(<type>path</type>)</entry>
3714         <entry><type>polygon</type></entry>
3715         <entry>path to polygon</entry>
3716         <entry><literal>polygon(path '((0,0),(1,1),(2,0))')</literal></entry>
3717        </row>
3718       </tbody>
3719      </tgroup>
3720    </table>
3721
3722   </sect1>
3723
3724
3725   <sect1 id="functions-net">
3726    <title>Network Address Type Functions</title>
3727
3728
3729     <table tocentry="1" id="cidr-inet-operators-table">
3730      <title><type>cidr</type> and <type>inet</type> Operators</title>
3731      <tgroup cols="3">
3732       <thead>
3733        <row>
3734         <entry>Operator</entry>
3735         <entry>Description</entry>
3736         <entry>Usage</entry>
3737        </row>
3738       </thead>
3739       <tbody>
3740        <row>
3741         <entry> &lt; </entry>
3742         <entry>Less than</entry>
3743         <entry><literal>inet '192.168.1.5' &lt; inet '192.168.1.6'</literal></entry>
3744        </row>
3745        <row>
3746         <entry> &lt;= </entry>
3747         <entry>Less than or equal</entry>
3748         <entry><literal>inet '192.168.1.5' &lt;= inet '192.168.1.5'</literal></entry>
3749        </row>
3750        <row>
3751         <entry> = </entry>
3752         <entry>Equals</entry>
3753         <entry><literal>inet '192.168.1.5' = inet '192.168.1.5'</literal></entry>
3754        </row>
3755        <row>
3756         <entry> &gt;= </entry>
3757         <entry>Greater or equal</entry>
3758         <entry><literal>inet '192.168.1.5' &gt;= inet '192.168.1.5'</literal></entry>
3759        </row>
3760        <row>
3761         <entry> &gt; </entry>
3762         <entry>Greater</entry>
3763         <entry><literal>inet '192.168.1.5' &gt; inet '192.168.1.4'</literal></entry>
3764        </row>
3765        <row>
3766         <entry> &lt;&gt; </entry>
3767         <entry>Not equal</entry>
3768         <entry><literal>inet '192.168.1.5' &lt;&gt; inet '192.168.1.4'</literal></entry>
3769        </row>
3770        <row>
3771         <entry> &lt;&lt; </entry>
3772         <entry>is contained within</entry>
3773         <entry><literal>inet '192.168.1.5' &lt;&lt; inet '192.168.1/24'</literal></entry>
3774        </row>
3775        <row>
3776         <entry> &lt;&lt;= </entry>
3777         <entry>is contained within or equals</entry>
3778         <entry><literal>inet '192.168.1/24' &lt;&lt;= inet '192.168.1/24'</literal></entry>
3779        </row>
3780        <row>
3781         <entry> &gt;&gt; </entry>
3782         <entry>contains</entry>
3783         <entry><literal>inet'192.168.1/24' &gt;&gt; inet '192.168.1.5'</literal></entry>
3784        </row>
3785        <row>
3786         <entry> &gt;&gt;= </entry>
3787         <entry>contains or equals</entry>
3788         <entry><literal>inet '192.168.1/24' &gt;&gt;= inet '192.168.1/24'</literal></entry>
3789        </row>
3790       </tbody>
3791      </tgroup>
3792     </table>
3793
3794     <para>
3795      All of the operators for <type>inet</type> can be applied to
3796      <type>cidr</type> values as well.  The operators
3797      <literal>&lt;&lt;</literal>, <literal>&lt;&lt;=</literal>,
3798      <literal>&gt;&gt;</literal>, <literal>&gt;&gt;=</literal>
3799      test for subnet inclusion: they consider only the network parts
3800      of the two addresses, ignoring any host part, and determine whether
3801      one network part is identical to or a subnet of the other.
3802     </para>
3803
3804
3805     <table tocentry="1" id="cidr-inet-functions">
3806      <title><type>cidr</type> and <type>inet</type> Functions</title>
3807      <tgroup cols="5">
3808       <thead>
3809        <row>
3810         <entry>Function</entry>
3811         <entry>Returns</entry>
3812         <entry>Description</entry>
3813         <entry>Example</entry>
3814         <entry>Result</entry>
3815        </row>
3816       </thead>
3817       <tbody>
3818        <row>
3819         <entry><function>broadcast</function>(<type>inet</type>)</entry>
3820         <entry><type>inet</type></entry>
3821         <entry>broadcast address for network</entry>
3822         <entry><literal>broadcast('192.168.1.5/24')</literal></entry>
3823         <entry><literal>192.168.1.255/24</literal></entry>
3824        </row>
3825        <row>
3826         <entry><function>host</function>(<type>inet</type>)</entry>
3827         <entry><type>text</type></entry>
3828         <entry>extract IP address as text</entry>
3829         <entry><literal>host('192.168.1.5/24')</literal></entry>
3830         <entry><literal>192.168.1.5</literal></entry>
3831        </row>
3832        <row>
3833         <entry><function>masklen</function>(<type>inet</type>)</entry>
3834         <entry><type>integer</type></entry>
3835         <entry>extract netmask length</entry>
3836         <entry><literal>masklen('192.168.1.5/24')</literal></entry>
3837         <entry><literal>24</literal></entry>
3838        </row>
3839        <row>
3840         <entry><function>set_masklen</function>(<type>inet</type>,<type>integer</type>)</entry>
3841         <entry><type>inet</type></entry>
3842         <entry>set netmask length for <type>inet</type> value</entry>
3843         <entry><literal>set_masklen('192.168.1.5/24',16)</literal></entry>
3844         <entry><literal>192.168.1.5/16</literal></entry>
3845        </row>
3846        <row>
3847         <entry><function>netmask</function>(<type>inet</type>)</entry>
3848         <entry><type>inet</type></entry>
3849         <entry>construct netmask for network</entry>
3850         <entry><literal>netmask('192.168.1.5/24')</literal></entry>
3851         <entry><literal>255.255.255.0</literal></entry>
3852        </row>
3853        <row>
3854         <entry><function>network</function>(<type>inet</type>)</entry>
3855         <entry><type>cidr</type></entry>
3856         <entry>extract network part of address</entry>
3857         <entry><literal>network('192.168.1.5/24')</literal></entry>
3858         <entry><literal>192.168.1.0/24</literal></entry>
3859        </row>
3860        <row>
3861         <entry><function>text</function>(<type>inet</type>)</entry>
3862         <entry><type>text</type></entry>
3863         <entry>extract IP address and masklen as text</entry>
3864         <entry><literal>text(inet '192.168.1.5')</literal></entry>
3865         <entry><literal>192.168.1.5/32</literal></entry>
3866        </row>
3867        <row>
3868         <entry><function>abbrev</function>(<type>inet</type>)</entry>
3869         <entry><type>text</type></entry>
3870         <entry>extract abbreviated display as text</entry>
3871         <entry><literal>abbrev(cidr '10.1.0.0/16')</literal></entry>
3872         <entry><literal>10.1/16</literal></entry>
3873        </row>
3874       </tbody>
3875      </tgroup>
3876     </table>
3877
3878    <para>
3879     All of the functions for <type>inet</type> can be applied to
3880     <type>cidr</type> values as well.  The <function>host</function>(),
3881     <function>text</function>(), and <function>abbrev</function>() functions are primarily
3882     intended to offer alternative display formats. You can cast a text
3883     field to inet using normal casting syntax: <literal>inet(expression)</literal> or 
3884     <literal>colname::inet</literal>.
3885    </para>
3886
3887     <table tocentry="1" id="macaddr-functions">
3888      <title><type>macaddr</type> Functions</title>
3889      <tgroup cols="5">
3890       <thead>
3891        <row>
3892         <entry>Function</entry>
3893         <entry>Returns</entry>
3894         <entry>Description</entry>
3895         <entry>Example</entry>
3896         <entry>Result</entry>
3897        </row>
3898       </thead>
3899       <tbody>
3900        <row>
3901         <entry><function>trunc</function>(<type>macaddr</type>)</entry>
3902         <entry><type>macaddr</type></entry>
3903         <entry>set last 3 bytes to zero</entry>
3904         <entry><literal>trunc(macaddr '12:34:56:78:90:ab')</literal></entry>
3905         <entry><literal>12:34:56:00:00:00</literal></entry>
3906        </row>
3907       </tbody>
3908      </tgroup>
3909     </table>
3910
3911    <para>
3912     The function <function>trunc</function>(<type>macaddr</type>) returns a MAC
3913     address with the last 3 bytes set to 0.  This can be used to
3914     associate the remaining prefix with a manufacturer.  The directory
3915     <filename>contrib/mac</filename> in the source distribution contains some
3916     utilities to create and maintain such an association table.
3917    </para>
3918
3919    <para>
3920     The <type>macaddr</type> type also supports the standard relational
3921     operators (<literal>&gt;</literal>, <literal>&lt;=</literal>, etc.) for
3922     lexicographical ordering.
3923    </para>
3924
3925   </sect1>
3926
3927
3928  <sect1 id="functions-sequence">
3929   <title>Sequence-Manipulation Functions</title>
3930
3931   <indexterm>
3932    <primary>sequences</primary>
3933   </indexterm>
3934   <indexterm>
3935    <primary>nextval</primary>
3936   </indexterm>
3937   <indexterm>
3938    <primary>currval</primary>
3939   </indexterm>
3940   <indexterm>
3941    <primary>setval</primary>
3942   </indexterm>
3943
3944    <table>
3945     <title>Sequence Functions</title>
3946     <tgroup cols="3">
3947      <thead>
3948       <row><entry>Function</entry> <entry>Returns</entry> <entry>Description</entry></row>
3949      </thead>
3950
3951      <tbody>
3952       <row>
3953         <entry><function>nextval</function>(<type>text</type>)</entry>
3954         <entry><type>bigint</type></entry>
3955         <entry>Advance sequence and return new value</entry>
3956       </row>
3957       <row>
3958         <entry><function>currval</function>(<type>text</type>)</entry>
3959         <entry><type>bigint</type></entry>
3960         <entry>Return value most recently obtained with <function>nextval</function></entry>
3961       </row>
3962       <row>
3963         <entry><function>setval</function>(<type>text</type>,<type>bigint</type>)</entry>
3964         <entry><type>bigint</type></entry>
3965         <entry>Set sequence's current value</entry>
3966       </row>
3967       <row>
3968         <entry><function>setval</function>(<type>text</type>,<type>bigint</type>,<type>boolean</type>)</entry>
3969         <entry><type>bigint</type></entry>
3970         <entry>Set sequence's current value and <literal>is_called</literal> flag</entry>
3971       </row>
3972      </tbody>
3973     </tgroup>
3974    </table>
3975
3976   <para>
3977    This section describes <productname>PostgreSQL</productname>'s functions
3978    for operating on <firstterm>sequence objects</firstterm>.
3979    Sequence objects (also called sequence generators or
3980    just sequences) are special single-row tables created with
3981    <command>CREATE SEQUENCE</command>.  A sequence object is usually used to
3982    generate unique identifiers for rows of a table.  The sequence functions
3983    provide simple, multiuser-safe methods for obtaining successive
3984    sequence values from sequence objects.
3985   </para>
3986
3987   <para>
3988    For largely historical reasons, the sequence to be operated on by
3989    a sequence-function call is specified by a text-string argument.
3990    To achieve some compatibility with the handling of ordinary SQL
3991    names, the sequence functions convert their argument to lower case
3992    unless the string is double-quoted.  Thus
3993 <programlisting>
3994 nextval('foo')      <lineannotation>operates on sequence </><literal>foo</literal>
3995 nextval('FOO')      <lineannotation>operates on sequence </><literal>foo</literal>
3996 nextval('"Foo"')    <lineannotation>operates on sequence </><literal>Foo</literal>
3997 </programlisting>
3998    The sequence name can be schema-qualified if necessary:
3999 <programlisting>
4000 nextval('myschema.foo') <lineannotation>operates on </><literal>myschema.foo</literal>
4001 nextval('"myschema".foo') <lineannotation>same as above</lineannotation>
4002 nextval('foo')      <lineannotation>searches search path for
4003      </><literal>foo</literal>
4004 </programlisting>
4005    Of course, the text argument can be the result of an expression,
4006    not only a simple literal, which is occasionally useful.
4007   </para>
4008
4009   <para>
4010    The available sequence functions are:
4011
4012     <variablelist>
4013      <varlistentry>
4014       <term><function>nextval</function></term>
4015       <listitem>
4016        <para>
4017         Advance the sequence object to its next value and return that
4018         value.  This is done atomically: even if multiple server processes
4019         execute <function>nextval</function> concurrently, each will safely receive
4020         a distinct sequence value.
4021        </para>
4022       </listitem>
4023      </varlistentry>
4024
4025      <varlistentry>
4026       <term><function>currval</function></term>
4027       <listitem>
4028        <para>
4029         Return the value most recently obtained by <function>nextval</function>
4030         for this sequence in the current server process.  (An error is
4031         reported if <function>nextval</function> has never been called for this
4032         sequence in this process.)  Notice that because this is returning
4033         a process-local value, it gives a predictable answer even if other
4034         server processes are executing <function>nextval</function> meanwhile.
4035        </para>
4036       </listitem>
4037      </varlistentry>
4038
4039      <varlistentry>
4040       <term><function>setval</function></term>
4041       <listitem>
4042        <para>
4043         Reset the sequence object's counter value.  The two-parameter
4044         form sets the sequence's <literal>last_value</literal> field to the specified
4045         value and sets its <literal>is_called</literal> field to <literal>true</literal>,
4046         meaning that the next <function>nextval</function> will advance the sequence
4047         before returning a value.  In the three-parameter form,
4048         <literal>is_called</literal> may be set either <literal>true</literal> or
4049         <literal>false</literal>.  If it's set to <literal>false</literal>,
4050         the next <function>nextval</function> will return exactly the specified
4051         value, and sequence advancement commences with the following
4052         <function>nextval</function>.  For example,
4053        </para>
4054
4055        <informalexample>
4056 <screen>
4057 SELECT setval('foo', 42);           <lineannotation>Next nextval() will return 43</lineannotation>
4058 SELECT setval('foo', 42, true);     <lineannotation>Same as above</lineannotation>
4059 SELECT setval('foo', 42, false);    <lineannotation>Next nextval() will return 42</lineannotation>
4060 </screen>
4061        </informalexample>
4062
4063        <para>
4064         The result returned by <function>setval</function> is just the value of its
4065         second argument.
4066        </para>
4067       </listitem>
4068      </varlistentry>
4069     </variablelist>
4070   </para>
4071
4072   <important>
4073    <para>
4074     To avoid blocking of concurrent transactions that obtain numbers from the
4075     same sequence, a <function>nextval</function> operation is never rolled back;
4076     that is, once a value has been fetched it is considered used, even if the
4077     transaction that did the <function>nextval</function> later aborts.  This means
4078     that aborted transactions may leave unused <quote>holes</quote> in the
4079     sequence of assigned values.  <function>setval</function> operations are never
4080     rolled back, either.
4081    </para>
4082   </important>
4083
4084   <para>
4085    If a sequence object has been created with default parameters,
4086    <function>nextval()</function> calls on it will return successive values
4087    beginning with one.  Other behaviors can be obtained by using
4088    special parameters in the <command>CREATE SEQUENCE</command> command;
4089    see its command reference page for more information.
4090   </para>
4091
4092  </sect1>
4093
4094
4095  <sect1 id="functions-conditional">
4096   <title>Conditional Expressions</title>
4097
4098   <indexterm>
4099    <primary>case</primary>
4100   </indexterm>
4101
4102   <indexterm>
4103    <primary>conditionals</primary>
4104   </indexterm>
4105
4106   <para>
4107    This section describes the <acronym>SQL</acronym>-compliant conditional expressions
4108    available in <productname>PostgreSQL</productname>.
4109   </para>
4110
4111   <tip>
4112    <para>
4113     If your needs go beyond the capabilities of these conditional
4114     expressions you might want to consider writing a stored procedure
4115     in a more expressive programming language.
4116    </para>
4117   </tip>
4118
4119   <bridgehead renderas="sect2">CASE</bridgehead>
4120
4121 <synopsis>
4122 CASE WHEN <replaceable>condition</replaceable> THEN <replaceable>result</replaceable>
4123      <optional>WHEN ...</optional>
4124      <optional>ELSE <replaceable>result</replaceable></optional>
4125 END
4126 </synopsis>
4127
4128   <para>
4129    The <acronym>SQL</acronym> <token>CASE</token> expression is a
4130    generic conditional expression, similar to if/else statements in
4131    other languages.  <token>CASE</token> clauses can be used wherever
4132    an expression is valid.  <replaceable>condition</replaceable> is an
4133    expression that returns a <type>boolean</type> result.  If the result is true
4134    then the value of the <token>CASE</token> expression is
4135    <replaceable>result</replaceable>.  If the result is false any
4136    subsequent <token>WHEN</token> clauses are searched in the same
4137    manner.  If no <token>WHEN</token>
4138    <replaceable>condition</replaceable> is true then the value of the
4139    case expression is the <replaceable>result</replaceable> in the
4140    <token>ELSE</token> clause.  If the <token>ELSE</token> clause is
4141    omitted and no condition matches, the result is NULL.
4142   </para>
4143
4144   <informalexample>
4145    <para>
4146     An example:
4147 <screen>
4148 <prompt>=&gt;</prompt> <userinput>SELECT * FROM test;</userinput>
4149 <computeroutput>
4150  a
4151 ---
4152  1
4153  2
4154  3
4155 </computeroutput>
4156
4157 <prompt>=&gt;</prompt> <userinput>SELECT a,
4158           CASE WHEN a=1 THEN 'one'
4159                WHEN a=2 THEN 'two'
4160                ELSE 'other'
4161           END
4162     FROM test;</userinput>
4163 <computeroutput>
4164  a | case
4165 ---+-------
4166  1 | one
4167  2 | two
4168  3 | other
4169 </computeroutput>
4170 </screen>
4171    </para>
4172   </informalexample>
4173
4174   <para>
4175    The data types of all the <replaceable>result</replaceable>
4176    expressions must be coercible to a single output type.
4177    See <xref linkend="typeconv-union-case"> for more detail.
4178   </para>
4179
4180 <synopsis>
4181 CASE <replaceable>expression</replaceable>
4182     WHEN <replaceable>value</replaceable> THEN <replaceable>result</replaceable>
4183     <optional>WHEN ...</optional>
4184     <optional>ELSE <replaceable>result</replaceable></optional>
4185 END
4186 </synopsis>
4187
4188   <para>
4189    This <quote>simple</quote> <token>CASE</token> expression is a
4190    specialized variant of the general form above.  The
4191    <replaceable>expression</replaceable> is computed and compared to
4192    all the <replaceable>value</replaceable>s in the
4193    <token>WHEN</token> clauses until one is found that is equal.  If
4194    no match is found, the <replaceable>result</replaceable> in the
4195    <token>ELSE</token> clause (or NULL) is returned.  This is similar
4196    to the <function>switch</function> statement in C.
4197   </para>
4198
4199   <informalexample>
4200    <para>
4201     The example above can be written using the simple
4202     <token>CASE</token> syntax:
4203 <screen>
4204 <prompt>=&gt;</prompt> <userinput>SELECT a,
4205           CASE a WHEN 1 THEN 'one'
4206                  WHEN 2 THEN 'two'
4207                  ELSE 'other'
4208           END
4209     FROM test;</userinput>
4210 <computeroutput>
4211  a | case
4212 ---+-------
4213  1 | one
4214  2 | two
4215  3 | other
4216 </computeroutput>
4217 </screen>
4218     </para>
4219    </informalexample>
4220
4221    <bridgehead renderas="sect2">COALESCE</bridgehead>
4222
4223 <synopsis>
4224 <function>COALESCE</function>(<replaceable>value</replaceable><optional
4225      >, ...</optional>)
4226 </synopsis>
4227
4228   <para>
4229    The <function>COALESCE</function> function returns the first of its
4230    arguments that is not NULL.  This is often useful to substitute a
4231    default value for NULL values when data is retrieved for display,
4232    for example:
4233 <programlisting>
4234 SELECT COALESCE(description, short_description, '(none)') ...
4235 </programlisting>
4236   </para>
4237
4238  <bridgehead renderas="sect2">NULLIF</bridgehead>
4239
4240   <indexterm>
4241    <primary>nullif</primary>
4242   </indexterm>
4243
4244 <synopsis>
4245 <function>NULLIF</function>(<replaceable>value1</replaceable>,
4246     <replaceable>value2</replaceable>)
4247 </synopsis>
4248
4249   <para>
4250    The <function>NULLIF</function> function returns NULL if and only
4251    if <replaceable>value1</replaceable> and
4252    <replaceable>value2</replaceable> are equal.  Otherwise it returns
4253    <replaceable>value1</replaceable>.  This can be used to perform the
4254    inverse operation of the <function>COALESCE</function> example
4255    given above:
4256 <programlisting>
4257 SELECT NULLIF(value, '(none)') ...
4258 </programlisting>
4259   </para>
4260
4261   <tip>
4262    <para>
4263     <function>COALESCE</function> and <function>NULLIF</function> are
4264     just shorthand for <token>CASE</token> expressions.  They are actually
4265     converted into <token>CASE</token> expressions at a very early stage
4266     of processing, and subsequent processing thinks it is dealing with
4267     <token>CASE</token>.  Thus an incorrect <function>COALESCE</function> or
4268     <function>NULLIF</function> usage may draw an error message that
4269     refers to <token>CASE</token>.
4270    </para>
4271   </tip>
4272
4273  </sect1>
4274
4275
4276   <sect1 id="functions-misc">
4277    <title>Miscellaneous Functions</title>
4278
4279    <table>
4280     <title>Session Information Functions</title>
4281     <tgroup cols="3">
4282      <thead>
4283       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4284      </thead>
4285
4286      <tbody>
4287       <row>
4288        <entry><function>current_user</function></entry>
4289        <entry><type>name</type></entry>
4290        <entry>user name of current execution context</entry>
4291       </row>
4292       <row>
4293        <entry><function>session_user</function></entry>
4294        <entry><type>name</type></entry>
4295        <entry>session user name</entry>
4296       </row>
4297       <row>
4298        <entry><function>user</function></entry>
4299        <entry><type>name</type></entry>
4300        <entry>equivalent to <function>current_user</function></entry>
4301       </row>
4302       <row>
4303        <entry><function>current_schema()</function></entry>
4304        <entry><type>name</type></entry>
4305        <entry>name of current schema</entry>
4306       </row>
4307       <row>
4308        <entry><function>current_schemas()</function></entry>
4309        <entry><type>name[]</type></entry>
4310        <entry>names of schemas in search path</entry>
4311       </row>
4312      </tbody>
4313     </tgroup>
4314    </table>
4315
4316    <indexterm zone="functions-misc">
4317     <primary>user</primary>
4318     <secondary>current</secondary>
4319    </indexterm>
4320
4321    <indexterm zone="functions-misc">
4322     <primary>schema</primary>
4323     <secondary>current</secondary>
4324    </indexterm>
4325
4326    <indexterm zone="functions-misc">
4327     <primary>search path</primary>
4328     <secondary>current</secondary>
4329    </indexterm>
4330
4331    <para>
4332     The <function>session_user</function> is the user that initiated a
4333     database connection; it is fixed for the duration of that
4334     connection. The <function>current_user</function> is the user identifier
4335     that is applicable for permission checking. Normally, it is equal
4336     to the session user, but it changes during the execution of
4337     functions with the attribute <literal>SECURITY DEFINER</literal>.
4338     In Unix parlance, the session user is the <quote>real user</quote> and
4339     the current user is the <quote>effective user</quote>.
4340    </para>
4341
4342    <note>
4343     <para>
4344      <function>current_user</function>, <function>session_user</function>, and
4345      <function>user</function> have special syntactic status in <acronym>SQL</acronym>:
4346      they must be called without trailing parentheses.
4347     </para>
4348    </note>
4349
4350    <note>
4351     <title>Deprecated</title>
4352     <para>
4353      The function <function>getpgusername()</function> is an obsolete equivalent
4354      of <function>current_user</function>.
4355     </para>
4356    </note>
4357
4358    <para>
4359     <function>current_schema</function> returns the name of the schema that is
4360     at the front of the search path (or NULL if the search path is
4361     empty).  This is the schema that will be used for any tables or
4362     other named objects that are created without specifying a target schema.
4363     <function>current_schemas</function> returns an array of the names of all
4364     schemas presently in the search path.  Note that these functions show
4365     only schemas that are explicitly part of the path; when a system schema
4366     is being searched implicitly, it is not listed.
4367    </para>
4368
4369    <table>
4370     <title>System Information Functions</title>
4371     <tgroup cols="3">
4372      <thead>
4373       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4374      </thead>
4375
4376      <tbody>
4377       <row>
4378        <entry><function>version</function></entry>
4379        <entry><type>text</type></entry>
4380        <entry>PostgreSQL version information</entry>
4381       </row>
4382      </tbody>
4383     </tgroup>
4384    </table>
4385
4386    <indexterm zone="functions-misc">
4387     <primary>version</primary>
4388    </indexterm>
4389
4390    <para>
4391     <function>version()</function> returns a string describing the PostgreSQL
4392     server's version.
4393    </para>
4394
4395    <table>
4396     <title>Access Privilege Inquiry Functions</title>
4397     <tgroup cols="3">
4398      <thead>
4399       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4400      </thead>
4401
4402      <tbody>
4403       <row>
4404        <entry><function>has_table_privilege</function>(<parameter>user</parameter>,
4405                                   <parameter>table</parameter>,
4406                                   <parameter>access</parameter>)
4407        </entry>
4408        <entry><type>boolean</type></entry>
4409        <entry>does user have access to table</entry>
4410       </row>
4411       <row>
4412        <entry><function>has_table_privilege</function>(<parameter>table</parameter>,
4413                                   <parameter>access</parameter>)
4414        </entry>
4415        <entry><type>boolean</type></entry>
4416        <entry>does current user have access to table</entry>
4417       </row>
4418      </tbody>
4419     </tgroup>
4420    </table>
4421
4422    <indexterm zone="functions-misc">
4423     <primary>has_table_privilege</primary>
4424    </indexterm>
4425
4426    <para>
4427     <function>has_table_privilege</function> determines whether a user
4428     can access a table in a particular way.  The user can be
4429     specified by name or by ID
4430     (<classname>pg_user</classname>.<structfield>usesysid</structfield>), or if the argument is
4431     omitted
4432     <function>current_user</function> is assumed.  The table can be specified
4433     by name or by OID.  (Thus, there are actually six variants of
4434     <function>has_table_privilege</function>, which can be distinguished by
4435     the number and types of their arguments.)  When specifying by name,
4436     the name can be schema-qualified if necessary.
4437     The desired access type
4438     is specified by a text string, which must evaluate to one of the
4439     values <literal>SELECT</literal>, <literal>INSERT</literal>, <literal>UPDATE</literal>,
4440     <literal>DELETE</literal>, <literal>RULE</literal>, <literal>REFERENCES</literal>, or
4441     <literal>TRIGGER</literal>.  (Case of the string is not significant, however.)
4442     An example is:
4443 <programlisting>
4444 SELECT has_table_privilege('myschema.mytable', 'select');
4445 </programlisting>
4446    </para>
4447
4448    <table>
4449     <title>Catalog Information Functions</title>
4450     <tgroup cols="3">
4451      <thead>
4452       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4453      </thead>
4454
4455      <tbody>
4456       <row>
4457        <entry><function>pg_get_viewdef</function>(<parameter>viewname</parameter>)</entry>
4458        <entry><type>text</type></entry>
4459        <entry>Get CREATE VIEW command for view</entry>
4460       </row>
4461       <row>
4462        <entry><function>pg_get_viewdef</function>(<parameter>viewOID</parameter>)</entry>
4463        <entry><type>text</type></entry>
4464        <entry>Get CREATE VIEW command for view</entry>
4465       </row>
4466       <row>
4467        <entry><function>pg_get_ruledef</function>(<parameter>ruleOID</parameter>)</entry>
4468        <entry><type>text</type></entry>
4469        <entry>Get CREATE RULE command for rule</entry>
4470       </row>
4471       <row>
4472        <entry><function>pg_get_indexdef</function>(<parameter>indexOID</parameter>)</entry>
4473        <entry><type>text</type></entry>
4474        <entry>Get CREATE INDEX command for index</entry>
4475       </row>
4476       <row>
4477        <entry><function>pg_get_userbyid</function>(<parameter>userid</parameter>)</entry>
4478        <entry><type>name</type></entry>
4479        <entry>Get user name given ID</entry>
4480       </row>
4481      </tbody>
4482     </tgroup>
4483    </table>
4484
4485    <indexterm zone="functions-misc">
4486     <primary>pg_get_viewdef</primary>
4487    </indexterm>
4488
4489    <indexterm zone="functions-misc">
4490     <primary>pg_get_ruledef</primary>
4491    </indexterm>
4492
4493    <indexterm zone="functions-misc">
4494     <primary>pg_get_indexdef</primary>
4495    </indexterm>
4496
4497    <indexterm zone="functions-misc">
4498     <primary>pg_get_userbyid</primary>
4499    </indexterm>
4500
4501    <para>
4502     These functions extract information from the system catalogs.
4503     <function>pg_get_viewdef()</function>, <function>pg_get_ruledef()</function>, and
4504     <function>pg_get_indexdef()</function> respectively reconstruct the creating
4505     command for a view, rule, or index.  (Note that this is a decompiled
4506     reconstruction, not the verbatim text of the command.)
4507     <function>pg_get_userbyid()</function> extracts a user's name given a
4508     <structfield>usesysid</structfield> value.
4509    </para>
4510
4511    <table>
4512     <title>Comment Information Functions</title>
4513     <tgroup cols="3">
4514      <thead>
4515       <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
4516      </thead>
4517
4518      <tbody>
4519       <row>
4520        <entry><function>obj_description</function>(<parameter>objectOID</parameter>, <parameter>tablename</parameter>)</entry>
4521        <entry><type>text</type></entry>
4522        <entry>Get comment for a database object</entry>
4523       </row>
4524       <row>
4525        <entry><function>obj_description</function>(<parameter>objectOID</parameter>)</entry>
4526        <entry><type>text</type></entry>
4527        <entry>Get comment for a database object (<emphasis>deprecated</emphasis>)</entry>
4528       </row>
4529       <row>
4530        <entry><function>col_description</function>(<parameter>tableOID</parameter>, <parameter>columnnumber</parameter>)</entry>
4531        <entry><type>text</type></entry>
4532        <entry>Get comment for a table column</entry>
4533       </row>
4534      </tbody>
4535     </tgroup>
4536    </table>
4537
4538    <indexterm zone="functions-misc">
4539     <primary>obj_description</primary>
4540    </indexterm>
4541
4542    <indexterm zone="functions-misc">
4543     <primary>col_description</primary>
4544    </indexterm>
4545
4546    <para>
4547     These functions extract comments previously stored with the
4548     <command>COMMENT</command> command.  <literal>NULL</literal> is returned if
4549     no comment can be found matching the specified parameters.
4550    </para>
4551
4552    <para>
4553     The two-parameter form of <function>obj_description()</function> returns the
4554     comment for a database object specified by its OID and the name of the
4555     containing system catalog.  For example,
4556     <literal>obj_description(123456,'pg_class')</literal>
4557     would retrieve the comment for a table with OID 123456.
4558     The one-parameter form of <function>obj_description()</function> requires only
4559     the object OID.  It is now deprecated since there is no guarantee that
4560     OIDs are unique across different system catalogs; therefore, the wrong
4561     comment could be returned.
4562    </para>
4563
4564    <para>
4565     <function>col_description()</function> returns the comment for a table column,
4566     which is specified by the OID of its table and its column number.
4567     <function>obj_description()</function> cannot be used for table columns since
4568     columns do not have OIDs of their own.
4569    </para>
4570
4571   </sect1>
4572
4573
4574  <sect1 id="functions-aggregate">
4575   <title>Aggregate Functions</title>
4576
4577   <note>
4578    <title>Author</title>
4579    <para>
4580     Written by Isaac Wilcox <email>isaac@azartmedia.com</email> on 2000-06-16
4581    </para>
4582   </note>
4583
4584   <para>
4585    <firstterm>Aggregate functions</firstterm> compute a single result
4586    value from a set of input values.  The special syntax
4587    considerations for aggregate functions are explained in <xref
4588                                                                  linkend="syntax-aggregates">.  Consult the <citetitle>PostgreSQL
4589    Tutorial</citetitle> for additional introductory information.
4590   </para>
4591
4592   <table tocentry="1">
4593    <title>Aggregate Functions</title>
4594
4595    <tgroup cols="3">
4596     <thead>
4597      <row>
4598       <entry>Function</entry>
4599       <entry>Description</entry>
4600       <entry>Notes</entry>
4601      </row>
4602     </thead>
4603
4604     <tbody>
4605      <row>
4606       <entry>avg(<replaceable class="parameter">expression</replaceable>)</entry>
4607       <entry>the average (arithmetic mean) of all input values</entry>
4608       <entry>
4609        <indexterm>
4610         <primary>average</primary>
4611         <secondary>function</secondary>
4612        </indexterm>
4613        Finding the average value is available on the following data
4614        types: <type>smallint</type>, <type>integer</type>,
4615        <type>bigint</type>, <type>real</type>, <type>double
4616        precision</type>, <type>numeric</type>, <type>interval</type>.
4617        The result is of type <type>numeric</type> for any integer type
4618        input, <type>double precision</type> for floating-point input,
4619        otherwise the same as the input data type.
4620       </entry>
4621      </row>
4622
4623      <row>
4624       <entry><function>count</function>(*)</entry>
4625       <entry>number of input values</entry>
4626       <entry>The return value is of type <type>bigint</type>.</entry>
4627      </row>
4628
4629      <row>
4630       <entry><function>count</function>(<replaceable class="parameter">expression</replaceable>)</entry>
4631       <entry>
4632        Counts the input values for which the value of <replaceable
4633                                                                    class="parameter">expression</replaceable> is not NULL.
4634       </entry>
4635       <entry>The return value is of type <type>bigint</type>.</entry>
4636      </row>
4637
4638      <row>
4639       <entry><function>max</function>(<replaceable class="parameter">expression</replaceable>)</entry>
4640       <entry>the maximum value of <replaceable class="parameter">expression</replaceable> across all input values</entry>
4641       <entry>
4642        Available for all numeric, string, and date/time types.  The
4643        result has the same type as the input expression.
4644       </entry>
4645      </row>
4646
4647      <row>
4648       <entry><function>min</function>(<replaceable class="parameter">expression</replaceable>)</entry>
4649       <entry>the minimum value of <replaceable class="parameter">expression</replaceable> across all input values</entry>
4650       <entry>
4651        Available for all numeric, string, and date/time types.  The
4652        result has the same type as the input expression.
4653       </entry>
4654      </row>
4655
4656      <row>
4657       <entry><function>stddev</function>(<replaceable
4658                                                       class="parameter">expression</replaceable>)</entry>
4659       <entry>the sample standard deviation of the input values</entry>
4660       <entry>
4661        <indexterm>
4662         <primary>standard deviation</primary>
4663        </indexterm>
4664        Finding the standard deviation is available on the following
4665        data types: <type>smallint</type>, <type>integer</type>,
4666        <type>bigint</type>, <type>real</type>, <type>double
4667        precision</type>, <type>numeric</type>.  The result is of type
4668        <type>double precision</type> for floating-point input,
4669        otherwise <type>numeric</type>.
4670       </entry>
4671      </row>
4672
4673      <row>
4674       <entry><function>sum</function>(<replaceable class="parameter">expression</replaceable>)</entry>
4675       <entry>sum of <replaceable class="parameter">expression</replaceable> across all input values</entry>
4676       <entry>
4677        Summation is available on the following data types:
4678        <type>smallint</type>, <type>integer</type>,
4679        <type>bigint</type>, <type>real</type>, <type>double
4680        precision</type>, <type>numeric</type>, <type>interval</type>.
4681        The result is of type <type>bigint</type> for <type>smallint</type>
4682        or <type>integer</type> input, <type>numeric</type> for
4683        <type>bigint</type> 
4684        input, <type>double precision</type> for floating-point input,
4685        otherwise the same as the input data type.
4686       </entry>
4687      </row>
4688
4689      <row>
4690       <entry><function>variance</function>(<replaceable
4691                                                         class="parameter">expression</replaceable>)</entry>
4692       <entry>the sample variance of the input values</entry>
4693       <entry>
4694        <indexterm>
4695         <primary>variance</primary>
4696        </indexterm>
4697        The variance is the square of the standard deviation.  The
4698        supported data types and result types are the same as for
4699        standard deviation.
4700       </entry>
4701      </row>
4702
4703     </tbody>
4704    </tgroup>
4705   </table>
4706
4707   <para>
4708    It should be noted that except for <function>COUNT</function>,
4709    these functions return NULL when no rows are selected.  In
4710    particular, <function>SUM</function> of no rows returns NULL, not
4711    zero as one might expect.  <function>COALESCE</function> may be
4712    used to substitute zero for NULL when necessary.
4713   </para>
4714
4715  </sect1>
4716
4717
4718  <sect1 id="functions-subquery">
4719   <title>Subquery Expressions</title>
4720
4721   <indexterm>
4722    <primary>exists</primary>
4723   </indexterm>
4724
4725   <indexterm>
4726    <primary>in</primary>
4727   </indexterm>
4728
4729   <indexterm>
4730    <primary>not in</primary>
4731   </indexterm>
4732
4733   <indexterm>
4734    <primary>any</primary>
4735   </indexterm>
4736
4737   <indexterm>
4738    <primary>all</primary>
4739   </indexterm>
4740
4741   <indexterm>
4742    <primary>some</primary>
4743   </indexterm>
4744
4745   <indexterm>
4746    <primary>subqueries</primary>
4747   </indexterm>
4748
4749   <para>
4750    This section describes the <acronym>SQL</acronym>-compliant subquery
4751    expressions available in <productname>PostgreSQL</productname>.
4752    All of the expression forms documented in this section return
4753    Boolean (true/false) results.
4754   </para>
4755
4756   <bridgehead renderas="sect2">EXISTS</bridgehead>
4757
4758 <synopsis>
4759 EXISTS ( <replaceable>subquery</replaceable> )
4760 </synopsis>
4761
4762   <para>
4763    The argument of <token>EXISTS</token> is an arbitrary SELECT statement,
4764    or <firstterm>subquery</firstterm>.  The
4765    subquery is evaluated to determine whether it returns any rows.
4766    If it returns at least one row, the result of <token>EXISTS</token> is
4767    TRUE; if the subquery returns no rows, the result of <token>EXISTS</token> 
4768    is FALSE.
4769   </para>
4770
4771   <para>
4772    The subquery can refer to variables from the surrounding query,
4773    which will act as constants during any one evaluation of the subquery.
4774   </para>
4775
4776   <para>
4777    The subquery will generally only be executed far enough to determine
4778    whether at least one row is returned, not all the way to completion.
4779    It is unwise to write a subquery that has any side-effects (such as
4780    calling sequence functions); whether the side-effects occur or not
4781    may be difficult to predict.
4782   </para>
4783
4784   <para>
4785    Since the result depends only on whether any rows are returned,
4786    and not on the contents of those rows, the output list of the
4787    subquery is normally uninteresting.  A common coding convention is
4788    to write all EXISTS tests in the form
4789    <literal>EXISTS(SELECT 1 WHERE ...)</literal>.  There are exceptions to
4790    this rule however, such as subqueries that use <token>INTERSECT</token>.
4791   </para>
4792
4793   <para>
4794    This simple example is like an inner join on col2, but it produces at
4795    most one output row for each tab1 row, even if there are multiple matching
4796    tab2 rows:
4797 <screen>
4798 SELECT col1 FROM tab1
4799     WHERE EXISTS(SELECT 1 FROM tab2 WHERE col2 = tab1.col2);
4800 </screen>
4801   </para>
4802
4803    <bridgehead renderas="sect2">IN (scalar form)</bridgehead>
4804
4805 <synopsis>
4806 <replaceable>expression</replaceable> IN
4807  <replaceable>ble>value</replaceable><optional>, ...</optional>)
4808 </synopsis>
4809
4810   <para>
4811    The right-hand side of this form of <token>IN</token> is a parenthesized list
4812    of scalar expressions.  The result is TRUE if the left-hand expression's
4813    result is equal to any of the right-hand expressions.  This is a shorthand
4814    notation for
4815
4816 <synopsis>
4817 <replaceable>expression</replaceable> = <replaceable>value1</replaceable>
4818 OR
4819 <replaceable>expression</replaceable> = <replaceable>value2</replaceable>
4820 OR
4821 ...
4822 </synopsis>
4823
4824    Note that if the left-hand expression yields NULL, or if there are
4825    no equal right-hand values and at least one right-hand expression yields
4826    NULL, the result of the <token>IN</token> construct will be NULL, not FALSE.
4827    This is in accordance with SQL's normal rules for Boolean combinations
4828    of NULL values.
4829   </para>
4830
4831   <note>
4832   <para>
4833    This form of <token>IN</token> is not truly a subquery expression, but it
4834    seems best to document it in the same place as subquery <token>IN</token>.
4835   </para>
4836   </note>
4837
4838    <bridgehead renderas="sect2">IN (subquery form)</bridgehead>
4839
4840 <synopsis>
4841 <replaceable>expression</replaceable> IN (<replaceable>subquery</replaceable>)
4842 </synopsis>
4843
4844   <para>
4845    The right-hand side of this form of <token>IN</token> is a parenthesized
4846    subquery, which must return exactly one column.  The left-hand expression
4847    is evaluated and compared to each row of the subquery result.
4848    The result of <token>IN</token> is TRUE if any equal subquery row is found.
4849    The result is FALSE if no equal row is found (including the special
4850    case where the subquery returns no rows).
4851   </para>
4852
4853   <para>
4854    Note that if the left-hand expression yields NULL, or if there are
4855    no equal right-hand values and at least one right-hand row yields
4856    NULL, the result of the <token>IN</token> construct will be NULL, not FALSE.
4857    This is in accordance with SQL's normal rules for Boolean combinations
4858    of NULL values.
4859   </para>
4860
4861   <para>
4862    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
4863    be evaluated completely.
4864   </para>
4865
4866 <synopsis>
4867 (<replaceable>expression</replaceable>,
4868 <replaceable>ble>expres</replaceable><optional>nal>,</optional>nal>)
4869     IN (<replaceable>subquery</replaceable>)
4870 </synopsis>
4871
4872   <para>
4873    The right-hand side of this form of <token>IN</token> is a parenthesized
4874    subquery, which must return exactly as many columns as there are
4875    expressions in the left-hand list.  The left-hand expressions are
4876    evaluated and compared row-wise to each row of the subquery result.
4877    The result of <token>IN</token> is TRUE if any equal subquery row is found.
4878    The result is FALSE if no equal row is found (including the special
4879    case where the subquery returns no rows).
4880   </para>
4881
4882   <para>
4883    As usual, NULLs in the expressions or subquery rows are combined per
4884    the normal rules of SQL Boolean expressions.  Two rows are considered
4885    equal if all their corresponding members are non-null and equal; the rows
4886    are unequal if any corresponding members are non-null and unequal;
4887    otherwise the result of that row comparison is unknown (NULL).
4888    If all the row results are either unequal or NULL, with at least one NULL,
4889    then the result of <token>IN</token> is NULL.
4890   </para>
4891
4892    <bridgehead renderas="sect2">NOT IN (scalar form)</bridgehead>
4893
4894 <synopsis>
4895 <replaceable>expression</replaceable> NOT IN
4896  <replaceable>ble>value</replaceable><optional>, ...</optional>)
4897 </synopsis>
4898
4899   <para>
4900    The right-hand side of this form of <token>NOT IN</token> is a parenthesized list
4901    of scalar expressions.  The result is TRUE if the left-hand expression's
4902    result is unequal to all of the right-hand expressions.  This is a shorthand
4903    notation for
4904
4905 <synopsis>
4906 <replaceable>expression</replaceable> &lt;&gt; <replaceable>value1</replaceable>
4907 AND
4908 <replaceable>expression</replaceable> &lt;&gt; <replaceable>value2</replaceable>
4909 AND
4910 ...
4911 </synopsis>
4912
4913    Note that if the left-hand expression yields NULL, or if there are
4914    no equal right-hand values and at least one right-hand expression yields
4915    NULL, the result of the <token>NOT IN</token> construct will be NULL, not TRUE
4916    as one might naively expect.
4917    This is in accordance with SQL's normal rules for Boolean combinations
4918    of NULL values.
4919   </para>
4920
4921   <tip>
4922   <para>
4923    <literal>x NOT IN y</literal> is equivalent to <literal>NOT (x IN y)</literal> in all
4924    cases.  However, NULLs are much more likely to trip up the novice when
4925    working with <token>NOT IN</token> than when working with <token>IN</token>.
4926    It's best to express your condition positively if possible.
4927   </para>
4928   </tip>
4929
4930    <bridgehead renderas="sect2">NOT IN (subquery form)</bridgehead>
4931
4932 <synopsis>
4933 <replaceable>expression</replaceable> NOT IN (<replaceable>subquery</replaceable>)
4934 </synopsis>
4935
4936   <para>
4937    The right-hand side of this form of <token>NOT IN</token> is a parenthesized
4938    subquery, which must return exactly one column.  The left-hand expression
4939    is evaluated and compared to each row of the subquery result.
4940    The result of <token>NOT IN</token> is TRUE if only unequal subquery rows
4941    are found (including the special case where the subquery returns no rows).
4942    The result is FALSE if any equal row is found.
4943   </para>
4944
4945   <para>
4946    Note that if the left-hand expression yields NULL, or if there are
4947    no equal right-hand values and at least one right-hand row yields
4948    NULL, the result of the <token>NOT IN</token> construct will be NULL, not TRUE.
4949    This is in accordance with SQL's normal rules for Boolean combinations
4950    of NULL values.
4951   </para>
4952
4953   <para>
4954    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
4955    be evaluated completely.
4956   </para>
4957
4958 <synopsis>
4959 (<replaceable>expression</replaceable>,
4960 <replaceable>ble>expres</replaceable><optional>nal>,</optional>nal>)
4961     NOT IN (<replaceable>subquery</replaceable>)
4962 </synopsis>
4963
4964   <para>
4965    The right-hand side of this form of <token>NOT IN</token> is a parenthesized
4966    subquery, which must return exactly as many columns as there are
4967    expressions in the left-hand list.  The left-hand expressions are
4968    evaluated and compared row-wise to each row of the subquery result.
4969    The result of <token>NOT IN</token> is TRUE if only unequal subquery rows
4970    are found (including the special case where the subquery returns no rows).
4971    The result is FALSE if any equal row is found.
4972   </para>
4973
4974   <para>
4975    As usual, NULLs in the expressions or subquery rows are combined per
4976    the normal rules of SQL Boolean expressions.  Two rows are considered
4977    equal if all their corresponding members are non-null and equal; the rows
4978    are unequal if any corresponding members are non-null and unequal;
4979    otherwise the result of that row comparison is unknown (NULL).
4980    If all the row results are either unequal or NULL, with at least one NULL,
4981    then the result of <token>NOT IN</token> is NULL.
4982   </para>
4983
4984    <bridgehead renderas="sect2">ANY</bridgehead>
4985
4986 <synopsis>
4987 <replaceable>expression</replaceable>
4988 <replaceable>ble>oper</replaceable>ble> ANY (<replaceable>subquery</replaceable>)
4989 <replaceable>expression</replaceable>
4990 <replaceable>ble>oper</replaceable>ble> SOME (<replaceable>subquery</replaceable>)
4991 </synopsis>
4992
4993   <para>
4994    The right-hand side of this form of <token>ANY</token> is a parenthesized
4995    subquery, which must return exactly one column.  The left-hand expression
4996    is evaluated and compared to each row of the subquery result using the
4997    given <replaceable>operator</replaceable>, which must yield a Boolean
4998    result.
4999    The result of <token>ANY</token> is TRUE if any true result is obtained.
5000    The result is FALSE if no true result is found (including the special
5001    case where the subquery returns no rows).
5002   </para>
5003
5004   <para>
5005    <token>SOME</token> is a synonym for <token>ANY</token>.
5006    <token>IN</token> is equivalent to <literal>= ANY</literal>.
5007   </para>
5008
5009   <para>
5010    Note that if there are no successes and at least one right-hand row yields
5011    NULL for the operator's result, the result of the <token>ANY</token> construct
5012    will be NULL, not FALSE.
5013    This is in accordance with SQL's normal rules for Boolean combinations
5014    of NULL values.
5015   </para>
5016
5017   <para>
5018    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
5019    be evaluated completely.
5020   </para>
5021
5022 <synopsis>
5023 (<replaceable>expression</replaceable>,
5024 <replaceable>ble>expres</replaceable><optional>nal>,</optional>optiona<replaceable>aceable></replaceable>aceable> ANY (<replaceable>subquery</replaceable>)
5025 (<replaceable>expression</replaceable>,
5026 <replaceable>ble>expres</replaceable><optional>nal>,</optional>optiona<replaceable>aceable></replaceable>aceable> SOME (<replaceable>subquery</replaceable>)
5027 </synopsis>
5028
5029   <para>
5030    The right-hand side of this form of <token>ANY</token> is a parenthesized
5031    subquery, which must return exactly as many columns as there are
5032    expressions in the left-hand list.  The left-hand expressions are
5033    evaluated and compared row-wise to each row of the subquery result,
5034    using the given <replaceable>operator</replaceable>.  Presently,
5035    only <literal>=</literal> and <literal>&lt;&gt;</literal> operators are allowed
5036    in row-wise <token>ANY</token> queries.
5037    The result of <token>ANY</token> is TRUE if any equal or unequal row is
5038    found, respectively.
5039    The result is FALSE if no such row is found (including the special
5040    case where the subquery returns no rows).
5041   </para>
5042
5043   <para>
5044    As usual, NULLs in the expressions or subquery rows are combined per
5045    the normal rules of SQL Boolean expressions.  Two rows are considered
5046    equal if all their corresponding members are non-null and equal; the rows
5047    are unequal if any corresponding members are non-null and unequal;
5048    otherwise the result of that row comparison is unknown (NULL).
5049    If there is at least one NULL row result, then the result of <token>ANY</token>
5050    cannot be FALSE; it will be TRUE or NULL. 
5051   </para>
5052
5053    <bridgehead renderas="sect2">ALL</bridgehead>
5054
5055 <synopsis>
5056 <replaceable>expression</replaceable>
5057 <replaceable>ble>oper</replaceable>ble> ALL (<replaceable>subquery</replaceable>)
5058 </synopsis>
5059
5060   <para>
5061    The right-hand side of this form of <token>ALL</token> is a parenthesized
5062    subquery, which must return exactly one column.  The left-hand expression
5063    is evaluated and compared to each row of the subquery result using the
5064    given <replaceable>operator</replaceable>, which must yield a Boolean
5065    result.
5066    The result of <token>ALL</token> is TRUE if all rows yield TRUE
5067    (including the special case where the subquery returns no rows).
5068    The result is FALSE if any false result is found.
5069   </para>
5070
5071   <para>
5072    <token>NOT IN</token> is equivalent to <literal>&lt;&gt; ALL</literal>.
5073   </para>
5074
5075   <para>
5076    Note that if there are no failures but at least one right-hand row yields
5077    NULL for the operator's result, the result of the <token>ALL</token> construct
5078    will be NULL, not TRUE.
5079    This is in accordance with SQL's normal rules for Boolean combinations
5080    of NULL values.
5081   </para>
5082
5083   <para>
5084    As with <token>EXISTS</token>, it's unwise to assume that the subquery will
5085    be evaluated completely.
5086   </para>
5087
5088    <synopsis>
5089 (<replaceable>expression</replaceable>, <replaceable>expression</replaceable><optional>, ...</optional>) <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
5090    </synopsis>
5091
5092   <para>
5093    The right-hand side of this form of <token>ALL</token> is a parenthesized
5094    subquery, which must return exactly as many columns as there are
5095    expressions in the left-hand list.  The left-hand expressions are
5096    evaluated and compared row-wise to each row of the subquery result,
5097    using the given <replaceable>operator</replaceable>.  Presently,
5098    only <literal>=</literal> and <literal>&lt;&gt;</literal> operators are allowed
5099    in row-wise <token>ALL</token> queries.
5100    The result of <token>ALL</token> is TRUE if all subquery rows are equal
5101    or unequal, respectively (including the special
5102    case where the subquery returns no rows).
5103    The result is FALSE if any row is found to be unequal or equal,
5104    respectively.
5105   </para>
5106
5107   <para>
5108    As usual, NULLs in the expressions or subquery rows are combined per
5109    the normal rules of SQL Boolean expressions.  Two rows are considered
5110    equal if all their corresponding members are non-null and equal; the rows
5111    are unequal if any corresponding members are non-null and unequal;
5112    otherwise the result of that row comparison is unknown (NULL).
5113    If there is at least one NULL row result, then the result of <token>ALL</token>
5114    cannot be TRUE; it will be FALSE or NULL. 
5115   </para>
5116
5117    <bridgehead renderas="sect2">Row-wise comparison</bridgehead>
5118
5119    <synopsis>
5120 (<replaceable>expression</replaceable>, <replaceable>expression</replaceable><optional>, ...</optional>) <replaceable>operator</replaceable> (<replaceable>subquery</replaceable>)
5121 (<replaceable>expression</replaceable>, <replaceable>expression</replaceable><optional>, ...</optional>) <replaceable>operator</replaceable> (<replaceable>expression</replaceable> <replaceable>expression</replaceable><optional>, ...</optional>)
5122    </synopsis>
5123
5124   <para>
5125    The left-hand side is a list of scalar expressions.  The right-hand side
5126    can be either a list of scalar expressions of the same length, or a
5127    parenthesized subquery, which must return exactly as many columns as there
5128    are expressions on the left-hand side.  Furthermore, the subquery cannot
5129    return more than one row.  (If it returns zero rows, the result is taken to
5130    be NULL.)  The left-hand side is evaluated and compared row-wise to the
5131    single subquery result row, or to the right-hand expression list.
5132    Presently, only <literal>=</literal> and <literal>&lt;&gt;</literal> operators are allowed
5133    in row-wise comparisons.
5134    The result is TRUE if the two rows are equal or unequal, respectively.
5135   </para>
5136
5137   <para>
5138    As usual, NULLs in the expressions or subquery rows are combined per
5139    the normal rules of SQL Boolean expressions.  Two rows are considered
5140    equal if all their corresponding members are non-null and equal; the rows
5141    are unequal if any corresponding members are non-null and unequal;
5142    otherwise the result of the row comparison is unknown (NULL).
5143   </para>
5144
5145  </sect1>
5146
5147 </chapter>
5148
5149 <!-- Keep this comment at the end of the file
5150 Local variables:
5151 mode:sgml
5152 sgml-omittag:nil
5153 sgml-shorttag:t
5154 sgml-minimize-attributes:nil
5155 sgml-always-quote-attributes:t
5156 sgml-indent-step:1
5157 sgml-indent-data:t
5158 sgml-parent-document:nil
5159 sgml-default-dtd-file:"./reference.ced"
5160 sgml-exposed-tags:nil
5161 sgml-local-catalogs:("/usr/lib/sgml/catalog")
5162 sgml-local-ecat-files:nil
5163 End:
5164 -->