~ubuntu-branches/ubuntu/trusty/postgresql-9.3/trusty-proposed

1 by Martin Pitt
Import upstream version 9.3~beta1
1
<!-- doc/src/sgml/func.sgml -->
2
3
 <chapter id="functions">
4
  <title>Functions and Operators</title>
5
6
  <indexterm zone="functions">
7
   <primary>function</primary>
8
  </indexterm>
9
10
  <indexterm zone="functions">
11
   <primary>operator</primary>
12
  </indexterm>
13
14
  <para>
15
   <productname>PostgreSQL</productname> provides a large number of
16
   functions and operators for the built-in data types.  Users can also
17
   define their own functions and operators, as described in
18
   <xref linkend="server-programming">.  The
19
   <application>psql</application> commands <command>\df</command> and
20
   <command>\do</command> can be used to list all
21
   available functions and operators, respectively.
22
  </para>
23
24
  <para>
25
   If you are concerned about portability then note that most of
26
   the functions and operators described in this chapter, with the
27
   exception of the most trivial arithmetic and comparison operators
28
   and some explicitly marked functions, are not specified by the
29
   <acronym>SQL</acronym> standard. Some of this extended functionality
30
   is present in other <acronym>SQL</acronym> database management
31
   systems, and in many cases this functionality is compatible and
32
   consistent between the various implementations.  This chapter is also
33
   not exhaustive;  additional functions appear in relevant sections of
34
   the manual.
35
  </para>
36
37
38
  <sect1 id="functions-logical">
39
   <title>Logical Operators</title>
40
41
   <indexterm zone="functions-logical">
42
    <primary>operator</primary>
43
    <secondary>logical</secondary>
44
   </indexterm>
45
46
   <indexterm>
47
    <primary>Boolean</primary>
48
    <secondary>operators</secondary>
49
    <see>operators, logical</see>
50
   </indexterm>
51
52
   <para>
53
    The usual logical operators are available:
54
55
    <indexterm>
56
     <primary>AND (operator)</primary>
57
    </indexterm>
58
59
    <indexterm>
60
     <primary>OR (operator)</primary>
61
    </indexterm>
62
63
    <indexterm>
64
     <primary>NOT (operator)</primary>
65
    </indexterm>
66
67
    <indexterm>
68
     <primary>conjunction</primary>
69
    </indexterm>
70
71
    <indexterm>
72
     <primary>disjunction</primary>
73
    </indexterm>
74
75
    <indexterm>
76
     <primary>negation</primary>
77
    </indexterm>
78
79
    <simplelist>
80
     <member><literal>AND</></member>
81
     <member><literal>OR</></member>
82
     <member><literal>NOT</></member>
83
    </simplelist>
84
85
    <acronym>SQL</acronym> uses a three-valued logic system with true,
86
    false, and <literal>null</>, which represents <quote>unknown</quote>.
87
    Observe the following truth tables:
88
89
    <informaltable>
90
     <tgroup cols="4">
91
      <thead>
92
       <row>
93
        <entry><replaceable>a</replaceable></entry>
94
        <entry><replaceable>b</replaceable></entry>
95
        <entry><replaceable>a</replaceable> AND <replaceable>b</replaceable></entry>
96
        <entry><replaceable>a</replaceable> OR <replaceable>b</replaceable></entry>
97
       </row>
98
      </thead>
99
100
      <tbody>
101
       <row>
102
        <entry>TRUE</entry>
103
        <entry>TRUE</entry>
104
        <entry>TRUE</entry>
105
        <entry>TRUE</entry>
106
       </row>
107
108
       <row>
109
        <entry>TRUE</entry>
110
        <entry>FALSE</entry>
111
        <entry>FALSE</entry>
112
        <entry>TRUE</entry>
113
       </row>
114
115
       <row>
116
        <entry>TRUE</entry>
117
        <entry>NULL</entry>
118
        <entry>NULL</entry>
119
        <entry>TRUE</entry>
120
       </row>
121
122
       <row>
123
        <entry>FALSE</entry>
124
        <entry>FALSE</entry>
125
        <entry>FALSE</entry>
126
        <entry>FALSE</entry>
127
       </row>
128
129
       <row>
130
        <entry>FALSE</entry>
131
        <entry>NULL</entry>
132
        <entry>FALSE</entry>
133
        <entry>NULL</entry>
134
       </row>
135
136
       <row>
137
        <entry>NULL</entry>
138
        <entry>NULL</entry>
139
        <entry>NULL</entry>
140
        <entry>NULL</entry>
141
       </row>
142
      </tbody>
143
     </tgroup>
144
    </informaltable>
145
146
    <informaltable>
147
     <tgroup cols="2">
148
      <thead>
149
       <row>
150
        <entry><replaceable>a</replaceable></entry>
151
        <entry>NOT <replaceable>a</replaceable></entry>
152
       </row>
153
      </thead>
154
155
      <tbody>
156
       <row>
157
        <entry>TRUE</entry>
158
        <entry>FALSE</entry>
159
       </row>
160
161
       <row>
162
        <entry>FALSE</entry>
163
        <entry>TRUE</entry>
164
       </row>
165
166
       <row>
167
        <entry>NULL</entry>
168
        <entry>NULL</entry>
169
       </row>
170
      </tbody>
171
     </tgroup>
172
    </informaltable>
173
   </para>
174
175
   <para>
176
    The operators <literal>AND</literal> and <literal>OR</literal> are
177
    commutative, that is, you can switch the left and right operand
178
    without affecting the result.  But see <xref
179
    linkend="syntax-express-eval"> for more information about the
180
    order of evaluation of subexpressions.
181
   </para>
182
  </sect1>
183
184
  <sect1 id="functions-comparison">
185
   <title>Comparison Operators</title>
186
187
   <indexterm zone="functions-comparison">
188
    <primary>comparison</primary>
189
    <secondary>operators</secondary>
190
   </indexterm>
191
192
   <para>
193
    The usual comparison operators are available, shown in <xref
194
    linkend="functions-comparison-table">.
195
   </para>
196
197
   <table id="functions-comparison-table">
198
    <title>Comparison Operators</title>
199
    <tgroup cols="2">
200
     <thead>
201
      <row>
202
       <entry>Operator</entry>
203
       <entry>Description</entry>
204
      </row>
205
     </thead>
206
207
     <tbody>
208
      <row>
209
       <entry> <literal>&lt;</literal> </entry>
210
       <entry>less than</entry>
211
      </row>
212
213
      <row>
214
       <entry> <literal>&gt;</literal> </entry>
215
       <entry>greater than</entry>
216
      </row>
217
218
      <row>
219
       <entry> <literal>&lt;=</literal> </entry>
220
       <entry>less than or equal to</entry>
221
      </row>
222
223
      <row>
224
       <entry> <literal>&gt;=</literal> </entry>
225
       <entry>greater than or equal to</entry>
226
      </row>
227
228
      <row>
229
       <entry> <literal>=</literal> </entry>
230
       <entry>equal</entry>
231
      </row>
232
233
      <row>
234
       <entry> <literal>&lt;&gt;</literal> or <literal>!=</literal> </entry>
235
       <entry>not equal</entry>
236
      </row>
237
     </tbody>
238
    </tgroup>
239
   </table>
240
241
   <note>
242
    <para>
243
     The <literal>!=</literal> operator is converted to
244
     <literal>&lt;&gt;</literal> in the parser stage.  It is not
245
     possible to implement <literal>!=</literal> and
246
     <literal>&lt;&gt;</literal> operators that do different things.
247
    </para>
248
   </note>
249
250
   <para>
251
    Comparison operators are available for all relevant data types.
252
    All comparison operators are binary operators that
253
    return values of type <type>boolean</type>; expressions like
254
    <literal>1 &lt; 2 &lt; 3</literal> are not valid (because there is
255
    no <literal>&lt;</literal> operator to compare a Boolean value with
256
    <literal>3</literal>).
257
   </para>
258
259
   <para>
260
    <indexterm>
261
     <primary>BETWEEN</primary>
262
    </indexterm>
263
    In addition to the comparison operators, the special
264
    <token>BETWEEN</token> construct is available:
265
<synopsis>
266
<replaceable>a</replaceable> BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
267
</synopsis>
268
    is equivalent to
269
<synopsis>
270
<replaceable>a</replaceable> &gt;= <replaceable>x</replaceable> AND <replaceable>a</replaceable> &lt;= <replaceable>y</replaceable>
271
</synopsis>
272
    Notice that <token>BETWEEN</token> treats the endpoint values as included
273
    in the range.
274
    <literal>NOT BETWEEN</literal> does the opposite comparison:
275
<synopsis>
276
<replaceable>a</replaceable> NOT BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
277
</synopsis>
278
    is equivalent to
279
<synopsis>
280
<replaceable>a</replaceable> &lt; <replaceable>x</replaceable> OR <replaceable>a</replaceable> &gt; <replaceable>y</replaceable>
281
</synopsis>
282
    <indexterm>
283
     <primary>BETWEEN SYMMETRIC</primary>
284
    </indexterm>
285
    <literal>BETWEEN SYMMETRIC</> is the same as <literal>BETWEEN</>
286
    except there is no requirement that the argument to the left of
287
    <literal>AND</> be less than or equal to the argument on the right.
288
    If it is not, those two arguments are automatically swapped, so that
289
    a nonempty range is always implied.
290
   </para>
291
292
   <para>
293
    <indexterm>
294
     <primary>IS NULL</primary>
295
    </indexterm>
296
    <indexterm>
297
     <primary>IS NOT NULL</primary>
298
    </indexterm>
299
    <indexterm>
300
     <primary>ISNULL</primary>
301
    </indexterm>
302
    <indexterm>
303
     <primary>NOTNULL</primary>
304
    </indexterm>
305
    To check whether a value is or is not null, use the constructs:
306
<synopsis>
307
<replaceable>expression</replaceable> IS NULL
308
<replaceable>expression</replaceable> IS NOT NULL
309
</synopsis>
310
    or the equivalent, but nonstandard, constructs:
311
<synopsis>
312
<replaceable>expression</replaceable> ISNULL
313
<replaceable>expression</replaceable> NOTNULL
314
</synopsis>
315
    <indexterm><primary>null value</primary><secondary>comparing</secondary></indexterm>
316
   </para>
317
318
   <para>
319
    Do <emphasis>not</emphasis> write
320
    <literal><replaceable>expression</replaceable> = NULL</literal>
321
    because <literal>NULL</> is not <quote>equal to</quote>
322
    <literal>NULL</>.  (The null value represents an unknown value,
323
    and it is not known whether two unknown values are equal.) This
324
    behavior conforms to the SQL standard.
325
   </para>
326
327
  <tip>
328
   <para>
329
    Some applications might expect that
330
    <literal><replaceable>expression</replaceable> = NULL</literal>
331
    returns true if <replaceable>expression</replaceable> evaluates to
332
    the null value.  It is highly recommended that these applications
333
    be modified to comply with the SQL standard. However, if that
334
    cannot be done the <xref linkend="guc-transform-null-equals">
335
    configuration variable is available. If it is enabled,
336
    <productname>PostgreSQL</productname> will convert <literal>x =
337
    NULL</literal> clauses to <literal>x IS NULL</literal>.
338
   </para>
339
  </tip>
340
341
  <note>
342
   <para>
343
    If the <replaceable>expression</replaceable> is row-valued, then
344
    <literal>IS NULL</> is true when the row expression itself is null
345
    or when all the row's fields are null, while
346
    <literal>IS NOT NULL</> is true when the row expression itself is non-null
347
    and all the row's fields are non-null.  Because of this behavior,
348
    <literal>IS NULL</> and <literal>IS NOT NULL</> do not always return
349
    inverse results for row-valued expressions, i.e., a row-valued
350
    expression that contains both NULL and non-null values will return false
351
    for both tests.
352
    This definition conforms to the SQL standard, and is a change from the
353
    inconsistent behavior exhibited by <productname>PostgreSQL</productname>
354
    versions prior to 8.2.
355
   </para>
356
  </note>
357
358
   <para>
359
    <indexterm>
360
     <primary>IS DISTINCT FROM</primary>
361
    </indexterm>
362
    <indexterm>
363
     <primary>IS NOT DISTINCT FROM</primary>
364
    </indexterm>
365
    Ordinary comparison operators yield null (signifying <quote>unknown</>),
366
    not true or false, when either input is null.  For example,
367
    <literal>7 = NULL</> yields null, as does <literal>7 &lt;&gt; NULL</>.  When
368
    this behavior is not suitable, use the
369
    <literal>IS <optional> NOT </> DISTINCT FROM</literal> constructs:
370
<synopsis>
371
<replaceable>expression</replaceable> IS DISTINCT FROM <replaceable>expression</replaceable>
372
<replaceable>expression</replaceable> IS NOT DISTINCT FROM <replaceable>expression</replaceable>
373
</synopsis>
374
    For non-null inputs, <literal>IS DISTINCT FROM</literal> is
375
    the same as the <literal>&lt;&gt;</> operator.  However, if both
376
    inputs are null it returns false, and if only one input is
377
    null it returns true.  Similarly, <literal>IS NOT DISTINCT
378
    FROM</literal> is identical to <literal>=</literal> for non-null
379
    inputs, but it returns true when both inputs are null, and false when only
380
    one input is null. Thus, these constructs effectively act as though null
381
    were a normal data value, rather than <quote>unknown</>.
382
   </para>
383
384
   <para>
385
    <indexterm>
386
     <primary>IS TRUE</primary>
387
    </indexterm>
388
    <indexterm>
389
     <primary>IS NOT TRUE</primary>
390
    </indexterm>
391
    <indexterm>
392
     <primary>IS FALSE</primary>
393
    </indexterm>
394
    <indexterm>
395
     <primary>IS NOT FALSE</primary>
396
    </indexterm>
397
    <indexterm>
398
     <primary>IS UNKNOWN</primary>
399
    </indexterm>
400
    <indexterm>
401
     <primary>IS NOT UNKNOWN</primary>
402
    </indexterm>
403
    Boolean values can also be tested using the constructs
404
<synopsis>
405
<replaceable>expression</replaceable> IS TRUE
406
<replaceable>expression</replaceable> IS NOT TRUE
407
<replaceable>expression</replaceable> IS FALSE
408
<replaceable>expression</replaceable> IS NOT FALSE
409
<replaceable>expression</replaceable> IS UNKNOWN
410
<replaceable>expression</replaceable> IS NOT UNKNOWN
411
</synopsis>
412
    These will always return true or false, never a null value, even when the
413
    operand is null.
414
    A null input is treated as the logical value <quote>unknown</>.
415
    Notice that <literal>IS UNKNOWN</> and <literal>IS NOT UNKNOWN</> are
416
    effectively the same as <literal>IS NULL</literal> and
417
    <literal>IS NOT NULL</literal>, respectively, except that the input
418
    expression must be of Boolean type.
419
   </para>
420
421
<!-- IS OF does not conform to the ISO SQL behavior, so it is undocumented here
422
   <para>
423
    <indexterm>
424
     <primary>IS OF</primary>
425
    </indexterm>
426
    <indexterm>
427
     <primary>IS NOT OF</primary>
428
    </indexterm>
429
    It is possible to check the data type of an expression using the
430
    constructs
431
<synopsis>
432
<replaceable>expression</replaceable> IS OF (typename, ...)
433
<replaceable>expression</replaceable> IS NOT OF (typename, ...)
434
</synopsis>
435
    They return a boolean value based on whether the expression's data
436
    type is one of the listed data types.
437
   </para>
438
-->
439
440
  </sect1>
441
442
  <sect1 id="functions-math">
443
   <title>Mathematical Functions and Operators</title>
444
445
   <para>
446
    Mathematical operators are provided for many
447
    <productname>PostgreSQL</productname> types. For types without
448
    standard mathematical conventions
449
    (e.g., date/time types) we
450
    describe the actual behavior in subsequent sections.
451
   </para>
452
453
   <para>
454
    <xref linkend="functions-math-op-table"> shows the available mathematical operators.
455
   </para>
456
457
   <table id="functions-math-op-table">
458
    <title>Mathematical Operators</title>
459
460
    <tgroup cols="4">
461
     <thead>
462
      <row>
463
       <entry>Operator</entry>
464
       <entry>Description</entry>
465
       <entry>Example</entry>
466
       <entry>Result</entry>
467
      </row>
468
     </thead>
469
470
     <tbody>
471
      <row>
472
       <entry> <literal>+</literal> </entry>
473
       <entry>addition</entry>
474
       <entry><literal>2 + 3</literal></entry>
475
       <entry><literal>5</literal></entry>
476
      </row>
477
478
      <row>
479
       <entry> <literal>-</literal> </entry>
480
       <entry>subtraction</entry>
481
       <entry><literal>2 - 3</literal></entry>
482
       <entry><literal>-1</literal></entry>
483
      </row>
484
485
      <row>
486
       <entry> <literal>*</literal> </entry>
487
       <entry>multiplication</entry>
488
       <entry><literal>2 * 3</literal></entry>
489
       <entry><literal>6</literal></entry>
490
      </row>
491
492
      <row>
493
       <entry> <literal>/</literal> </entry>
494
       <entry>division (integer division truncates the result)</entry>
495
       <entry><literal>4 / 2</literal></entry>
496
       <entry><literal>2</literal></entry>
497
      </row>
498
499
      <row>
500
       <entry> <literal>%</literal> </entry>
501
       <entry>modulo (remainder)</entry>
502
       <entry><literal>5 % 4</literal></entry>
503
       <entry><literal>1</literal></entry>
504
      </row>
505
506
      <row>
507
       <entry> <literal>^</literal> </entry>
1.2.4 by Martin Pitt
Import upstream version 9.3.11
508
       <entry>exponentiation (associates left to right)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
509
       <entry><literal>2.0 ^ 3.0</literal></entry>
510
       <entry><literal>8</literal></entry>
511
      </row>
512
513
      <row>
514
       <entry> <literal>|/</literal> </entry>
515
       <entry>square root</entry>
516
       <entry><literal>|/ 25.0</literal></entry>
517
       <entry><literal>5</literal></entry>
518
      </row>
519
520
      <row>
521
       <entry> <literal>||/</literal> </entry>
522
       <entry>cube root</entry>
523
       <entry><literal>||/ 27.0</literal></entry>
524
       <entry><literal>3</literal></entry>
525
      </row>
526
527
      <row>
528
       <entry> <literal>!</literal> </entry>
529
       <entry>factorial</entry>
530
       <entry><literal>5 !</literal></entry>
531
       <entry><literal>120</literal></entry>
532
      </row>
533
534
      <row>
535
       <entry> <literal>!!</literal> </entry>
536
       <entry>factorial (prefix operator)</entry>
537
       <entry><literal>!! 5</literal></entry>
538
       <entry><literal>120</literal></entry>
539
      </row>
540
541
      <row>
542
       <entry> <literal>@</literal> </entry>
543
       <entry>absolute value</entry>
544
       <entry><literal>@ -5.0</literal></entry>
545
       <entry><literal>5</literal></entry>
546
      </row>
547
548
      <row>
549
       <entry> <literal>&amp;</literal> </entry>
550
       <entry>bitwise AND</entry>
551
       <entry><literal>91 &amp; 15</literal></entry>
552
       <entry><literal>11</literal></entry>
553
      </row>
554
555
      <row>
556
       <entry> <literal>|</literal> </entry>
557
       <entry>bitwise OR</entry>
558
       <entry><literal>32 | 3</literal></entry>
559
       <entry><literal>35</literal></entry>
560
      </row>
561
562
      <row>
563
       <entry> <literal>#</literal> </entry>
564
       <entry>bitwise XOR</entry>
565
       <entry><literal>17 # 5</literal></entry>
566
       <entry><literal>20</literal></entry>
567
      </row>
568
569
      <row>
570
       <entry> <literal>~</literal> </entry>
571
       <entry>bitwise NOT</entry>
572
       <entry><literal>~1</literal></entry>
573
       <entry><literal>-2</literal></entry>
574
      </row>
575
576
      <row>
577
       <entry> <literal>&lt;&lt;</literal> </entry>
578
       <entry>bitwise shift left</entry>
579
       <entry><literal>1 &lt;&lt; 4</literal></entry>
580
       <entry><literal>16</literal></entry>
581
      </row>
582
583
      <row>
584
       <entry> <literal>&gt;&gt;</literal> </entry>
585
       <entry>bitwise shift right</entry>
586
       <entry><literal>8 &gt;&gt; 2</literal></entry>
587
       <entry><literal>2</literal></entry>
588
      </row>
589
590
     </tbody>
591
    </tgroup>
592
   </table>
593
594
   <para>
595
    The bitwise operators work only on integral data types, whereas
596
    the others are available for all numeric data types.  The bitwise
597
    operators are also available for the bit
598
    string types <type>bit</type> and <type>bit varying</type>, as
599
    shown in <xref linkend="functions-bit-string-op-table">.
600
   </para>
601
602
  <para>
603
   <xref linkend="functions-math-func-table"> shows the available
604
   mathematical functions.  In the table, <literal>dp</literal>
605
   indicates <type>double precision</type>.  Many of these functions
606
   are provided in multiple forms with different argument types.
607
   Except where noted, any given form of a function returns the same
608
   data type as its argument.
609
   The functions working with <type>double precision</type> data are mostly
610
   implemented on top of the host system's C library; accuracy and behavior in
611
   boundary cases can therefore vary depending on the host system.
612
  </para>
613
614
   <table id="functions-math-func-table">
615
    <title>Mathematical Functions</title>
616
    <tgroup cols="5">
617
     <thead>
618
      <row>
619
       <entry>Function</entry>
620
       <entry>Return Type</entry>
621
       <entry>Description</entry>
622
       <entry>Example</entry>
623
       <entry>Result</entry>
624
      </row>
625
     </thead>
626
627
     <tbody>
628
      <row>
629
       <entry>
630
        <indexterm>
631
         <primary>abs</primary>
632
        </indexterm>
633
        <literal><function>abs(<replaceable>x</replaceable>)</function></literal>
634
       </entry>
635
       <entry>(same as input)</entry>
636
       <entry>absolute value</entry>
637
       <entry><literal>abs(-17.4)</literal></entry>
638
       <entry><literal>17.4</literal></entry>
639
      </row>
640
641
      <row>
642
       <entry>
643
        <indexterm>
644
         <primary>cbrt</primary>
645
        </indexterm>
646
        <literal><function>cbrt(<type>dp</type>)</function></literal>
647
       </entry>
648
       <entry><type>dp</type></entry>
649
       <entry>cube root</entry>
650
       <entry><literal>cbrt(27.0)</literal></entry>
651
       <entry><literal>3</literal></entry>
652
      </row>
653
654
      <row>
655
       <entry>
656
        <indexterm>
657
         <primary>ceil</primary>
658
        </indexterm>
659
        <literal><function>ceil(<type>dp</type> or <type>numeric</type>)</function></literal>
660
       </entry>
661
       <entry>(same as input)</entry>
662
       <entry>smallest integer not less than argument</entry>
663
       <entry><literal>ceil(-42.8)</literal></entry>
664
       <entry><literal>-42</literal></entry>
665
      </row>
666
667
      <row>
668
       <entry>
669
        <indexterm>
670
         <primary>ceiling</primary>
671
        </indexterm>
672
        <literal><function>ceiling(<type>dp</type> or <type>numeric</type>)</function></literal>
673
       </entry>
674
       <entry>(same as input)</entry>
675
       <entry>smallest integer not less than argument (alias for <function>ceil</function>)</entry>
676
       <entry><literal>ceiling(-95.3)</literal></entry>
677
       <entry><literal>-95</literal></entry>
678
      </row>
679
680
      <row>
681
       <entry>
682
        <indexterm>
683
         <primary>degrees</primary>
684
        </indexterm>
685
        <literal><function>degrees(<type>dp</type>)</function></literal>
686
       </entry>
687
       <entry><type>dp</type></entry>
688
       <entry>radians to degrees</entry>
689
       <entry><literal>degrees(0.5)</literal></entry>
690
       <entry><literal>28.6478897565412</literal></entry>
691
      </row>
692
693
      <row>
694
       <entry>
695
        <indexterm>
696
         <primary>div</primary>
697
        </indexterm>
698
        <literal><function>div(<parameter>y</parameter> <type>numeric</>,
699
         <parameter>x</parameter> <type>numeric</>)</function></literal>
700
       </entry>
701
       <entry><type>numeric</></entry>
702
       <entry>integer quotient of <parameter>y</parameter>/<parameter>x</parameter></entry>
703
       <entry><literal>div(9,4)</literal></entry>
704
       <entry><literal>2</literal></entry>
705
      </row>
706
707
      <row>
708
       <entry>
709
        <indexterm>
710
         <primary>exp</primary>
711
        </indexterm>
712
        <literal><function>exp(<type>dp</type> or <type>numeric</type>)</function></literal>
713
       </entry>
714
       <entry>(same as input)</entry>
715
       <entry>exponential</entry>
716
       <entry><literal>exp(1.0)</literal></entry>
717
       <entry><literal>2.71828182845905</literal></entry>
718
      </row>
719
720
      <row>
721
       <entry>
722
        <indexterm>
723
         <primary>floor</primary>
724
        </indexterm>
725
        <literal><function>floor(<type>dp</type> or <type>numeric</type>)</function></literal>
726
       </entry>
727
       <entry>(same as input)</entry>
728
       <entry>largest integer not greater than argument</entry>
729
       <entry><literal>floor(-42.8)</literal></entry>
730
       <entry><literal>-43</literal></entry>
731
      </row>
732
733
      <row>
734
       <entry>
735
        <indexterm>
736
         <primary>ln</primary>
737
        </indexterm>
738
        <literal><function>ln(<type>dp</type> or <type>numeric</type>)</function></literal>
739
       </entry>
740
       <entry>(same as input)</entry>
741
       <entry>natural logarithm</entry>
742
       <entry><literal>ln(2.0)</literal></entry>
743
       <entry><literal>0.693147180559945</literal></entry>
744
      </row>
745
746
      <row>
747
       <entry>
748
        <indexterm>
749
         <primary>log</primary>
750
        </indexterm>
751
        <literal><function>log(<type>dp</type> or <type>numeric</type>)</function></literal>
752
       </entry>
753
       <entry>(same as input)</entry>
754
       <entry>base 10 logarithm</entry>
755
       <entry><literal>log(100.0)</literal></entry>
756
       <entry><literal>2</literal></entry>
757
      </row>
758
759
      <row>
760
       <entry><literal><function>log(<parameter>b</parameter> <type>numeric</type>,
761
        <parameter>x</parameter> <type>numeric</type>)</function></literal></entry>
762
       <entry><type>numeric</type></entry>
763
       <entry>logarithm to base <parameter>b</parameter></entry>
764
       <entry><literal>log(2.0, 64.0)</literal></entry>
765
       <entry><literal>6.0000000000</literal></entry>
766
      </row>
767
768
      <row>
769
       <entry>
770
        <indexterm>
771
         <primary>mod</primary>
772
        </indexterm>
773
        <literal><function>mod(<parameter>y</parameter>,
774
         <parameter>x</parameter>)</function></literal>
775
       </entry>
776
       <entry>(same as argument types)</entry>
777
       <entry>remainder of <parameter>y</parameter>/<parameter>x</parameter></entry>
778
       <entry><literal>mod(9,4)</literal></entry>
779
       <entry><literal>1</literal></entry>
780
      </row>
781
782
      <row>
783
       <entry>
784
        <indexterm>
785
         <primary>pi</primary>
786
        </indexterm>
787
        <literal><function>pi()</function></literal>
788
       </entry>
789
       <entry><type>dp</type></entry>
790
       <entry><quote>&pi;</quote> constant</entry>
791
       <entry><literal>pi()</literal></entry>
792
       <entry><literal>3.14159265358979</literal></entry>
793
      </row>
794
795
      <row>
796
       <entry>
797
        <indexterm>
798
         <primary>power</primary>
799
        </indexterm>
800
        <literal><function>power(<parameter>a</parameter> <type>dp</type>,
801
        <parameter>b</parameter> <type>dp</type>)</function></literal>
802
       </entry>
803
       <entry><type>dp</type></entry>
804
       <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
805
       <entry><literal>power(9.0, 3.0)</literal></entry>
806
       <entry><literal>729</literal></entry>
807
      </row>
808
809
      <row>
810
       <entry><literal><function>power(<parameter>a</parameter> <type>numeric</type>,
811
        <parameter>b</parameter> <type>numeric</type>)</function></literal></entry>
812
       <entry><type>numeric</type></entry>
813
       <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
814
       <entry><literal>power(9.0, 3.0)</literal></entry>
815
       <entry><literal>729</literal></entry>
816
      </row>
817
818
      <row>
819
       <entry>
820
        <indexterm>
821
         <primary>radians</primary>
822
        </indexterm>
823
        <literal><function>radians(<type>dp</type>)</function></literal>
824
       </entry>
825
       <entry><type>dp</type></entry>
826
       <entry>degrees to radians</entry>
827
       <entry><literal>radians(45.0)</literal></entry>
828
       <entry><literal>0.785398163397448</literal></entry>
829
      </row>
830
831
      <row>
832
       <entry>
833
        <indexterm>
834
         <primary>round</primary>
835
        </indexterm>
836
        <literal><function>round(<type>dp</type> or <type>numeric</type>)</function></literal>
837
       </entry>
838
       <entry>(same as input)</entry>
839
       <entry>round to nearest integer</entry>
840
       <entry><literal>round(42.4)</literal></entry>
841
       <entry><literal>42</literal></entry>
842
      </row>
843
844
      <row>
845
       <entry><literal><function>round(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</function></literal></entry>
846
       <entry><type>numeric</type></entry>
847
       <entry>round to <parameter>s</parameter> decimal places</entry>
848
       <entry><literal>round(42.4382, 2)</literal></entry>
849
       <entry><literal>42.44</literal></entry>
850
      </row>
851
852
      <row>
853
       <entry>
854
        <indexterm>
855
         <primary>sign</primary>
856
        </indexterm>
857
        <literal><function>sign(<type>dp</type> or <type>numeric</type>)</function></literal>
858
       </entry>
859
       <entry>(same as input)</entry>
860
       <entry>sign of the argument (-1, 0, +1)</entry>
861
       <entry><literal>sign(-8.4)</literal></entry>
862
       <entry><literal>-1</literal></entry>
863
      </row>
864
865
      <row>
866
       <entry>
867
        <indexterm>
868
         <primary>sqrt</primary>
869
        </indexterm>
870
        <literal><function>sqrt(<type>dp</type> or <type>numeric</type>)</function></literal>
871
       </entry>
872
       <entry>(same as input)</entry>
873
       <entry>square root</entry>
874
       <entry><literal>sqrt(2.0)</literal></entry>
875
       <entry><literal>1.4142135623731</literal></entry>
876
      </row>
877
878
      <row>
879
       <entry>
880
        <indexterm>
881
         <primary>trunc</primary>
882
        </indexterm>
883
        <literal><function>trunc(<type>dp</type> or <type>numeric</type>)</function></literal>
884
       </entry>
885
       <entry>(same as input)</entry>
886
       <entry>truncate toward zero</entry>
887
       <entry><literal>trunc(42.8)</literal></entry>
888
       <entry><literal>42</literal></entry>
889
      </row>
890
891
      <row>
892
       <entry><literal><function>trunc(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</function></literal></entry>
893
       <entry><type>numeric</type></entry>
894
       <entry>truncate to <parameter>s</parameter> decimal places</entry>
895
       <entry><literal>trunc(42.4382, 2)</literal></entry>
896
       <entry><literal>42.43</literal></entry>
897
      </row>
898
899
      <row>
900
       <entry>
901
        <indexterm>
902
         <primary>width_bucket</primary>
903
        </indexterm>
904
        <literal><function>width_bucket(<parameter>op</parameter> <type>numeric</type>, <parameter>b1</parameter> <type>numeric</type>, <parameter>b2</parameter> <type>numeric</type>, <parameter>count</parameter> <type>int</type>)</function></literal>
905
       </entry>
906
       <entry><type>int</type></entry>
907
       <entry>return the bucket to which <parameter>operand</> would
908
       be assigned in an equidepth histogram with <parameter>count</>
909
       buckets, in the range <parameter>b1</> to <parameter>b2</></entry>
910
       <entry><literal>width_bucket(5.35, 0.024, 10.06, 5)</literal></entry>
911
       <entry><literal>3</literal></entry>
912
      </row>
913
914
      <row>
915
       <entry><literal><function>width_bucket(<parameter>op</parameter> <type>dp</type>, <parameter>b1</parameter> <type>dp</type>, <parameter>b2</parameter> <type>dp</type>, <parameter>count</parameter> <type>int</type>)</function></literal></entry>
916
       <entry><type>int</type></entry>
917
       <entry>return the bucket to which <parameter>operand</> would
918
       be assigned in an equidepth histogram with <parameter>count</>
919
       buckets, in the range <parameter>b1</> to <parameter>b2</></entry>
920
       <entry><literal>width_bucket(5.35, 0.024, 10.06, 5)</literal></entry>
921
       <entry><literal>3</literal></entry>
922
      </row>
923
     </tbody>
924
    </tgroup>
925
   </table>
926
927
  <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
928
    <xref linkend="functions-math-random-table"> shows functions for
929
    generating random numbers.
930
  </para>
931
932
   <table id="functions-math-random-table">
933
    <title>Random Functions</title>
934
935
    <tgroup cols="3">
936
     <thead>
937
      <row>
938
       <entry>Function</entry>
939
       <entry>Return Type</entry>
940
       <entry>Description</entry>
941
      </row>
942
     </thead>
943
     <tbody>
944
      <row>
945
       <entry>
946
        <indexterm>
947
         <primary>random</primary>
948
        </indexterm>
949
        <literal><function>random()</function></literal>
950
       </entry>
951
       <entry><type>dp</type></entry>
952
       <entry>random value in the range 0.0 &lt;= x &lt; 1.0</entry>
953
      </row>
954
955
      <row>
956
       <entry>
957
        <indexterm>
958
         <primary>setseed</primary>
959
        </indexterm>
960
        <literal><function>setseed(<type>dp</type>)</function></literal>
961
       </entry>
962
       <entry><type>void</type></entry>
963
       <entry>set seed for subsequent <literal>random()</literal> calls (value between -1.0 and
964
       1.0, inclusive)</entry>
965
      </row>
966
     </tbody>
967
    </tgroup>
968
   </table>
969
970
  <para>
971
   The characteristics of the values returned by
972
   <literal><function>random()</function></literal> depend
973
   on the system implementation. It is not suitable for cryptographic
974
   applications; see <xref linkend="pgcrypto"> module for an alternative.
975
   </para>
976
977
  <para>
1 by Martin Pitt
Import upstream version 9.3~beta1
978
   Finally, <xref linkend="functions-math-trig-table"> shows the
979
   available trigonometric functions.  All trigonometric functions
980
   take arguments and return values of type <type>double
981
   precision</type>. Trigonometric functions arguments are expressed
982
   in radians. Inverse functions return values are expressed in
983
   radians.  See unit transformation functions
984
   <literal><function>radians()</function></literal> and
985
   <literal><function>degrees()</function></literal> above.
986
  </para>
987
988
   <table id="functions-math-trig-table">
989
    <title>Trigonometric Functions</title>
990
991
    <tgroup cols="2">
992
     <thead>
993
      <row>
994
       <entry>Function</entry>
995
       <entry>Description</entry>
996
      </row>
997
     </thead>
998
999
     <tbody>
1000
      <row>
1001
       <entry>
1002
        <indexterm>
1003
         <primary>acos</primary>
1004
        </indexterm><literal><function>acos(<replaceable>x</replaceable>)</function></literal>
1005
       </entry>
1006
       <entry>inverse cosine</entry>
1007
      </row>
1008
1009
      <row>
1010
       <entry>
1011
        <indexterm>
1012
         <primary>asin</primary>
1013
        </indexterm>
1014
        <literal><function>asin(<replaceable>x</replaceable>)</function></literal>
1015
       </entry>
1016
       <entry>inverse sine</entry>
1017
      </row>
1018
1019
      <row>
1020
       <entry>
1021
        <indexterm>
1022
         <primary>atan</primary>
1023
        </indexterm>
1024
        <literal><function>atan(<replaceable>x</replaceable>)</function></literal>
1025
       </entry>
1026
       <entry>inverse tangent</entry>
1027
      </row>
1028
1029
      <row>
1030
       <entry>
1031
        <indexterm>
1032
         <primary>atan2</primary>
1033
        </indexterm>
1034
        <literal><function>atan2(<replaceable>y</replaceable>,
1035
        <replaceable>x</replaceable>)</function></literal>
1036
       </entry>
1037
       <entry>inverse tangent of
1038
        <literal><replaceable>y</replaceable>/<replaceable>x</replaceable></literal></entry>
1039
      </row>
1040
1041
      <row>
1042
       <entry>
1043
        <indexterm>
1044
         <primary>cos</primary>
1045
        </indexterm>
1046
        <literal><function>cos(<replaceable>x</replaceable>)</function></literal>
1047
       </entry>
1048
       <entry>cosine</entry>
1049
      </row>
1050
1051
      <row>
1052
       <entry>
1053
        <indexterm>
1054
         <primary>cot</primary>
1055
        </indexterm>
1056
        <literal><function>cot(<replaceable>x</replaceable>)</function></literal>
1057
       </entry>
1058
       <entry>cotangent</entry>
1059
      </row>
1060
1061
      <row>
1062
       <entry>
1063
        <indexterm>
1064
         <primary>sin</primary>
1065
        </indexterm>
1066
        <literal><function>sin(<replaceable>x</replaceable>)</function></literal>
1067
       </entry>
1068
       <entry>sine</entry>
1069
      </row>
1070
1071
      <row>
1072
       <entry>
1073
        <indexterm>
1074
         <primary>tan</primary>
1075
        </indexterm>
1076
        <literal><function>tan(<replaceable>x</replaceable>)</function></literal>
1077
       </entry>
1078
       <entry>tangent</entry>
1079
      </row>
1080
     </tbody>
1081
    </tgroup>
1082
   </table>
1083
1084
  </sect1>
1085
1086
1087
  <sect1 id="functions-string">
1088
   <title>String Functions and Operators</title>
1089
1090
   <para>
1091
    This section describes functions and operators for examining and
1092
    manipulating string values.  Strings in this context include values
1093
    of the types <type>character</type>, <type>character varying</type>,
1094
    and <type>text</type>.  Unless otherwise noted, all
1095
    of the functions listed below work on all of these types, but be
1096
    wary of potential effects of automatic space-padding when using the
1097
    <type>character</type> type.  Some functions also exist
1098
    natively for the bit-string types.
1099
   </para>
1100
1101
   <para>
1102
    <acronym>SQL</acronym> defines some string functions that use
1103
    key words, rather than commas, to separate
1104
    arguments.  Details are in
1105
    <xref linkend="functions-string-sql">.
1106
    <productname>PostgreSQL</> also provides versions of these functions
1107
    that use the regular function invocation syntax
1108
    (see <xref linkend="functions-string-other">).
1109
   </para>
1110
1111
   <note>
1112
    <para>
1113
     Before <productname>PostgreSQL</productname> 8.3, these functions would
1114
     silently accept values of several non-string data types as well, due to
1115
     the presence of implicit coercions from those data types to
1116
     <type>text</>.  Those coercions have been removed because they frequently
1117
     caused surprising behaviors.  However, the string concatenation operator
1118
     (<literal>||</>) still accepts non-string input, so long as at least one
1119
     input is of a string type, as shown in <xref
1120
     linkend="functions-string-sql">.  For other cases, insert an explicit
1121
     coercion to <type>text</> if you need to duplicate the previous behavior.
1122
    </para>
1123
   </note>
1124
1125
   <table id="functions-string-sql">
1126
    <title><acronym>SQL</acronym> String Functions and Operators</title>
1127
    <tgroup cols="5">
1128
     <thead>
1129
      <row>
1130
       <entry>Function</entry>
1131
       <entry>Return Type</entry>
1132
       <entry>Description</entry>
1133
       <entry>Example</entry>
1134
       <entry>Result</entry>
1135
      </row>
1136
     </thead>
1137
1138
     <tbody>
1139
      <row>
1140
       <entry><literal><parameter>string</parameter> <literal>||</literal>
1141
        <parameter>string</parameter></literal></entry>
1142
       <entry> <type>text</type> </entry>
1143
       <entry>
1144
        String concatenation
1145
        <indexterm>
1146
         <primary>character string</primary>
1147
         <secondary>concatenation</secondary>
1148
        </indexterm>
1149
       </entry>
1150
       <entry><literal>'Post' || 'greSQL'</literal></entry>
1151
       <entry><literal>PostgreSQL</literal></entry>
1152
      </row>
1153
1154
      <row>
1155
       <entry>
1156
        <literal><parameter>string</parameter> <literal>||</literal>
1157
        <parameter>non-string</parameter></literal>
1158
        or
1159
        <literal><parameter>non-string</parameter> <literal>||</literal>
1160
        <parameter>string</parameter></literal>
1161
       </entry>
1162
       <entry> <type>text</type> </entry>
1163
       <entry>
1164
        String concatenation with one non-string input
1165
       </entry>
1166
       <entry><literal>'Value: ' || 42</literal></entry>
1167
       <entry><literal>Value: 42</literal></entry>
1168
      </row>
1169
1170
      <row>
1171
       <entry>
1172
        <indexterm>
1173
         <primary>bit_length</primary>
1174
        </indexterm>
1175
        <literal><function>bit_length(<parameter>string</parameter>)</function></literal>
1176
       </entry>
1177
       <entry><type>int</type></entry>
1178
       <entry>Number of bits in string</entry>
1179
       <entry><literal>bit_length('jose')</literal></entry>
1180
       <entry><literal>32</literal></entry>
1181
      </row>
1182
1183
      <row>
1184
       <entry>
1185
        <indexterm>
1186
         <primary>char_length</primary>
1187
        </indexterm>
1188
        <literal><function>char_length(<parameter>string</parameter>)</function></literal> or <literal><function>character_length(<parameter>string</parameter>)</function></literal>
1189
       </entry>
1190
       <entry><type>int</type></entry>
1191
       <entry>
1192
        Number of characters in string
1193
        <indexterm>
1194
         <primary>character string</primary>
1195
         <secondary>length</secondary>
1196
        </indexterm>
1197
        <indexterm>
1198
         <primary>length</primary>
1199
         <secondary sortas="character string">of a character string</secondary>
1200
         <see>character string, length</see>
1201
        </indexterm>
1202
       </entry>
1203
       <entry><literal>char_length('jose')</literal></entry>
1204
       <entry><literal>4</literal></entry>
1205
      </row>
1206
1207
      <row>
1208
       <entry>
1209
        <indexterm>
1210
         <primary>lower</primary>
1211
        </indexterm>
1212
        <literal><function>lower(<parameter>string</parameter>)</function></literal>
1213
       </entry>
1214
       <entry><type>text</type></entry>
1215
       <entry>Convert string to lower case</entry>
1216
       <entry><literal>lower('TOM')</literal></entry>
1217
       <entry><literal>tom</literal></entry>
1218
      </row>
1219
1220
      <row>
1221
       <entry>
1222
        <indexterm>
1223
         <primary>octet_length</primary>
1224
        </indexterm>
1225
        <literal><function>octet_length(<parameter>string</parameter>)</function></literal>
1226
       </entry>
1227
       <entry><type>int</type></entry>
1228
       <entry>Number of bytes in string</entry>
1229
       <entry><literal>octet_length('jose')</literal></entry>
1230
       <entry><literal>4</literal></entry>
1231
      </row>
1232
1233
      <row>
1234
       <entry>
1235
        <indexterm>
1236
         <primary>overlay</primary>
1237
        </indexterm>
1238
        <literal><function>overlay(<parameter>string</parameter> placing <parameter>string</parameter> from <type>int</type> <optional>for <type>int</type></optional>)</function></literal>
1239
       </entry>
1240
       <entry><type>text</type></entry>
1241
       <entry>
1242
        Replace substring
1243
       </entry>
1244
       <entry><literal>overlay('Txxxxas' placing 'hom' from 2 for 4)</literal></entry>
1245
       <entry><literal>Thomas</literal></entry>
1246
      </row>
1247
1248
      <row>
1249
       <entry>
1250
        <indexterm>
1251
         <primary>position</primary>
1252
        </indexterm>
1253
        <literal><function>position(<parameter>substring</parameter> in <parameter>string</parameter>)</function></literal>
1254
       </entry>
1255
       <entry><type>int</type></entry>
1256
       <entry>Location of specified substring</entry>
1257
       <entry><literal>position('om' in 'Thomas')</literal></entry>
1258
       <entry><literal>3</literal></entry>
1259
      </row>
1260
1261
      <row>
1262
       <entry>
1263
        <indexterm>
1264
         <primary>substring</primary>
1265
        </indexterm>
1266
        <literal><function>substring(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</function></literal>
1267
       </entry>
1268
       <entry><type>text</type></entry>
1269
       <entry>
1270
        Extract substring
1271
       </entry>
1272
       <entry><literal>substring('Thomas' from 2 for 3)</literal></entry>
1273
       <entry><literal>hom</literal></entry>
1274
      </row>
1275
1276
      <row>
1277
       <entry><literal><function>substring(<parameter>string</parameter> from <replaceable>pattern</replaceable>)</function></literal></entry>
1278
       <entry><type>text</type></entry>
1279
       <entry>
1280
        Extract substring matching POSIX regular expression. See
1281
        <xref linkend="functions-matching"> for more information on pattern
1282
        matching.
1283
       </entry>
1284
       <entry><literal>substring('Thomas' from '...$')</literal></entry>
1285
       <entry><literal>mas</literal></entry>
1286
      </row>
1287
1288
      <row>
1289
       <entry><literal><function>substring(<parameter>string</parameter> from <replaceable>pattern</replaceable> for <replaceable>escape</replaceable>)</function></literal></entry>
1290
       <entry><type>text</type></entry>
1291
       <entry>
1292
        Extract substring matching <acronym>SQL</acronym> regular expression.
1293
        See <xref linkend="functions-matching"> for more information on
1294
        pattern matching.
1295
       </entry>
1296
       <entry><literal>substring('Thomas' from '%#"o_a#"_' for '#')</literal></entry>
1297
       <entry><literal>oma</literal></entry>
1298
      </row>
1299
1300
      <row>
1301
       <entry>
1302
        <indexterm>
1303
         <primary>trim</primary>
1304
        </indexterm>
1305
        <literal><function>trim(<optional>leading | trailing | both</optional>
1306
        <optional><parameter>characters</parameter></optional> from
1307
        <parameter>string</parameter>)</function></literal>
1308
       </entry>
1309
       <entry><type>text</type></entry>
1310
       <entry>
1311
        Remove the longest string containing only the
1312
        <parameter>characters</parameter> (a space by default) from the
1313
        start/end/both ends of the <parameter>string</parameter>
1314
       </entry>
1315
       <entry><literal>trim(both 'x' from 'xTomxx')</literal></entry>
1316
       <entry><literal>Tom</literal></entry>
1317
      </row>
1318
1319
      <row>
1320
       <entry>
1321
        <indexterm>
1322
         <primary>upper</primary>
1323
        </indexterm>
1324
        <literal><function>upper(<parameter>string</parameter>)</function></literal>
1325
       </entry>
1326
       <entry><type>text</type></entry>
1327
       <entry>Convert string to upper case</entry>
1328
       <entry><literal>upper('tom')</literal></entry>
1329
       <entry><literal>TOM</literal></entry>
1330
      </row>
1331
     </tbody>
1332
    </tgroup>
1333
   </table>
1334
1335
   <para>
1336
    Additional string manipulation functions are available and are
1337
    listed in <xref linkend="functions-string-other">.  Some of them are used internally to implement the
1338
    <acronym>SQL</acronym>-standard string functions listed in <xref linkend="functions-string-sql">.
1339
   </para>
1340
1341
   <table id="functions-string-other">
1342
    <title>Other String Functions</title>
1343
    <tgroup cols="5">
1344
     <thead>
1345
      <row>
1346
       <entry>Function</entry>
1347
       <entry>Return Type</entry>
1348
       <entry>Description</entry>
1349
       <entry>Example</entry>
1350
       <entry>Result</entry>
1351
      </row>
1352
     </thead>
1353
1354
     <tbody>
1355
      <row>
1356
       <entry>
1357
        <indexterm>
1358
         <primary>ascii</primary>
1359
        </indexterm>
1360
        <literal><function>ascii(<parameter>string</parameter>)</function></literal>
1361
       </entry>
1362
       <entry><type>int</type></entry>
1363
       <entry>
1364
        <acronym>ASCII</acronym> code of the first character of the
1365
        argument.  For <acronym>UTF8</acronym> returns the Unicode code
1366
        point of the character.  For other multibyte encodings, the
1367
        argument must be an <acronym>ASCII</acronym> character.
1368
       </entry>
1369
       <entry><literal>ascii('x')</literal></entry>
1370
       <entry><literal>120</literal></entry>
1371
      </row>
1372
1373
      <row>
1374
       <entry>
1375
        <indexterm>
1376
         <primary>btrim</primary>
1377
        </indexterm>
1378
        <literal><function>btrim(<parameter>string</parameter> <type>text</type>
1379
        <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
1380
       </entry>
1381
       <entry><type>text</type></entry>
1382
       <entry>
1383
        Remove the longest string consisting only of characters
1384
        in <parameter>characters</parameter> (a space by default)
1385
        from the start and end of <parameter>string</parameter>
1386
       </entry>
1387
       <entry><literal>btrim('xyxtrimyyx', 'xy')</literal></entry>
1388
       <entry><literal>trim</literal></entry>
1389
      </row>
1390
1391
      <row>
1392
       <entry>
1393
        <indexterm>
1394
         <primary>chr</primary>
1395
        </indexterm>
1396
        <literal><function>chr(<type>int</type>)</function></literal>
1397
       </entry>
1398
       <entry><type>text</type></entry>
1399
       <entry>
1400
        Character with the given code. For <acronym>UTF8</acronym> the
1401
        argument is treated as a Unicode code point. For other multibyte
1402
        encodings the argument must designate an
1403
        <acronym>ASCII</acronym> character.  The NULL (0) character is not
1404
        allowed because text data types cannot store such bytes.
1405
       </entry>
1406
       <entry><literal>chr(65)</literal></entry>
1407
       <entry><literal>A</literal></entry>
1408
      </row>
1409
1410
      <row>
1411
       <entry>
1412
        <indexterm>
1413
         <primary>concat</primary>
1414
        </indexterm>
1415
        <literal><function>concat(<parameter>str</parameter> <type>"any"</type>
1416
         [, <parameter>str</parameter> <type>"any"</type> [, ...] ])</function></literal>
1417
       </entry>
1418
       <entry><type>text</type></entry>
1419
       <entry>
1420
        Concatenate the text representations of all the arguments.
1421
        NULL arguments are ignored.
1422
       </entry>
1423
       <entry><literal>concat('abcde', 2, NULL, 22)</literal></entry>
1424
       <entry><literal>abcde222</literal></entry>
1425
      </row>
1426
1427
      <row>
1428
       <entry>
1429
        <indexterm>
1430
         <primary>concat_ws</primary>
1431
        </indexterm>
1432
        <literal><function>concat_ws(<parameter>sep</parameter> <type>text</type>,
1433
        <parameter>str</parameter> <type>"any"</type>
1434
        [, <parameter>str</parameter> <type>"any"</type> [, ...] ])</function></literal>
1435
       </entry>
1436
       <entry><type>text</type></entry>
1437
       <entry>
1438
        Concatenate all but the first argument with separators. The first
1439
        argument is used as the separator string. NULL arguments are ignored.
1440
       </entry>
1441
       <entry><literal>concat_ws(',', 'abcde', 2, NULL, 22)</literal></entry>
1442
       <entry><literal>abcde,2,22</literal></entry>
1443
      </row>
1444
1445
      <row>
1446
       <entry>
1447
        <indexterm>
1448
         <primary>convert</primary>
1449
        </indexterm>
1450
        <literal><function>convert(<parameter>string</parameter> <type>bytea</type>,
1451
        <parameter>src_encoding</parameter> <type>name</type>,
1452
        <parameter>dest_encoding</parameter> <type>name</type>)</function></literal>
1453
       </entry>
1454
       <entry><type>bytea</type></entry>
1455
       <entry>
1456
        Convert string to <parameter>dest_encoding</parameter>.  The
1457
        original encoding is specified by
1458
        <parameter>src_encoding</parameter>. The
1459
        <parameter>string</parameter> must be valid in this encoding.
1460
        Conversions can be defined by <command>CREATE CONVERSION</command>.
1461
        Also there are some predefined conversions. See <xref
1462
        linkend="conversion-names"> for available conversions.
1463
       </entry>
1464
       <entry><literal>convert('text_in_utf8', 'UTF8', 'LATIN1')</literal></entry>
1465
       <entry><literal>text_in_utf8</literal> represented in Latin-1
1466
       encoding (ISO 8859-1)</entry>
1467
      </row>
1468
1469
      <row>
1470
       <entry>
1471
        <indexterm>
1472
         <primary>convert_from</primary>
1473
        </indexterm>
1474
        <literal><function>convert_from(<parameter>string</parameter> <type>bytea</type>,
1475
        <parameter>src_encoding</parameter> <type>name</type>)</function></literal>
1476
       </entry>
1477
       <entry><type>text</type></entry>
1478
       <entry>
1479
        Convert string to the database encoding.  The original encoding
1480
        is specified by <parameter>src_encoding</parameter>. The
1481
        <parameter>string</parameter> must be valid in this encoding.
1482
       </entry>
1483
       <entry><literal>convert_from('text_in_utf8', 'UTF8')</literal></entry>
1484
       <entry><literal>text_in_utf8</literal> represented in the current database encoding</entry>
1485
      </row>
1486
1487
      <row>
1488
       <entry>
1489
        <indexterm>
1490
         <primary>convert_to</primary>
1491
        </indexterm>
1492
        <literal><function>convert_to(<parameter>string</parameter> <type>text</type>,
1493
        <parameter>dest_encoding</parameter> <type>name</type>)</function></literal>
1494
       </entry>
1495
       <entry><type>bytea</type></entry>
1496
       <entry>
1497
        Convert string to <parameter>dest_encoding</parameter>.
1498
       </entry>
1499
       <entry><literal>convert_to('some text', 'UTF8')</literal></entry>
1500
       <entry><literal>some text</literal> represented in the UTF8 encoding</entry>
1501
      </row>
1502
1503
      <row>
1504
       <entry>
1505
        <indexterm>
1506
         <primary>decode</primary>
1507
        </indexterm>
1508
        <literal><function>decode(<parameter>string</parameter> <type>text</type>,
1509
        <parameter>format</parameter> <type>text</type>)</function></literal>
1510
       </entry>
1511
       <entry><type>bytea</type></entry>
1512
       <entry>
1513
        Decode binary data from textual representation in <parameter>string</>.
1514
        Options for <parameter>format</> are same as in <function>encode</>.
1515
       </entry>
1516
       <entry><literal>decode('MTIzAAE=', 'base64')</literal></entry>
1517
       <entry><literal>\x3132330001</literal></entry>
1518
      </row>
1519
1520
      <row>
1521
       <entry>
1522
        <indexterm>
1523
         <primary>encode</primary>
1524
        </indexterm>
1525
        <literal><function>encode(<parameter>data</parameter> <type>bytea</type>,
1526
        <parameter>format</parameter> <type>text</type>)</function></literal>
1527
       </entry>
1528
       <entry><type>text</type></entry>
1529
       <entry>
1530
        Encode binary data into a textual representation.  Supported
1531
        formats are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
1532
        <literal>escape</> converts zero bytes and high-bit-set bytes to
1533
        octal sequences (<literal>\</><replaceable>nnn</>) and
1534
        doubles backslashes.
1535
       </entry>
1536
       <entry><literal>encode(E'123\\000\\001', 'base64')</literal></entry>
1537
       <entry><literal>MTIzAAE=</literal></entry>
1538
      </row>
1539
1540
      <row>
1541
       <entry id="format">
1542
        <indexterm>
1543
         <primary>format</primary>
1544
        </indexterm>
1545
        <literal><function>format</function>(<parameter>formatstr</parameter> <type>text</type>
1546
        [, <parameter>formatarg</parameter> <type>"any"</type> [, ...] ])</literal>
1547
       </entry>
1548
       <entry><type>text</type></entry>
1549
       <entry>
1550
         Format arguments according to a format string.
1551
         This function is similar to the C function <function>sprintf</>.
1552
         See <xref linkend="functions-string-format">.
1553
       </entry>
1554
       <entry><literal>format('Hello %s, %1$s', 'World')</literal></entry>
1555
       <entry><literal>Hello World, World</literal></entry>
1556
      </row>
1557
1558
      <row>
1559
       <entry>
1560
        <indexterm>
1561
         <primary>initcap</primary>
1562
        </indexterm>
1563
        <literal><function>initcap(<parameter>string</parameter>)</function></literal>
1564
       </entry>
1565
       <entry><type>text</type></entry>
1566
       <entry>
1567
        Convert the first letter of each word to upper case and the
1568
        rest to lower case. Words are sequences of alphanumeric
1569
        characters separated by non-alphanumeric characters.
1570
       </entry>
1571
       <entry><literal>initcap('hi THOMAS')</literal></entry>
1572
       <entry><literal>Hi Thomas</literal></entry>
1573
      </row>
1574
1575
      <row>
1576
       <entry>
1577
        <indexterm>
1578
         <primary>left</primary>
1579
        </indexterm>
1580
        <literal><function>left(<parameter>str</parameter> <type>text</type>,
1581
        <parameter>n</parameter> <type>int</type>)</function></literal>
1582
       </entry>
1583
       <entry><type>text</type></entry>
1584
       <entry>
1585
        Return first <replaceable>n</> characters in the string. When <replaceable>n</>
1586
        is negative, return all but last |<replaceable>n</>| characters.
1587
        </entry>
1588
       <entry><literal>left('abcde', 2)</literal></entry>
1589
       <entry><literal>ab</literal></entry>
1590
      </row>
1591
1592
      <row>
1593
       <entry>
1594
        <indexterm>
1595
         <primary>length</primary>
1596
        </indexterm>
1597
        <literal><function>length(<parameter>string</parameter>)</function></literal>
1598
       </entry>
1599
       <entry><type>int</type></entry>
1600
       <entry>
1601
        Number of characters in <parameter>string</parameter>
1602
       </entry>
1603
       <entry><literal>length('jose')</literal></entry>
1604
       <entry><literal>4</literal></entry>
1605
      </row>
1606
1607
      <row>
1608
       <entry><literal><function>length(<parameter>string</parameter> <type>bytea</type>,
1609
        <parameter>encoding</parameter> <type>name</type> )</function></literal></entry>
1610
       <entry><type>int</type></entry>
1611
       <entry>
1612
        Number of characters in <parameter>string</parameter> in the given
1613
        <parameter>encoding</parameter>. The <parameter>string</parameter>
1614
        must be valid in this encoding.
1615
       </entry>
1616
       <entry><literal>length('jose', 'UTF8')</literal></entry>
1617
       <entry><literal>4</literal></entry>
1618
      </row>
1619
1620
      <row>
1621
       <entry>
1622
        <indexterm>
1623
         <primary>lpad</primary>
1624
        </indexterm>
1625
        <literal><function>lpad(<parameter>string</parameter> <type>text</type>,
1626
        <parameter>length</parameter> <type>int</type>
1627
        <optional>, <parameter>fill</parameter> <type>text</type></optional>)</function></literal>
1628
       </entry>
1629
       <entry><type>text</type></entry>
1630
       <entry>
1631
        Fill up the <parameter>string</parameter> to length
1632
        <parameter>length</parameter> by prepending the characters
1633
        <parameter>fill</parameter> (a space by default).  If the
1634
        <parameter>string</parameter> is already longer than
1635
        <parameter>length</parameter> then it is truncated (on the
1636
        right).
1637
       </entry>
1638
       <entry><literal>lpad('hi', 5, 'xy')</literal></entry>
1639
       <entry><literal>xyxhi</literal></entry>
1640
      </row>
1641
1642
      <row>
1643
       <entry>
1644
        <indexterm>
1645
         <primary>ltrim</primary>
1646
        </indexterm>
1647
        <literal><function>ltrim(<parameter>string</parameter> <type>text</type>
1648
        <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
1649
       </entry>
1650
       <entry><type>text</type></entry>
1651
       <entry>
1652
        Remove the longest string containing only characters from
1653
        <parameter>characters</parameter> (a space by default) from the start of
1654
        <parameter>string</parameter>
1655
       </entry>
1656
       <entry><literal>ltrim('zzzytrim', 'xyz')</literal></entry>
1657
       <entry><literal>trim</literal></entry>
1658
      </row>
1659
1660
      <row>
1661
       <entry>
1662
        <indexterm>
1663
         <primary>md5</primary>
1664
        </indexterm>
1665
        <literal><function>md5(<parameter>string</parameter>)</function></literal>
1666
       </entry>
1667
       <entry><type>text</type></entry>
1668
       <entry>
1669
        Calculates the MD5 hash of <parameter>string</parameter>,
1670
        returning the result in hexadecimal
1671
       </entry>
1672
       <entry><literal>md5('abc')</literal></entry>
1673
       <entry><literal>900150983cd24fb0 d6963f7d28e17f72</literal></entry>
1674
      </row>
1675
1676
      <row>
1677
       <entry>
1678
        <indexterm>
1679
         <primary>pg_client_encoding</primary>
1680
        </indexterm>
1681
        <literal><function>pg_client_encoding()</function></literal>
1682
       </entry>
1683
       <entry><type>name</type></entry>
1684
       <entry>
1685
        Current client encoding name
1686
       </entry>
1687
       <entry><literal>pg_client_encoding()</literal></entry>
1688
       <entry><literal>SQL_ASCII</literal></entry>
1689
      </row>
1690
1691
      <row>
1692
       <entry>
1693
        <indexterm>
1694
         <primary>quote_ident</primary>
1695
        </indexterm>
1696
        <literal><function>quote_ident(<parameter>string</parameter> <type>text</type>)</function></literal>
1697
       </entry>
1698
       <entry><type>text</type></entry>
1699
       <entry>
1700
        Return the given string suitably quoted to be used as an identifier
1701
        in an <acronym>SQL</acronym> statement string.
1702
        Quotes are added only if necessary (i.e., if the string contains
1703
        non-identifier characters or would be case-folded).
1704
        Embedded quotes are properly doubled.
1705
        See also <xref linkend="plpgsql-quote-literal-example">.
1706
       </entry>
1707
       <entry><literal>quote_ident('Foo bar')</literal></entry>
1708
       <entry><literal>"Foo bar"</literal></entry>
1709
      </row>
1710
1711
      <row>
1712
       <entry>
1713
        <indexterm>
1714
         <primary>quote_literal</primary>
1715
        </indexterm>
1716
        <literal><function>quote_literal(<parameter>string</parameter> <type>text</type>)</function></literal>
1717
       </entry>
1718
       <entry><type>text</type></entry>
1719
       <entry>
1720
        Return the given string suitably quoted to be used as a string literal
1721
        in an <acronym>SQL</acronym> statement string.
1722
        Embedded single-quotes and backslashes are properly doubled.
1723
        Note that <function>quote_literal</function> returns null on null
1724
        input; if the argument might be null,
1725
        <function>quote_nullable</function> is often more suitable.
1726
        See also <xref linkend="plpgsql-quote-literal-example">.
1727
       </entry>
1728
       <entry><literal>quote_literal(E'O\'Reilly')</literal></entry>
1729
       <entry><literal>'O''Reilly'</literal></entry>
1730
      </row>
1731
1732
      <row>
1733
       <entry><literal><function>quote_literal(<parameter>value</parameter> <type>anyelement</type>)</function></literal></entry>
1734
       <entry><type>text</type></entry>
1735
       <entry>
1736
        Coerce the given value to text and then quote it as a literal.
1737
        Embedded single-quotes and backslashes are properly doubled.
1738
       </entry>
1739
       <entry><literal>quote_literal(42.5)</literal></entry>
1740
       <entry><literal>'42.5'</literal></entry>
1741
      </row>
1742
1743
      <row>
1744
       <entry>
1745
        <indexterm>
1746
         <primary>quote_nullable</primary>
1747
        </indexterm>
1748
        <literal><function>quote_nullable(<parameter>string</parameter> <type>text</type>)</function></literal>
1749
       </entry>
1750
       <entry><type>text</type></entry>
1751
       <entry>
1752
        Return the given string suitably quoted to be used as a string literal
1753
        in an <acronym>SQL</acronym> statement string; or, if the argument
1754
        is null, return <literal>NULL</>.
1755
        Embedded single-quotes and backslashes are properly doubled.
1756
        See also <xref linkend="plpgsql-quote-literal-example">.
1757
       </entry>
1758
       <entry><literal>quote_nullable(NULL)</literal></entry>
1759
       <entry><literal>NULL</literal></entry>
1760
      </row>
1761
1762
      <row>
1763
       <entry><literal><function>quote_nullable(<parameter>value</parameter> <type>anyelement</type>)</function></literal></entry>
1764
       <entry><type>text</type></entry>
1765
       <entry>
1766
        Coerce the given value to text and then quote it as a literal;
1767
        or, if the argument is null, return <literal>NULL</>.
1768
        Embedded single-quotes and backslashes are properly doubled.
1769
       </entry>
1770
       <entry><literal>quote_nullable(42.5)</literal></entry>
1771
       <entry><literal>'42.5'</literal></entry>
1772
      </row>
1773
1774
      <row>
1775
       <entry>
1776
        <indexterm>
1777
         <primary>regexp_matches</primary>
1778
        </indexterm>
1779
        <literal><function>regexp_matches(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
1780
       </entry>
1781
       <entry><type>setof text[]</type></entry>
1782
       <entry>
1783
        Return all captured substrings resulting from matching a POSIX regular
1784
        expression against the <parameter>string</parameter>. See
1785
        <xref linkend="functions-posix-regexp"> for more information.
1786
       </entry>
1787
       <entry><literal>regexp_matches('foobarbequebaz', '(bar)(beque)')</literal></entry>
1788
       <entry><literal>{bar,beque}</literal></entry>
1789
      </row>
1790
1791
      <row>
1792
       <entry>
1793
        <indexterm>
1794
         <primary>regexp_replace</primary>
1795
        </indexterm>
1796
        <literal><function>regexp_replace(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type>, <parameter>replacement</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
1797
       </entry>
1798
       <entry><type>text</type></entry>
1799
       <entry>
1800
        Replace substring(s) matching a POSIX regular expression. See
1801
        <xref linkend="functions-posix-regexp"> for more information.
1802
       </entry>
1803
       <entry><literal>regexp_replace('Thomas', '.[mN]a.', 'M')</literal></entry>
1804
       <entry><literal>ThM</literal></entry>
1805
      </row>
1806
1807
      <row>
1808
       <entry>
1809
        <indexterm>
1810
         <primary>regexp_split_to_array</primary>
1811
        </indexterm>
1812
        <literal><function>regexp_split_to_array(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type> ])</function></literal>
1813
       </entry>
1814
       <entry><type>text[]</type></entry>
1815
       <entry>
1816
        Split <parameter>string</parameter> using a POSIX regular expression as
1817
        the delimiter.  See <xref linkend="functions-posix-regexp"> for more
1818
        information.
1819
       </entry>
1820
       <entry><literal>regexp_split_to_array('hello world', E'\\s+')</literal></entry>
1821
       <entry><literal>{hello,world}</literal></entry>
1822
      </row>
1823
1824
      <row>
1825
       <entry>
1826
        <indexterm>
1827
         <primary>regexp_split_to_table</primary>
1828
        </indexterm>
1829
        <literal><function>regexp_split_to_table(<parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> [, <parameter>flags</parameter> <type>text</type>])</function></literal>
1830
       </entry>
1831
       <entry><type>setof text</type></entry>
1832
       <entry>
1833
        Split <parameter>string</parameter> using a POSIX regular expression as
1834
        the delimiter.  See <xref linkend="functions-posix-regexp"> for more
1835
        information.
1836
       </entry>
1837
       <entry><literal>regexp_split_to_table('hello world', E'\\s+')</literal></entry>
1838
       <entry><literal>hello</literal><para><literal>world</literal></para> (2 rows)</entry>
1839
      </row>
1840
1841
      <row>
1842
       <entry>
1843
        <indexterm>
1844
         <primary>repeat</primary>
1845
        </indexterm>
1846
        <literal><function>repeat(<parameter>string</parameter> <type>text</type>, <parameter>number</parameter> <type>int</type>)</function></literal>
1847
       </entry>
1848
       <entry><type>text</type></entry>
1849
       <entry>Repeat <parameter>string</parameter> the specified
1850
       <parameter>number</parameter> of times</entry>
1851
       <entry><literal>repeat('Pg', 4)</literal></entry>
1852
       <entry><literal>PgPgPgPg</literal></entry>
1853
      </row>
1854
1855
      <row>
1856
       <entry>
1857
        <indexterm>
1858
         <primary>replace</primary>
1859
        </indexterm>
1860
        <literal><function>replace(<parameter>string</parameter> <type>text</type>,
1861
        <parameter>from</parameter> <type>text</type>,
1862
        <parameter>to</parameter> <type>text</type>)</function></literal>
1863
       </entry>
1864
       <entry><type>text</type></entry>
1865
       <entry>Replace all occurrences in <parameter>string</parameter> of substring
1866
        <parameter>from</parameter> with substring <parameter>to</parameter>
1867
       </entry>
1868
       <entry><literal>replace('abcdefabcdef', 'cd', 'XX')</literal></entry>
1869
       <entry><literal>abXXefabXXef</literal></entry>
1870
      </row>
1871
1872
      <row>
1873
       <entry>
1874
        <indexterm>
1875
         <primary>reverse</primary>
1876
        </indexterm>
1877
        <literal><function>reverse(<parameter>str</parameter>)</function></literal>
1878
       </entry>
1879
       <entry><type>text</type></entry>
1880
       <entry>
1881
        Return reversed string.
1882
       </entry>
1883
       <entry><literal>reverse('abcde')</literal></entry>
1884
       <entry><literal>edcba</literal></entry>
1885
      </row>
1886
1887
      <row>
1888
       <entry>
1889
        <indexterm>
1890
         <primary>right</primary>
1891
        </indexterm>
1892
        <literal><function>right(<parameter>str</parameter> <type>text</type>,
1893
         <parameter>n</parameter> <type>int</type>)</function></literal>
1894
       </entry>
1895
       <entry><type>text</type></entry>
1896
       <entry>
1897
        Return last <replaceable>n</> characters in the string. When <replaceable>n</>
1898
        is negative, return all but first |<replaceable>n</>| characters.
1899
       </entry>
1900
       <entry><literal>right('abcde', 2)</literal></entry>
1901
       <entry><literal>de</literal></entry>
1902
      </row>
1903
1904
      <row>
1905
       <entry>
1906
        <indexterm>
1907
         <primary>rpad</primary>
1908
        </indexterm>
1909
        <literal><function>rpad(<parameter>string</parameter> <type>text</type>,
1910
        <parameter>length</parameter> <type>int</type>
1911
        <optional>, <parameter>fill</parameter> <type>text</type></optional>)</function></literal>
1912
       </entry>
1913
       <entry><type>text</type></entry>
1914
       <entry>
1915
        Fill up the <parameter>string</parameter> to length
1916
        <parameter>length</parameter> by appending the characters
1917
        <parameter>fill</parameter> (a space by default).  If the
1918
        <parameter>string</parameter> is already longer than
1919
        <parameter>length</parameter> then it is truncated.
1920
       </entry>
1921
       <entry><literal>rpad('hi', 5, 'xy')</literal></entry>
1922
       <entry><literal>hixyx</literal></entry>
1923
      </row>
1924
1925
      <row>
1926
       <entry>
1927
        <indexterm>
1928
         <primary>rtrim</primary>
1929
        </indexterm>
1930
        <literal><function>rtrim(<parameter>string</parameter> <type>text</type>
1931
         <optional>, <parameter>characters</parameter> <type>text</type></optional>)</function></literal>
1932
       </entry>
1933
       <entry><type>text</type></entry>
1934
       <entry>
1935
        Remove the longest string containing only characters from
1936
        <parameter>characters</parameter> (a space by default) from the end of
1937
        <parameter>string</parameter>
1938
       </entry>
1939
       <entry><literal>rtrim('trimxxxx', 'x')</literal></entry>
1940
       <entry><literal>trim</literal></entry>
1941
      </row>
1942
1943
      <row>
1944
       <entry>
1945
        <indexterm>
1946
         <primary>split_part</primary>
1947
        </indexterm>
1948
        <literal><function>split_part(<parameter>string</parameter> <type>text</type>,
1949
        <parameter>delimiter</parameter> <type>text</type>,
1950
        <parameter>field</parameter> <type>int</type>)</function></literal>
1951
       </entry>
1952
       <entry><type>text</type></entry>
1953
       <entry>Split <parameter>string</parameter> on <parameter>delimiter</parameter>
1954
        and return the given field (counting from one)
1955
       </entry>
1956
       <entry><literal>split_part('abc~@~def~@~ghi', '~@~', 2)</literal></entry>
1957
       <entry><literal>def</literal></entry>
1958
      </row>
1959
1960
      <row>
1961
       <entry>
1962
        <indexterm>
1963
         <primary>strpos</primary>
1964
        </indexterm>
1965
        <literal><function>strpos(<parameter>string</parameter>, <parameter>substring</parameter>)</function></literal>
1966
       </entry>
1967
       <entry><type>int</type></entry>
1968
       <entry>
1969
        Location of specified substring (same as
1970
        <literal>position(<parameter>substring</parameter> in
1971
         <parameter>string</parameter>)</literal>, but note the reversed
1972
        argument order)
1973
       </entry>
1974
       <entry><literal>strpos('high', 'ig')</literal></entry>
1975
       <entry><literal>2</literal></entry>
1976
      </row>
1977
1978
      <row>
1979
       <entry>
1980
        <indexterm>
1981
         <primary>substr</primary>
1982
        </indexterm>
1983
        <literal><function>substr(<parameter>string</parameter>, <parameter>from</parameter> <optional>, <parameter>count</parameter></optional>)</function></literal>
1984
       </entry>
1985
       <entry><type>text</type></entry>
1986
       <entry>
1987
        Extract substring (same as
1988
        <literal>substring(<parameter>string</parameter> from <parameter>from</parameter> for <parameter>count</parameter>)</literal>)
1989
       </entry>
1990
       <entry><literal>substr('alphabet', 3, 2)</literal></entry>
1991
       <entry><literal>ph</literal></entry>
1992
      </row>
1993
1994
      <row>
1995
       <entry>
1996
        <indexterm>
1997
         <primary>to_ascii</primary>
1998
        </indexterm>
1999
        <literal><function>to_ascii(<parameter>string</parameter> <type>text</type>
2000
        <optional>, <parameter>encoding</parameter> <type>text</type></optional>)</function></literal>
2001
       </entry>
2002
       <entry><type>text</type></entry>
2003
       <entry>
2004
       Convert <parameter>string</parameter> to <acronym>ASCII</acronym> from another encoding
2005
       (only supports conversion from  <literal>LATIN1</>, <literal>LATIN2</>, <literal>LATIN9</>,
2006
       and <literal>WIN1250</> encodings)
2007
       </entry>
2008
       <entry><literal>to_ascii('Karel')</literal></entry>
2009
       <entry><literal>Karel</literal></entry>
2010
      </row>
2011
2012
      <row>
2013
       <entry>
2014
        <indexterm>
2015
         <primary>to_hex</primary>
2016
        </indexterm>
2017
        <literal><function>to_hex(<parameter>number</parameter> <type>int</type>
2018
        or <type>bigint</type>)</function></literal>
2019
       </entry>
2020
       <entry><type>text</type></entry>
2021
       <entry>Convert <parameter>number</parameter> to its equivalent hexadecimal
2022
        representation
2023
       </entry>
2024
       <entry><literal>to_hex(2147483647)</literal></entry>
2025
       <entry><literal>7fffffff</literal></entry>
2026
      </row>
2027
2028
      <row>
2029
       <entry>
2030
        <indexterm>
2031
         <primary>translate</primary>
2032
        </indexterm>
2033
        <literal><function>translate(<parameter>string</parameter> <type>text</type>,
2034
        <parameter>from</parameter> <type>text</type>,
2035
        <parameter>to</parameter> <type>text</type>)</function></literal>
2036
       </entry>
2037
       <entry><type>text</type></entry>
2038
       <entry>
2039
        Any character in <parameter>string</parameter> that matches a
2040
        character in the <parameter>from</parameter> set is replaced by
2041
        the corresponding character in the <parameter>to</parameter>
2042
        set. If <parameter>from</parameter> is longer than
2043
        <parameter>to</parameter>, occurrences of the extra characters in
2044
        <parameter>from</parameter> are removed.
2045
       </entry>
2046
       <entry><literal>translate('12345', '143', 'ax')</literal></entry>
2047
       <entry><literal>a2x5</literal></entry>
2048
      </row>
2049
2050
     </tbody>
2051
    </tgroup>
2052
   </table>
2053
2054
   <para>
2055
    The <function>concat</function>, <function>concat_ws</function> and
2056
    <function>format</function> functions are variadic, so it is possible to
2057
    pass the values to be concatenated or formatted as an array marked with
2058
    the <literal>VARIADIC</literal> keyword (see <xref
2059
    linkend="xfunc-sql-variadic-functions">).  The array's elements are
2060
    treated as if they were separate ordinary arguments to the function.
2061
    If the variadic array argument is NULL, <function>concat</function>
2062
    and <function>concat_ws</function> return NULL, but
2063
    <function>format</function> treats a NULL as a zero-element array.
2064
   </para>
2065
2066
   <para>
2067
   See also the aggregate function <function>string_agg</function> in
2068
   <xref linkend="functions-aggregate">.
2069
   </para>
2070
2071
   <table id="conversion-names">
2072
    <title>Built-in Conversions</title>
2073
    <tgroup cols="3">
2074
     <thead>
2075
      <row>
2076
       <entry>Conversion Name
2077
        <footnote>
2078
         <para>
2079
          The conversion names follow a standard naming scheme: The
2080
          official name of the source encoding with all
2081
          non-alphanumeric characters replaced by underscores, followed
2082
          by <literal>_to_</literal>, followed by the similarly processed
2083
          destination encoding name. Therefore, the names might deviate
2084
          from the customary encoding names.
2085
         </para>
2086
        </footnote>
2087
       </entry>
2088
       <entry>Source Encoding</entry>
2089
       <entry>Destination Encoding</entry>
2090
      </row>
2091
     </thead>
2092
2093
     <tbody>
2094
      <row>
2095
       <entry><literal>ascii_to_mic</literal></entry>
2096
       <entry><literal>SQL_ASCII</literal></entry>
2097
       <entry><literal>MULE_INTERNAL</literal></entry>
2098
      </row>
2099
2100
      <row>
2101
       <entry><literal>ascii_to_utf8</literal></entry>
2102
       <entry><literal>SQL_ASCII</literal></entry>
2103
       <entry><literal>UTF8</literal></entry>
2104
      </row>
2105
2106
      <row>
2107
       <entry><literal>big5_to_euc_tw</literal></entry>
2108
       <entry><literal>BIG5</literal></entry>
2109
       <entry><literal>EUC_TW</literal></entry>
2110
      </row>
2111
2112
      <row>
2113
       <entry><literal>big5_to_mic</literal></entry>
2114
       <entry><literal>BIG5</literal></entry>
2115
       <entry><literal>MULE_INTERNAL</literal></entry>
2116
      </row>
2117
2118
      <row>
2119
       <entry><literal>big5_to_utf8</literal></entry>
2120
       <entry><literal>BIG5</literal></entry>
2121
       <entry><literal>UTF8</literal></entry>
2122
      </row>
2123
2124
      <row>
2125
       <entry><literal>euc_cn_to_mic</literal></entry>
2126
       <entry><literal>EUC_CN</literal></entry>
2127
       <entry><literal>MULE_INTERNAL</literal></entry>
2128
      </row>
2129
2130
      <row>
2131
       <entry><literal>euc_cn_to_utf8</literal></entry>
2132
       <entry><literal>EUC_CN</literal></entry>
2133
       <entry><literal>UTF8</literal></entry>
2134
      </row>
2135
2136
      <row>
2137
       <entry><literal>euc_jp_to_mic</literal></entry>
2138
       <entry><literal>EUC_JP</literal></entry>
2139
       <entry><literal>MULE_INTERNAL</literal></entry>
2140
      </row>
2141
2142
      <row>
2143
       <entry><literal>euc_jp_to_sjis</literal></entry>
2144
       <entry><literal>EUC_JP</literal></entry>
2145
       <entry><literal>SJIS</literal></entry>
2146
      </row>
2147
2148
      <row>
2149
       <entry><literal>euc_jp_to_utf8</literal></entry>
2150
       <entry><literal>EUC_JP</literal></entry>
2151
       <entry><literal>UTF8</literal></entry>
2152
      </row>
2153
2154
      <row>
2155
       <entry><literal>euc_kr_to_mic</literal></entry>
2156
       <entry><literal>EUC_KR</literal></entry>
2157
       <entry><literal>MULE_INTERNAL</literal></entry>
2158
      </row>
2159
2160
      <row>
2161
       <entry><literal>euc_kr_to_utf8</literal></entry>
2162
       <entry><literal>EUC_KR</literal></entry>
2163
       <entry><literal>UTF8</literal></entry>
2164
      </row>
2165
2166
      <row>
2167
       <entry><literal>euc_tw_to_big5</literal></entry>
2168
       <entry><literal>EUC_TW</literal></entry>
2169
       <entry><literal>BIG5</literal></entry>
2170
      </row>
2171
2172
      <row>
2173
       <entry><literal>euc_tw_to_mic</literal></entry>
2174
       <entry><literal>EUC_TW</literal></entry>
2175
       <entry><literal>MULE_INTERNAL</literal></entry>
2176
      </row>
2177
2178
      <row>
2179
       <entry><literal>euc_tw_to_utf8</literal></entry>
2180
       <entry><literal>EUC_TW</literal></entry>
2181
       <entry><literal>UTF8</literal></entry>
2182
      </row>
2183
2184
      <row>
2185
       <entry><literal>gb18030_to_utf8</literal></entry>
2186
       <entry><literal>GB18030</literal></entry>
2187
       <entry><literal>UTF8</literal></entry>
2188
      </row>
2189
2190
      <row>
2191
       <entry><literal>gbk_to_utf8</literal></entry>
2192
       <entry><literal>GBK</literal></entry>
2193
       <entry><literal>UTF8</literal></entry>
2194
      </row>
2195
2196
      <row>
2197
       <entry><literal>iso_8859_10_to_utf8</literal></entry>
2198
       <entry><literal>LATIN6</literal></entry>
2199
       <entry><literal>UTF8</literal></entry>
2200
      </row>
2201
2202
      <row>
2203
       <entry><literal>iso_8859_13_to_utf8</literal></entry>
2204
       <entry><literal>LATIN7</literal></entry>
2205
       <entry><literal>UTF8</literal></entry>
2206
      </row>
2207
2208
      <row>
2209
       <entry><literal>iso_8859_14_to_utf8</literal></entry>
2210
       <entry><literal>LATIN8</literal></entry>
2211
       <entry><literal>UTF8</literal></entry>
2212
      </row>
2213
2214
      <row>
2215
       <entry><literal>iso_8859_15_to_utf8</literal></entry>
2216
       <entry><literal>LATIN9</literal></entry>
2217
       <entry><literal>UTF8</literal></entry>
2218
      </row>
2219
2220
      <row>
2221
       <entry><literal>iso_8859_16_to_utf8</literal></entry>
2222
       <entry><literal>LATIN10</literal></entry>
2223
       <entry><literal>UTF8</literal></entry>
2224
      </row>
2225
2226
      <row>
2227
       <entry><literal>iso_8859_1_to_mic</literal></entry>
2228
       <entry><literal>LATIN1</literal></entry>
2229
       <entry><literal>MULE_INTERNAL</literal></entry>
2230
      </row>
2231
2232
      <row>
2233
       <entry><literal>iso_8859_1_to_utf8</literal></entry>
2234
       <entry><literal>LATIN1</literal></entry>
2235
       <entry><literal>UTF8</literal></entry>
2236
      </row>
2237
2238
      <row>
2239
       <entry><literal>iso_8859_2_to_mic</literal></entry>
2240
       <entry><literal>LATIN2</literal></entry>
2241
       <entry><literal>MULE_INTERNAL</literal></entry>
2242
      </row>
2243
2244
      <row>
2245
       <entry><literal>iso_8859_2_to_utf8</literal></entry>
2246
       <entry><literal>LATIN2</literal></entry>
2247
       <entry><literal>UTF8</literal></entry>
2248
      </row>
2249
2250
      <row>
2251
       <entry><literal>iso_8859_2_to_windows_1250</literal></entry>
2252
       <entry><literal>LATIN2</literal></entry>
2253
       <entry><literal>WIN1250</literal></entry>
2254
      </row>
2255
2256
      <row>
2257
       <entry><literal>iso_8859_3_to_mic</literal></entry>
2258
       <entry><literal>LATIN3</literal></entry>
2259
       <entry><literal>MULE_INTERNAL</literal></entry>
2260
      </row>
2261
2262
      <row>
2263
       <entry><literal>iso_8859_3_to_utf8</literal></entry>
2264
       <entry><literal>LATIN3</literal></entry>
2265
       <entry><literal>UTF8</literal></entry>
2266
      </row>
2267
2268
      <row>
2269
       <entry><literal>iso_8859_4_to_mic</literal></entry>
2270
       <entry><literal>LATIN4</literal></entry>
2271
       <entry><literal>MULE_INTERNAL</literal></entry>
2272
      </row>
2273
2274
      <row>
2275
       <entry><literal>iso_8859_4_to_utf8</literal></entry>
2276
       <entry><literal>LATIN4</literal></entry>
2277
       <entry><literal>UTF8</literal></entry>
2278
      </row>
2279
2280
      <row>
2281
       <entry><literal>iso_8859_5_to_koi8_r</literal></entry>
2282
       <entry><literal>ISO_8859_5</literal></entry>
2283
       <entry><literal>KOI8R</literal></entry>
2284
      </row>
2285
2286
      <row>
2287
       <entry><literal>iso_8859_5_to_mic</literal></entry>
2288
       <entry><literal>ISO_8859_5</literal></entry>
2289
       <entry><literal>MULE_INTERNAL</literal></entry>
2290
      </row>
2291
2292
      <row>
2293
       <entry><literal>iso_8859_5_to_utf8</literal></entry>
2294
       <entry><literal>ISO_8859_5</literal></entry>
2295
       <entry><literal>UTF8</literal></entry>
2296
      </row>
2297
2298
      <row>
2299
       <entry><literal>iso_8859_5_to_windows_1251</literal></entry>
2300
       <entry><literal>ISO_8859_5</literal></entry>
2301
       <entry><literal>WIN1251</literal></entry>
2302
      </row>
2303
2304
      <row>
2305
       <entry><literal>iso_8859_5_to_windows_866</literal></entry>
2306
       <entry><literal>ISO_8859_5</literal></entry>
2307
       <entry><literal>WIN866</literal></entry>
2308
      </row>
2309
2310
      <row>
2311
       <entry><literal>iso_8859_6_to_utf8</literal></entry>
2312
       <entry><literal>ISO_8859_6</literal></entry>
2313
       <entry><literal>UTF8</literal></entry>
2314
      </row>
2315
2316
      <row>
2317
       <entry><literal>iso_8859_7_to_utf8</literal></entry>
2318
       <entry><literal>ISO_8859_7</literal></entry>
2319
       <entry><literal>UTF8</literal></entry>
2320
      </row>
2321
2322
      <row>
2323
       <entry><literal>iso_8859_8_to_utf8</literal></entry>
2324
       <entry><literal>ISO_8859_8</literal></entry>
2325
       <entry><literal>UTF8</literal></entry>
2326
      </row>
2327
2328
      <row>
2329
       <entry><literal>iso_8859_9_to_utf8</literal></entry>
2330
       <entry><literal>LATIN5</literal></entry>
2331
       <entry><literal>UTF8</literal></entry>
2332
      </row>
2333
2334
      <row>
2335
       <entry><literal>johab_to_utf8</literal></entry>
2336
       <entry><literal>JOHAB</literal></entry>
2337
       <entry><literal>UTF8</literal></entry>
2338
      </row>
2339
2340
      <row>
2341
       <entry><literal>koi8_r_to_iso_8859_5</literal></entry>
2342
       <entry><literal>KOI8R</literal></entry>
2343
       <entry><literal>ISO_8859_5</literal></entry>
2344
      </row>
2345
2346
      <row>
2347
       <entry><literal>koi8_r_to_mic</literal></entry>
2348
       <entry><literal>KOI8R</literal></entry>
2349
       <entry><literal>MULE_INTERNAL</literal></entry>
2350
      </row>
2351
2352
      <row>
2353
       <entry><literal>koi8_r_to_utf8</literal></entry>
2354
       <entry><literal>KOI8R</literal></entry>
2355
       <entry><literal>UTF8</literal></entry>
2356
      </row>
2357
2358
      <row>
2359
       <entry><literal>koi8_r_to_windows_1251</literal></entry>
2360
       <entry><literal>KOI8R</literal></entry>
2361
       <entry><literal>WIN1251</literal></entry>
2362
      </row>
2363
2364
      <row>
2365
       <entry><literal>koi8_r_to_windows_866</literal></entry>
2366
       <entry><literal>KOI8R</literal></entry>
2367
       <entry><literal>WIN866</literal></entry>
2368
      </row>
2369
2370
      <row>
2371
       <entry><literal>koi8_u_to_utf8</literal></entry>
2372
       <entry><literal>KOI8U</literal></entry>
2373
       <entry><literal>UTF8</literal></entry>
2374
      </row>
2375
2376
      <row>
2377
       <entry><literal>mic_to_ascii</literal></entry>
2378
       <entry><literal>MULE_INTERNAL</literal></entry>
2379
       <entry><literal>SQL_ASCII</literal></entry>
2380
      </row>
2381
2382
      <row>
2383
       <entry><literal>mic_to_big5</literal></entry>
2384
       <entry><literal>MULE_INTERNAL</literal></entry>
2385
       <entry><literal>BIG5</literal></entry>
2386
      </row>
2387
2388
      <row>
2389
       <entry><literal>mic_to_euc_cn</literal></entry>
2390
       <entry><literal>MULE_INTERNAL</literal></entry>
2391
       <entry><literal>EUC_CN</literal></entry>
2392
      </row>
2393
2394
      <row>
2395
       <entry><literal>mic_to_euc_jp</literal></entry>
2396
       <entry><literal>MULE_INTERNAL</literal></entry>
2397
       <entry><literal>EUC_JP</literal></entry>
2398
      </row>
2399
2400
      <row>
2401
       <entry><literal>mic_to_euc_kr</literal></entry>
2402
       <entry><literal>MULE_INTERNAL</literal></entry>
2403
       <entry><literal>EUC_KR</literal></entry>
2404
      </row>
2405
2406
      <row>
2407
       <entry><literal>mic_to_euc_tw</literal></entry>
2408
       <entry><literal>MULE_INTERNAL</literal></entry>
2409
       <entry><literal>EUC_TW</literal></entry>
2410
      </row>
2411
2412
      <row>
2413
       <entry><literal>mic_to_iso_8859_1</literal></entry>
2414
       <entry><literal>MULE_INTERNAL</literal></entry>
2415
       <entry><literal>LATIN1</literal></entry>
2416
      </row>
2417
2418
      <row>
2419
       <entry><literal>mic_to_iso_8859_2</literal></entry>
2420
       <entry><literal>MULE_INTERNAL</literal></entry>
2421
       <entry><literal>LATIN2</literal></entry>
2422
      </row>
2423
2424
      <row>
2425
       <entry><literal>mic_to_iso_8859_3</literal></entry>
2426
       <entry><literal>MULE_INTERNAL</literal></entry>
2427
       <entry><literal>LATIN3</literal></entry>
2428
      </row>
2429
2430
      <row>
2431
       <entry><literal>mic_to_iso_8859_4</literal></entry>
2432
       <entry><literal>MULE_INTERNAL</literal></entry>
2433
       <entry><literal>LATIN4</literal></entry>
2434
      </row>
2435
2436
      <row>
2437
       <entry><literal>mic_to_iso_8859_5</literal></entry>
2438
       <entry><literal>MULE_INTERNAL</literal></entry>
2439
       <entry><literal>ISO_8859_5</literal></entry>
2440
      </row>
2441
2442
      <row>
2443
       <entry><literal>mic_to_koi8_r</literal></entry>
2444
       <entry><literal>MULE_INTERNAL</literal></entry>
2445
       <entry><literal>KOI8R</literal></entry>
2446
      </row>
2447
2448
      <row>
2449
       <entry><literal>mic_to_sjis</literal></entry>
2450
       <entry><literal>MULE_INTERNAL</literal></entry>
2451
       <entry><literal>SJIS</literal></entry>
2452
      </row>
2453
2454
      <row>
2455
       <entry><literal>mic_to_windows_1250</literal></entry>
2456
       <entry><literal>MULE_INTERNAL</literal></entry>
2457
       <entry><literal>WIN1250</literal></entry>
2458
      </row>
2459
2460
      <row>
2461
       <entry><literal>mic_to_windows_1251</literal></entry>
2462
       <entry><literal>MULE_INTERNAL</literal></entry>
2463
       <entry><literal>WIN1251</literal></entry>
2464
      </row>
2465
2466
      <row>
2467
       <entry><literal>mic_to_windows_866</literal></entry>
2468
       <entry><literal>MULE_INTERNAL</literal></entry>
2469
       <entry><literal>WIN866</literal></entry>
2470
      </row>
2471
2472
      <row>
2473
       <entry><literal>sjis_to_euc_jp</literal></entry>
2474
       <entry><literal>SJIS</literal></entry>
2475
       <entry><literal>EUC_JP</literal></entry>
2476
      </row>
2477
2478
      <row>
2479
       <entry><literal>sjis_to_mic</literal></entry>
2480
       <entry><literal>SJIS</literal></entry>
2481
       <entry><literal>MULE_INTERNAL</literal></entry>
2482
      </row>
2483
2484
      <row>
2485
       <entry><literal>sjis_to_utf8</literal></entry>
2486
       <entry><literal>SJIS</literal></entry>
2487
       <entry><literal>UTF8</literal></entry>
2488
      </row>
2489
2490
      <row>
2491
       <entry><literal>tcvn_to_utf8</literal></entry>
2492
       <entry><literal>WIN1258</literal></entry>
2493
       <entry><literal>UTF8</literal></entry>
2494
      </row>
2495
2496
      <row>
2497
       <entry><literal>uhc_to_utf8</literal></entry>
2498
       <entry><literal>UHC</literal></entry>
2499
       <entry><literal>UTF8</literal></entry>
2500
      </row>
2501
2502
      <row>
2503
       <entry><literal>utf8_to_ascii</literal></entry>
2504
       <entry><literal>UTF8</literal></entry>
2505
       <entry><literal>SQL_ASCII</literal></entry>
2506
      </row>
2507
2508
      <row>
2509
       <entry><literal>utf8_to_big5</literal></entry>
2510
       <entry><literal>UTF8</literal></entry>
2511
       <entry><literal>BIG5</literal></entry>
2512
      </row>
2513
2514
      <row>
2515
       <entry><literal>utf8_to_euc_cn</literal></entry>
2516
       <entry><literal>UTF8</literal></entry>
2517
       <entry><literal>EUC_CN</literal></entry>
2518
      </row>
2519
2520
      <row>
2521
       <entry><literal>utf8_to_euc_jp</literal></entry>
2522
       <entry><literal>UTF8</literal></entry>
2523
       <entry><literal>EUC_JP</literal></entry>
2524
      </row>
2525
2526
      <row>
2527
       <entry><literal>utf8_to_euc_kr</literal></entry>
2528
       <entry><literal>UTF8</literal></entry>
2529
       <entry><literal>EUC_KR</literal></entry>
2530
      </row>
2531
2532
      <row>
2533
       <entry><literal>utf8_to_euc_tw</literal></entry>
2534
       <entry><literal>UTF8</literal></entry>
2535
       <entry><literal>EUC_TW</literal></entry>
2536
      </row>
2537
2538
      <row>
2539
       <entry><literal>utf8_to_gb18030</literal></entry>
2540
       <entry><literal>UTF8</literal></entry>
2541
       <entry><literal>GB18030</literal></entry>
2542
      </row>
2543
2544
      <row>
2545
       <entry><literal>utf8_to_gbk</literal></entry>
2546
       <entry><literal>UTF8</literal></entry>
2547
       <entry><literal>GBK</literal></entry>
2548
      </row>
2549
2550
      <row>
2551
       <entry><literal>utf8_to_iso_8859_1</literal></entry>
2552
       <entry><literal>UTF8</literal></entry>
2553
       <entry><literal>LATIN1</literal></entry>
2554
      </row>
2555
2556
      <row>
2557
       <entry><literal>utf8_to_iso_8859_10</literal></entry>
2558
       <entry><literal>UTF8</literal></entry>
2559
       <entry><literal>LATIN6</literal></entry>
2560
      </row>
2561
2562
      <row>
2563
       <entry><literal>utf8_to_iso_8859_13</literal></entry>
2564
       <entry><literal>UTF8</literal></entry>
2565
       <entry><literal>LATIN7</literal></entry>
2566
      </row>
2567
2568
      <row>
2569
       <entry><literal>utf8_to_iso_8859_14</literal></entry>
2570
       <entry><literal>UTF8</literal></entry>
2571
       <entry><literal>LATIN8</literal></entry>
2572
      </row>
2573
2574
      <row>
2575
       <entry><literal>utf8_to_iso_8859_15</literal></entry>
2576
       <entry><literal>UTF8</literal></entry>
2577
       <entry><literal>LATIN9</literal></entry>
2578
      </row>
2579
2580
      <row>
2581
       <entry><literal>utf8_to_iso_8859_16</literal></entry>
2582
       <entry><literal>UTF8</literal></entry>
2583
       <entry><literal>LATIN10</literal></entry>
2584
      </row>
2585
2586
      <row>
2587
       <entry><literal>utf8_to_iso_8859_2</literal></entry>
2588
       <entry><literal>UTF8</literal></entry>
2589
       <entry><literal>LATIN2</literal></entry>
2590
      </row>
2591
2592
      <row>
2593
       <entry><literal>utf8_to_iso_8859_3</literal></entry>
2594
       <entry><literal>UTF8</literal></entry>
2595
       <entry><literal>LATIN3</literal></entry>
2596
      </row>
2597
2598
      <row>
2599
       <entry><literal>utf8_to_iso_8859_4</literal></entry>
2600
       <entry><literal>UTF8</literal></entry>
2601
       <entry><literal>LATIN4</literal></entry>
2602
      </row>
2603
2604
      <row>
2605
       <entry><literal>utf8_to_iso_8859_5</literal></entry>
2606
       <entry><literal>UTF8</literal></entry>
2607
       <entry><literal>ISO_8859_5</literal></entry>
2608
      </row>
2609
2610
      <row>
2611
       <entry><literal>utf8_to_iso_8859_6</literal></entry>
2612
       <entry><literal>UTF8</literal></entry>
2613
       <entry><literal>ISO_8859_6</literal></entry>
2614
      </row>
2615
2616
      <row>
2617
       <entry><literal>utf8_to_iso_8859_7</literal></entry>
2618
       <entry><literal>UTF8</literal></entry>
2619
       <entry><literal>ISO_8859_7</literal></entry>
2620
      </row>
2621
2622
      <row>
2623
       <entry><literal>utf8_to_iso_8859_8</literal></entry>
2624
       <entry><literal>UTF8</literal></entry>
2625
       <entry><literal>ISO_8859_8</literal></entry>
2626
      </row>
2627
2628
      <row>
2629
       <entry><literal>utf8_to_iso_8859_9</literal></entry>
2630
       <entry><literal>UTF8</literal></entry>
2631
       <entry><literal>LATIN5</literal></entry>
2632
      </row>
2633
2634
      <row>
2635
       <entry><literal>utf8_to_johab</literal></entry>
2636
       <entry><literal>UTF8</literal></entry>
2637
       <entry><literal>JOHAB</literal></entry>
2638
      </row>
2639
2640
      <row>
2641
       <entry><literal>utf8_to_koi8_r</literal></entry>
2642
       <entry><literal>UTF8</literal></entry>
2643
       <entry><literal>KOI8R</literal></entry>
2644
      </row>
2645
2646
      <row>
2647
       <entry><literal>utf8_to_koi8_u</literal></entry>
2648
       <entry><literal>UTF8</literal></entry>
2649
       <entry><literal>KOI8U</literal></entry>
2650
      </row>
2651
2652
      <row>
2653
       <entry><literal>utf8_to_sjis</literal></entry>
2654
       <entry><literal>UTF8</literal></entry>
2655
       <entry><literal>SJIS</literal></entry>
2656
      </row>
2657
2658
      <row>
2659
       <entry><literal>utf8_to_tcvn</literal></entry>
2660
       <entry><literal>UTF8</literal></entry>
2661
       <entry><literal>WIN1258</literal></entry>
2662
      </row>
2663
2664
      <row>
2665
       <entry><literal>utf8_to_uhc</literal></entry>
2666
       <entry><literal>UTF8</literal></entry>
2667
       <entry><literal>UHC</literal></entry>
2668
      </row>
2669
2670
      <row>
2671
       <entry><literal>utf8_to_windows_1250</literal></entry>
2672
       <entry><literal>UTF8</literal></entry>
2673
       <entry><literal>WIN1250</literal></entry>
2674
      </row>
2675
2676
      <row>
2677
       <entry><literal>utf8_to_windows_1251</literal></entry>
2678
       <entry><literal>UTF8</literal></entry>
2679
       <entry><literal>WIN1251</literal></entry>
2680
      </row>
2681
2682
      <row>
2683
       <entry><literal>utf8_to_windows_1252</literal></entry>
2684
       <entry><literal>UTF8</literal></entry>
2685
       <entry><literal>WIN1252</literal></entry>
2686
      </row>
2687
2688
      <row>
2689
       <entry><literal>utf8_to_windows_1253</literal></entry>
2690
       <entry><literal>UTF8</literal></entry>
2691
       <entry><literal>WIN1253</literal></entry>
2692
      </row>
2693
2694
      <row>
2695
       <entry><literal>utf8_to_windows_1254</literal></entry>
2696
       <entry><literal>UTF8</literal></entry>
2697
       <entry><literal>WIN1254</literal></entry>
2698
      </row>
2699
2700
      <row>
2701
       <entry><literal>utf8_to_windows_1255</literal></entry>
2702
       <entry><literal>UTF8</literal></entry>
2703
       <entry><literal>WIN1255</literal></entry>
2704
      </row>
2705
2706
      <row>
2707
       <entry><literal>utf8_to_windows_1256</literal></entry>
2708
       <entry><literal>UTF8</literal></entry>
2709
       <entry><literal>WIN1256</literal></entry>
2710
      </row>
2711
2712
      <row>
2713
       <entry><literal>utf8_to_windows_1257</literal></entry>
2714
       <entry><literal>UTF8</literal></entry>
2715
       <entry><literal>WIN1257</literal></entry>
2716
      </row>
2717
2718
      <row>
2719
       <entry><literal>utf8_to_windows_866</literal></entry>
2720
       <entry><literal>UTF8</literal></entry>
2721
       <entry><literal>WIN866</literal></entry>
2722
      </row>
2723
2724
      <row>
2725
       <entry><literal>utf8_to_windows_874</literal></entry>
2726
       <entry><literal>UTF8</literal></entry>
2727
       <entry><literal>WIN874</literal></entry>
2728
      </row>
2729
2730
      <row>
2731
       <entry><literal>windows_1250_to_iso_8859_2</literal></entry>
2732
       <entry><literal>WIN1250</literal></entry>
2733
       <entry><literal>LATIN2</literal></entry>
2734
      </row>
2735
2736
      <row>
2737
       <entry><literal>windows_1250_to_mic</literal></entry>
2738
       <entry><literal>WIN1250</literal></entry>
2739
       <entry><literal>MULE_INTERNAL</literal></entry>
2740
      </row>
2741
2742
      <row>
2743
       <entry><literal>windows_1250_to_utf8</literal></entry>
2744
       <entry><literal>WIN1250</literal></entry>
2745
       <entry><literal>UTF8</literal></entry>
2746
      </row>
2747
2748
      <row>
2749
       <entry><literal>windows_1251_to_iso_8859_5</literal></entry>
2750
       <entry><literal>WIN1251</literal></entry>
2751
       <entry><literal>ISO_8859_5</literal></entry>
2752
      </row>
2753
2754
      <row>
2755
       <entry><literal>windows_1251_to_koi8_r</literal></entry>
2756
       <entry><literal>WIN1251</literal></entry>
2757
       <entry><literal>KOI8R</literal></entry>
2758
      </row>
2759
2760
      <row>
2761
       <entry><literal>windows_1251_to_mic</literal></entry>
2762
       <entry><literal>WIN1251</literal></entry>
2763
       <entry><literal>MULE_INTERNAL</literal></entry>
2764
      </row>
2765
2766
      <row>
2767
       <entry><literal>windows_1251_to_utf8</literal></entry>
2768
       <entry><literal>WIN1251</literal></entry>
2769
       <entry><literal>UTF8</literal></entry>
2770
      </row>
2771
2772
      <row>
2773
       <entry><literal>windows_1251_to_windows_866</literal></entry>
2774
       <entry><literal>WIN1251</literal></entry>
2775
       <entry><literal>WIN866</literal></entry>
2776
      </row>
2777
2778
      <row>
2779
       <entry><literal>windows_1252_to_utf8</literal></entry>
2780
       <entry><literal>WIN1252</literal></entry>
2781
       <entry><literal>UTF8</literal></entry>
2782
      </row>
2783
2784
      <row>
2785
       <entry><literal>windows_1256_to_utf8</literal></entry>
2786
       <entry><literal>WIN1256</literal></entry>
2787
       <entry><literal>UTF8</literal></entry>
2788
      </row>
2789
2790
      <row>
2791
       <entry><literal>windows_866_to_iso_8859_5</literal></entry>
2792
       <entry><literal>WIN866</literal></entry>
2793
       <entry><literal>ISO_8859_5</literal></entry>
2794
      </row>
2795
2796
      <row>
2797
       <entry><literal>windows_866_to_koi8_r</literal></entry>
2798
       <entry><literal>WIN866</literal></entry>
2799
       <entry><literal>KOI8R</literal></entry>
2800
      </row>
2801
2802
      <row>
2803
       <entry><literal>windows_866_to_mic</literal></entry>
2804
       <entry><literal>WIN866</literal></entry>
2805
       <entry><literal>MULE_INTERNAL</literal></entry>
2806
      </row>
2807
2808
      <row>
2809
       <entry><literal>windows_866_to_utf8</literal></entry>
2810
       <entry><literal>WIN866</literal></entry>
2811
       <entry><literal>UTF8</literal></entry>
2812
      </row>
2813
2814
      <row>
2815
       <entry><literal>windows_866_to_windows_1251</literal></entry>
2816
       <entry><literal>WIN866</literal></entry>
2817
       <entry><literal>WIN</literal></entry>
2818
      </row>
2819
2820
      <row>
2821
       <entry><literal>windows_874_to_utf8</literal></entry>
2822
       <entry><literal>WIN874</literal></entry>
2823
       <entry><literal>UTF8</literal></entry>
2824
      </row>
2825
2826
      <row>
2827
       <entry><literal>euc_jis_2004_to_utf8</literal></entry>
2828
       <entry><literal>EUC_JIS_2004</literal></entry>
2829
       <entry><literal>UTF8</literal></entry>
2830
      </row>
2831
2832
      <row>
1.1.2 by Martin Pitt
Import upstream version 9.3~rc1
2833
       <entry><literal>utf8_to_euc_jis_2004</literal></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
2834
       <entry><literal>UTF8</literal></entry>
2835
       <entry><literal>EUC_JIS_2004</literal></entry>
2836
      </row>
2837
2838
      <row>
2839
       <entry><literal>shift_jis_2004_to_utf8</literal></entry>
2840
       <entry><literal>SHIFT_JIS_2004</literal></entry>
2841
       <entry><literal>UTF8</literal></entry>
2842
      </row>
2843
2844
      <row>
1.1.2 by Martin Pitt
Import upstream version 9.3~rc1
2845
       <entry><literal>utf8_to_shift_jis_2004</literal></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
2846
       <entry><literal>UTF8</literal></entry>
2847
       <entry><literal>SHIFT_JIS_2004</literal></entry>
2848
      </row>
2849
2850
      <row>
2851
       <entry><literal>euc_jis_2004_to_shift_jis_2004</literal></entry>
2852
       <entry><literal>EUC_JIS_2004</literal></entry>
2853
       <entry><literal>SHIFT_JIS_2004</literal></entry>
2854
      </row>
2855
2856
      <row>
2857
       <entry><literal>shift_jis_2004_to_euc_jis_2004</literal></entry>
2858
       <entry><literal>SHIFT_JIS_2004</literal></entry>
2859
       <entry><literal>EUC_JIS_2004</literal></entry>
2860
      </row>
2861
2862
     </tbody>
2863
    </tgroup>
2864
   </table>
2865
2866
   <sect2 id="functions-string-format">
2867
    <title><function>format</function></title>
2868
2869
    <indexterm>
2870
     <primary>format</primary>
2871
    </indexterm>
2872
2873
    <para>
2874
     The function <function>format</> produces output formatted according to
2875
     a format string, in a style similar to the C function
2876
     <function>sprintf</>.
2877
    </para>
2878
2879
    <para>
2880
<synopsis>
2881
<function>format</>(<parameter>formatstr</> <type>text</> [, <parameter>formatarg</> <type>"any"</> [, ...] ])
2882
</synopsis>
2883
     <replaceable>formatstr</> is a format string that specifies how the
2884
     result should be formatted.  Text in the format string is copied
2885
     directly to the result, except where <firstterm>format specifiers</> are
2886
     used.  Format specifiers act as placeholders in the string, defining how
2887
     subsequent function arguments should be formatted and inserted into the
2888
     result.  Each <replaceable>formatarg</> argument is converted to text
2889
     according to the usual output rules for its data type, and then formatted
2890
     and inserted into the result string according to the format specifier(s).
2891
    </para>
2892
2893
    <para>
2894
     Format specifiers are introduced by a <literal>%</> character and have
2895
     the form
2896
<synopsis>
2897
%[<replaceable>position</>][<replaceable>flags</>][<replaceable>width</>]<replaceable>type</>
2898
</synopsis>
2899
     where the component fields are:
2900
2901
     <variablelist>
2902
      <varlistentry>
2903
       <term><replaceable>position</replaceable> (optional)</term>
2904
       <listitem>
2905
        <para>
2906
         A string of the form <literal><replaceable>n</>$</> where
2907
         <replaceable>n</> is the index of the argument to print.
2908
         Index 1 means the first argument after
2909
         <replaceable>formatstr</>.  If the <replaceable>position</> is
2910
         omitted, the default is to use the next argument in sequence.
2911
        </para>
2912
       </listitem>
2913
      </varlistentry>
2914
2915
      <varlistentry>
2916
       <term><replaceable>flags</replaceable> (optional)</term>
2917
       <listitem>
2918
        <para>
2919
         Additional options controlling how the format specifier's output is
2920
         formatted.  Currently the only supported flag is a minus sign
2921
         (<literal>-</>) which will cause the format specifier's output to be
2922
         left-justified.  This has no effect unless the <replaceable>width</>
2923
         field is also specified.
2924
        </para>
2925
       </listitem>
2926
      </varlistentry>
2927
2928
      <varlistentry>
2929
       <term><replaceable>width</replaceable> (optional)</term>
2930
       <listitem>
2931
        <para>
2932
         Specifies the <emphasis>minimum</> number of characters to use to
2933
         display the format specifier's output.  The output is padded on the
2934
         left or right (depending on the <literal>-</> flag) with spaces as
2935
         needed to fill the width.  A too-small width does not cause
2936
         truncation of the output, but is simply ignored.  The width may be
2937
         specified using any of the following: a positive integer; an
2938
         asterisk (<literal>*</>) to use the next function argument as the
2939
         width; or a string of the form <literal>*<replaceable>n</>$</> to
2940
         use the <replaceable>n</>th function argument as the width.
2941
        </para>
2942
2943
        <para>
2944
         If the width comes from a function argument, that argument is
2945
         consumed before the argument that is used for the format specifier's
2946
         value.  If the width argument is negative, the result is left
2947
         aligned (as if the <literal>-</> flag had been specified) within a
2948
         field of length <function>abs</>(<replaceable>width</replaceable>).
2949
        </para>
2950
       </listitem>
2951
      </varlistentry>
2952
2953
      <varlistentry>
2954
       <term><replaceable>type</replaceable> (required)</term>
2955
       <listitem>
2956
        <para>
2957
         The type of format conversion to use to produce the format
2958
         specifier's output.  The following types are supported:
2959
         <itemizedlist>
2960
          <listitem>
2961
           <para>
2962
            <literal>s</literal> formats the argument value as a simple
2963
            string.  A null value is treated as an empty string.
2964
           </para>
2965
          </listitem>
2966
          <listitem>
2967
           <para>
2968
            <literal>I</literal> treats the argument value as an SQL
2969
            identifier, double-quoting it if necessary.
2970
            It is an error for the value to be null.
2971
           </para>
2972
          </listitem>
2973
          <listitem>
2974
           <para>
2975
            <literal>L</literal> quotes the argument value as an SQL literal.
2976
            A null value is displayed as the string <literal>NULL</>, without
2977
            quotes.
2978
           </para>
2979
          </listitem>
2980
         </itemizedlist>
2981
        </para>
2982
       </listitem>
2983
      </varlistentry>
2984
     </variablelist>
2985
    </para>
2986
2987
    <para>
2988
     In addition to the format specifiers described above, the special sequence
2989
     <literal>%%</> may be used to output a literal <literal>%</> character.
2990
    </para>
2991
2992
    <para>
2993
     Here are some examples of the basic format conversions:
2994
2995
<screen>
2996
SELECT format('Hello %s', 'World');
2997
<lineannotation>Result: </lineannotation><computeroutput>Hello World</computeroutput>
2998
2999
SELECT format('Testing %s, %s, %s, %%', 'one', 'two', 'three');
3000
<lineannotation>Result: </><computeroutput>Testing one, two, three, %</>
3001
3002
SELECT format('INSERT INTO %I VALUES(%L)', 'Foo bar', E'O\'Reilly');
3003
<lineannotation>Result: </lineannotation><computeroutput>INSERT INTO "Foo bar" VALUES('O''Reilly')</computeroutput>
3004
3005
SELECT format('INSERT INTO %I VALUES(%L)', 'locations', E'C:\\Program Files');
3006
<lineannotation>Result: </lineannotation><computeroutput>INSERT INTO locations VALUES(E'C:\\Program Files')</computeroutput>
3007
</screen>
3008
    </para>
3009
3010
    <para>
3011
     Here are examples using <replaceable>width</replaceable> fields
3012
     and the <literal>-</> flag:
3013
3014
<screen>
3015
SELECT format('|%10s|', 'foo');
3016
<lineannotation>Result: </><computeroutput>|       foo|</>
3017
3018
SELECT format('|%-10s|', 'foo');
3019
<lineannotation>Result: </><computeroutput>|foo       |</>
3020
3021
SELECT format('|%*s|', 10, 'foo');
3022
<lineannotation>Result: </><computeroutput>|       foo|</>
3023
3024
SELECT format('|%*s|', -10, 'foo');
3025
<lineannotation>Result: </><computeroutput>|foo       |</>
3026
3027
SELECT format('|%-*s|', 10, 'foo');
3028
<lineannotation>Result: </><computeroutput>|foo       |</>
3029
3030
SELECT format('|%-*s|', -10, 'foo');
3031
<lineannotation>Result: </><computeroutput>|foo       |</>
3032
</screen>
3033
    </para>
3034
3035
    <para>
3036
     These examples show use of <replaceable>position</> fields:
3037
3038
<screen>
3039
SELECT format('Testing %3$s, %2$s, %1$s', 'one', 'two', 'three');
3040
<lineannotation>Result: </><computeroutput>Testing three, two, one</>
3041
3042
SELECT format('|%*2$s|', 'foo', 10, 'bar');
3043
<lineannotation>Result: </><computeroutput>|       bar|</>
3044
3045
SELECT format('|%1$*2$s|', 'foo', 10, 'bar');
3046
<lineannotation>Result: </><computeroutput>|       foo|</>
3047
</screen>
3048
    </para>
3049
3050
    <para>
3051
     Unlike the standard C function <function>sprintf</>,
3052
     <productname>PostgreSQL</>'s <function>format</> function allows format
3053
     specifiers with and without <replaceable>position</> fields to be mixed
3054
     in the same format string.  A format specifier without a
3055
     <replaceable>position</> field always uses the next argument after the
3056
     last argument consumed.
3057
     In addition, the <function>format</> function does not require all
3058
     function arguments to be used in the format string.
3059
     For example:
3060
3061
<screen>
3062
SELECT format('Testing %3$s, %2$s, %s', 'one', 'two', 'three');
3063
<lineannotation>Result: </><computeroutput>Testing three, two, three</>
3064
</screen>
3065
    </para>
3066
3067
    <para>
3068
     The <literal>%I</> and <literal>%L</> format specifiers are particularly
3069
     useful for safely constructing dynamic SQL statements.  See
3070
     <xref linkend="plpgsql-quote-literal-example">.
3071
    </para>
3072
   </sect2>
3073
3074
  </sect1>
3075
3076
3077
  <sect1 id="functions-binarystring">
3078
   <title>Binary String Functions and Operators</title>
3079
3080
   <indexterm zone="functions-binarystring">
3081
    <primary>binary data</primary>
3082
    <secondary>functions</secondary>
3083
   </indexterm>
3084
3085
   <para>
3086
    This section describes functions and operators for examining and
3087
    manipulating values of type <type>bytea</type>.
3088
   </para>
3089
3090
   <para>
3091
    <acronym>SQL</acronym> defines some string functions that use
3092
    key words, rather than commas, to separate
3093
    arguments.  Details are in
3094
    <xref linkend="functions-binarystring-sql">.
3095
    <productname>PostgreSQL</> also provides versions of these functions
3096
    that use the regular function invocation syntax
3097
    (see <xref linkend="functions-binarystring-other">).
3098
   </para>
3099
3100
   <note>
3101
    <para>
3102
     The sample results shown on this page assume that the server parameter
3103
     <link linkend="guc-bytea-output"><varname>bytea_output</></link> is set
3104
     to <literal>escape</literal> (the traditional PostgreSQL format).
3105
    </para>
3106
   </note>
3107
3108
   <table id="functions-binarystring-sql">
3109
    <title><acronym>SQL</acronym> Binary String Functions and Operators</title>
3110
    <tgroup cols="5">
3111
     <thead>
3112
      <row>
3113
       <entry>Function</entry>
3114
       <entry>Return Type</entry>
3115
       <entry>Description</entry>
3116
       <entry>Example</entry>
3117
       <entry>Result</entry>
3118
      </row>
3119
     </thead>
3120
3121
     <tbody>
3122
      <row>
3123
       <entry><literal><parameter>string</parameter> <literal>||</literal>
3124
        <parameter>string</parameter></literal></entry>
3125
       <entry> <type>bytea</type> </entry>
3126
       <entry>
3127
        String concatenation
3128
        <indexterm>
3129
         <primary>binary string</primary>
3130
         <secondary>concatenation</secondary>
3131
        </indexterm>
3132
       </entry>
3133
       <entry><literal>E'\\\\Post'::bytea || E'\\047gres\\000'::bytea</literal></entry>
3134
       <entry><literal>\\Post'gres\000</literal></entry>
3135
      </row>
3136
3137
      <row>
3138
       <entry>
3139
        <indexterm>
3140
         <primary>octet_length</primary>
3141
        </indexterm>
3142
        <literal><function>octet_length(<parameter>string</parameter>)</function></literal>
3143
       </entry>
3144
       <entry><type>int</type></entry>
3145
       <entry>Number of bytes in binary string</entry>
3146
       <entry><literal>octet_length(E'jo\\000se'::bytea)</literal></entry>
3147
       <entry><literal>5</literal></entry>
3148
      </row>
3149
3150
      <row>
3151
       <entry>
3152
        <indexterm>
3153
         <primary>overlay</primary>
3154
        </indexterm>
3155
        <literal><function>overlay(<parameter>string</parameter> placing <parameter>string</parameter> from <type>int</type> <optional>for <type>int</type></optional>)</function></literal>
3156
       </entry>
3157
       <entry><type>bytea</type></entry>
3158
       <entry>
3159
        Replace substring
3160
       </entry>
3161
       <entry><literal>overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 2 for 3)</literal></entry>
3162
       <entry><literal>T\\002\\003mas</literal></entry>
3163
      </row>
3164
3165
      <row>
3166
       <entry>
3167
        <indexterm>
3168
         <primary>position</primary>
3169
        </indexterm>
3170
        <literal><function>position(<parameter>substring</parameter> in <parameter>string</parameter>)</function></literal>
3171
       </entry>
3172
       <entry><type>int</type></entry>
3173
       <entry>Location of specified substring</entry>
3174
      <entry><literal>position(E'\\000om'::bytea in E'Th\\000omas'::bytea)</literal></entry>
3175
       <entry><literal>3</literal></entry>
3176
      </row>
3177
3178
      <row>
3179
       <entry>
3180
        <indexterm>
3181
         <primary>substring</primary>
3182
        </indexterm>
3183
        <literal><function>substring(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</function></literal>
3184
       </entry>
3185
       <entry><type>bytea</type></entry>
3186
       <entry>
3187
        Extract substring
3188
       </entry>
3189
       <entry><literal>substring(E'Th\\000omas'::bytea from 2 for 3)</literal></entry>
3190
       <entry><literal>h\000o</literal></entry>
3191
      </row>
3192
3193
      <row>
3194
       <entry>
3195
        <indexterm>
3196
         <primary>trim</primary>
3197
        </indexterm>
3198
        <literal><function>trim(<optional>both</optional>
3199
        <parameter>bytes</parameter> from
3200
        <parameter>string</parameter>)</function></literal>
3201
       </entry>
3202
       <entry><type>bytea</type></entry>
3203
       <entry>
3204
        Remove the longest string containing only the bytes in
3205
        <parameter>bytes</parameter> from the start
3206
        and end of <parameter>string</parameter>
3207
       </entry>
3208
       <entry><literal>trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea)</literal></entry>
3209
       <entry><literal>Tom</literal></entry>
3210
      </row>
3211
     </tbody>
3212
    </tgroup>
3213
   </table>
3214
3215
   <para>
3216
    Additional binary string manipulation functions are available and
3217
    are listed in <xref linkend="functions-binarystring-other">.  Some
3218
    of them are used internally to implement the
3219
    <acronym>SQL</acronym>-standard string functions listed in <xref
3220
    linkend="functions-binarystring-sql">.
3221
   </para>
3222
3223
   <table id="functions-binarystring-other">
3224
    <title>Other Binary String Functions</title>
3225
    <tgroup cols="5">
3226
     <thead>
3227
      <row>
3228
       <entry>Function</entry>
3229
       <entry>Return Type</entry>
3230
       <entry>Description</entry>
3231
       <entry>Example</entry>
3232
       <entry>Result</entry>
3233
      </row>
3234
     </thead>
3235
3236
     <tbody>
3237
      <row>
3238
       <entry>
3239
        <indexterm>
3240
         <primary>btrim</primary>
3241
        </indexterm>
3242
        <literal><function>btrim(<parameter>string</parameter>
3243
        <type>bytea</type>, <parameter>bytes</parameter> <type>bytea</type>)</function></literal>
3244
       </entry>
3245
       <entry><type>bytea</type></entry>
3246
       <entry>
3247
        Remove the longest string consisting only of bytes
3248
        in <parameter>bytes</parameter> from the start and end of
3249
        <parameter>string</parameter>
3250
      </entry>
3251
      <entry><literal>btrim(E'\\000trim\\000'::bytea, E'\\000'::bytea)</literal></entry>
3252
      <entry><literal>trim</literal></entry>
3253
     </row>
3254
3255
     <row>
3256
      <entry>
3257
        <indexterm>
3258
         <primary>decode</primary>
3259
        </indexterm>
3260
       <literal><function>decode(<parameter>string</parameter> <type>text</type>,
3261
       <parameter>format</parameter> <type>text</type>)</function></literal>
3262
      </entry>
3263
      <entry><type>bytea</type></entry>
3264
      <entry>
3265
       Decode binary data from textual representation in <parameter>string</>.
3266
       Options for <parameter>format</> are same as in <function>encode</>.
3267
      </entry>
3268
      <entry><literal>decode(E'123\\000456', 'escape')</literal></entry>
3269
      <entry><literal>123\000456</literal></entry>
3270
     </row>
3271
3272
     <row>
3273
      <entry>
3274
        <indexterm>
3275
         <primary>encode</primary>
3276
        </indexterm>
3277
       <literal><function>encode(<parameter>data</parameter> <type>bytea</type>,
3278
       <parameter>format</parameter> <type>text</type>)</function></literal>
3279
      </entry>
3280
      <entry><type>text</type></entry>
3281
      <entry>
3282
       Encode binary data into a textual representation.  Supported
3283
       formats are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
3284
       <literal>escape</> converts zero bytes and high-bit-set bytes to
3285
       octal sequences (<literal>\</><replaceable>nnn</>) and
3286
       doubles backslashes.
3287
      </entry>
3288
      <entry><literal>encode(E'123\\000456'::bytea, 'escape')</literal></entry>
3289
      <entry><literal>123\000456</literal></entry>
3290
     </row>
3291
3292
      <row>
3293
       <entry>
3294
        <indexterm>
3295
         <primary>get_bit</primary>
3296
        </indexterm>
3297
        <literal><function>get_bit(<parameter>string</parameter>, <parameter>offset</parameter>)</function></literal>
3298
       </entry>
3299
       <entry><type>int</type></entry>
3300
       <entry>
3301
        Extract bit from string
3302
       </entry>
3303
       <entry><literal>get_bit(E'Th\\000omas'::bytea, 45)</literal></entry>
3304
       <entry><literal>1</literal></entry>
3305
      </row>
3306
3307
      <row>
3308
       <entry>
3309
        <indexterm>
3310
         <primary>get_byte</primary>
3311
        </indexterm>
3312
        <literal><function>get_byte(<parameter>string</parameter>, <parameter>offset</parameter>)</function></literal>
3313
       </entry>
3314
       <entry><type>int</type></entry>
3315
       <entry>
3316
        Extract byte from string
3317
       </entry>
3318
       <entry><literal>get_byte(E'Th\\000omas'::bytea, 4)</literal></entry>
3319
       <entry><literal>109</literal></entry>
3320
      </row>
3321
3322
     <row>
3323
      <entry>
3324
       <indexterm>
3325
        <primary>length</primary>
3326
       </indexterm>
3327
       <literal><function>length(<parameter>string</parameter>)</function></literal>
3328
      </entry>
3329
      <entry><type>int</type></entry>
3330
      <entry>
3331
       Length of binary string
3332
       <indexterm>
3333
        <primary>binary string</primary>
3334
        <secondary>length</secondary>
3335
       </indexterm>
3336
       <indexterm>
3337
        <primary>length</primary>
3338
        <secondary sortas="binary string">of a binary string</secondary>
3339
        <see>binary strings, length</see>
3340
       </indexterm>
3341
      </entry>
3342
      <entry><literal>length(E'jo\\000se'::bytea)</literal></entry>
3343
      <entry><literal>5</literal></entry>
3344
     </row>
3345
3346
     <row>
3347
      <entry>
3348
       <indexterm>
3349
        <primary>md5</primary>
3350
       </indexterm>
3351
       <literal><function>md5(<parameter>string</parameter>)</function></literal>
3352
      </entry>
3353
      <entry><type>text</type></entry>
3354
      <entry>
3355
       Calculates the MD5 hash of <parameter>string</parameter>,
3356
       returning the result in hexadecimal
3357
      </entry>
3358
      <entry><literal>md5(E'Th\\000omas'::bytea)</literal></entry>
3359
      <entry><literal>8ab2d3c9689aaf18 b4958c334c82d8b1</literal></entry>
3360
     </row>
3361
3362
      <row>
3363
       <entry>
3364
        <indexterm>
3365
         <primary>set_bit</primary>
3366
        </indexterm>
3367
        <literal><function>set_bit(<parameter>string</parameter>,
3368
        <parameter>offset</parameter>, <parameter>newvalue</>)</function></literal>
3369
       </entry>
3370
       <entry><type>bytea</type></entry>
3371
       <entry>
3372
        Set bit in string
3373
       </entry>
3374
       <entry><literal>set_bit(E'Th\\000omas'::bytea, 45, 0)</literal></entry>
3375
       <entry><literal>Th\000omAs</literal></entry>
3376
      </row>
3377
3378
      <row>
3379
       <entry>
3380
        <indexterm>
3381
         <primary>set_byte</primary>
3382
        </indexterm>
3383
        <literal><function>set_byte(<parameter>string</parameter>,
3384
        <parameter>offset</parameter>, <parameter>newvalue</>)</function></literal>
3385
       </entry>
3386
       <entry><type>bytea</type></entry>
3387
       <entry>
3388
        Set byte in string
3389
       </entry>
3390
       <entry><literal>set_byte(E'Th\\000omas'::bytea, 4, 64)</literal></entry>
3391
       <entry><literal>Th\000o@as</literal></entry>
3392
      </row>
3393
    </tbody>
3394
   </tgroup>
3395
  </table>
3396
3397
  <para>
3398
   <function>get_byte</> and <function>set_byte</> number the first byte
3399
   of a binary string as byte 0.
3400
   <function>get_bit</> and <function>set_bit</> number bits from the
3401
   right within each byte; for example bit 0 is the least significant bit of
3402
   the first byte, and bit 15 is the most significant bit of the second byte.
3403
  </para>
3404
3405
  <para>
3406
   See also the aggregate function <function>string_agg</function> in
3407
   <xref linkend="functions-aggregate">.
3408
  </para>
3409
 </sect1>
3410
3411
3412
  <sect1 id="functions-bitstring">
3413
   <title>Bit String Functions and Operators</title>
3414
3415
   <indexterm zone="functions-bitstring">
3416
    <primary>bit strings</primary>
3417
    <secondary>functions</secondary>
3418
   </indexterm>
3419
3420
   <para>
3421
    This section describes functions and operators for examining and
3422
    manipulating bit strings, that is values of the types
3423
    <type>bit</type> and <type>bit varying</type>.  Aside from the
3424
    usual comparison operators, the operators
3425
    shown in <xref linkend="functions-bit-string-op-table"> can be used.
3426
    Bit string operands of <literal>&amp;</literal>, <literal>|</literal>,
3427
    and <literal>#</literal> must be of equal length.  When bit
3428
    shifting, the original length of the string is preserved, as shown
3429
    in the examples.
3430
   </para>
3431
3432
   <table id="functions-bit-string-op-table">
3433
    <title>Bit String Operators</title>
3434
3435
    <tgroup cols="4">
3436
     <thead>
3437
      <row>
3438
       <entry>Operator</entry>
3439
       <entry>Description</entry>
3440
       <entry>Example</entry>
3441
       <entry>Result</entry>
3442
      </row>
3443
     </thead>
3444
3445
     <tbody>
3446
      <row>
3447
       <entry> <literal>||</literal> </entry>
3448
       <entry>concatenation</entry>
3449
       <entry><literal>B'10001' || B'011'</literal></entry>
3450
       <entry><literal>10001011</literal></entry>
3451
      </row>
3452
3453
      <row>
3454
       <entry> <literal>&amp;</literal> </entry>
3455
       <entry>bitwise AND</entry>
3456
       <entry><literal>B'10001' &amp; B'01101'</literal></entry>
3457
       <entry><literal>00001</literal></entry>
3458
      </row>
3459
3460
      <row>
3461
       <entry> <literal>|</literal> </entry>
3462
       <entry>bitwise OR</entry>
3463
       <entry><literal>B'10001' | B'01101'</literal></entry>
3464
       <entry><literal>11101</literal></entry>
3465
      </row>
3466
3467
      <row>
3468
       <entry> <literal>#</literal> </entry>
3469
       <entry>bitwise XOR</entry>
3470
       <entry><literal>B'10001' # B'01101'</literal></entry>
3471
       <entry><literal>11100</literal></entry>
3472
      </row>
3473
3474
      <row>
3475
       <entry> <literal>~</literal> </entry>
3476
       <entry>bitwise NOT</entry>
3477
       <entry><literal>~ B'10001'</literal></entry>
3478
       <entry><literal>01110</literal></entry>
3479
      </row>
3480
3481
      <row>
3482
       <entry> <literal>&lt;&lt;</literal> </entry>
3483
       <entry>bitwise shift left</entry>
3484
       <entry><literal>B'10001' &lt;&lt; 3</literal></entry>
3485
       <entry><literal>01000</literal></entry>
3486
      </row>
3487
3488
      <row>
3489
       <entry> <literal>&gt;&gt;</literal> </entry>
3490
       <entry>bitwise shift right</entry>
3491
       <entry><literal>B'10001' &gt;&gt; 2</literal></entry>
3492
       <entry><literal>00100</literal></entry>
3493
      </row>
3494
     </tbody>
3495
    </tgroup>
3496
   </table>
3497
3498
   <para>
3499
    The following <acronym>SQL</acronym>-standard functions work on bit
3500
    strings as well as character strings:
3501
    <literal><function>length</function></literal>,
3502
    <literal><function>bit_length</function></literal>,
3503
    <literal><function>octet_length</function></literal>,
3504
    <literal><function>position</function></literal>,
3505
    <literal><function>substring</function></literal>,
3506
    <literal><function>overlay</function></literal>.
3507
   </para>
3508
3509
   <para>
3510
    The following functions work on bit strings as well as binary
3511
    strings:
3512
    <literal><function>get_bit</function></literal>,
3513
    <literal><function>set_bit</function></literal>.
3514
    When working with a bit string, these functions number the first
3515
    (leftmost) bit of the string as bit 0.
3516
   </para>
3517
3518
   <para>
3519
    In addition, it is possible to cast integral values to and from type
3520
    <type>bit</>.
3521
    Some examples:
3522
<programlisting>
3523
44::bit(10)                    <lineannotation>0000101100</lineannotation>
3524
44::bit(3)                     <lineannotation>100</lineannotation>
3525
cast(-44 as bit(12))           <lineannotation>111111010100</lineannotation>
3526
'1110'::bit(4)::integer        <lineannotation>14</lineannotation>
3527
</programlisting>
3528
    Note that casting to just <quote>bit</> means casting to
3529
    <literal>bit(1)</>, and so will deliver only the least significant
3530
    bit of the integer.
3531
   </para>
3532
3533
    <note>
3534
     <para>
3535
      Prior to <productname>PostgreSQL</productname> 8.0, casting an
3536
      integer to <type>bit(n)</> would copy the leftmost <literal>n</>
3537
      bits of the integer, whereas now it copies the rightmost <literal>n</>
3538
      bits.  Also, casting an integer to a bit string width wider than
3539
      the integer itself will sign-extend on the left.
3540
     </para>
3541
    </note>
3542
3543
  </sect1>
3544
3545
3546
 <sect1 id="functions-matching">
3547
  <title>Pattern Matching</title>
3548
3549
  <indexterm zone="functions-matching">
3550
   <primary>pattern matching</primary>
3551
  </indexterm>
3552
3553
   <para>
3554
    There are three separate approaches to pattern matching provided
3555
    by <productname>PostgreSQL</productname>: the traditional
3556
    <acronym>SQL</acronym> <function>LIKE</function> operator, the
3557
    more recent <function>SIMILAR TO</function> operator (added in
3558
    SQL:1999), and <acronym>POSIX</acronym>-style regular
3559
    expressions.  Aside from the basic <quote>does this string match
3560
    this pattern?</> operators, functions are available to extract
3561
    or replace matching substrings and to split a string at matching
3562
    locations.
3563
   </para>
3564
3565
   <tip>
3566
    <para>
3567
     If you have pattern matching needs that go beyond this,
3568
     consider writing a user-defined function in Perl or Tcl.
3569
    </para>
3570
   </tip>
3571
1.2.3 by Martin Pitt
Import upstream version 9.3.10
3572
   <caution>
3573
    <para>
3574
     While most regular-expression searches can be executed very quickly,
3575
     regular expressions can be contrived that take arbitrary amounts of
3576
     time and memory to process.  Be wary of accepting regular-expression
3577
     search patterns from hostile sources.  If you must do so, it is
3578
     advisable to impose a statement timeout.
3579
    </para>
3580
3581
    <para>
3582
     Searches using <function>SIMILAR TO</function> patterns have the same
3583
     security hazards, since <function>SIMILAR TO</function> provides many
3584
     of the same capabilities as <acronym>POSIX</acronym>-style regular
3585
     expressions.
3586
    </para>
3587
3588
    <para>
3589
     <function>LIKE</function> searches, being much simpler than the other
3590
     two options, are safer to use with possibly-hostile pattern sources.
3591
    </para>
3592
   </caution>
3593
1 by Martin Pitt
Import upstream version 9.3~beta1
3594
  <sect2 id="functions-like">
3595
   <title><function>LIKE</function></title>
3596
3597
   <indexterm>
3598
    <primary>LIKE</primary>
3599
   </indexterm>
3600
3601
<synopsis>
3602
<replaceable>string</replaceable> LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3603
<replaceable>string</replaceable> NOT LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3604
</synopsis>
3605
3606
    <para>
3607
     The <function>LIKE</function> expression returns true if the
3608
     <replaceable>string</replaceable> matches the supplied
3609
     <replaceable>pattern</replaceable>.  (As
3610
     expected, the <function>NOT LIKE</function> expression returns
3611
     false if <function>LIKE</function> returns true, and vice versa.
3612
     An equivalent expression is
3613
     <literal>NOT (<replaceable>string</replaceable> LIKE
3614
      <replaceable>pattern</replaceable>)</literal>.)
3615
    </para>
3616
3617
    <para>
3618
     If <replaceable>pattern</replaceable> does not contain percent
3619
     signs or underscores, then the pattern only represents the string
3620
     itself; in that case <function>LIKE</function> acts like the
3621
     equals operator.  An underscore (<literal>_</literal>) in
3622
     <replaceable>pattern</replaceable> stands for (matches) any single
3623
     character; a percent sign (<literal>%</literal>) matches any sequence
3624
     of zero or more characters.
3625
    </para>
3626
3627
   <para>
3628
    Some examples:
3629
<programlisting>
3630
'abc' LIKE 'abc'    <lineannotation>true</lineannotation>
3631
'abc' LIKE 'a%'     <lineannotation>true</lineannotation>
3632
'abc' LIKE '_b_'    <lineannotation>true</lineannotation>
3633
'abc' LIKE 'c'      <lineannotation>false</lineannotation>
3634
</programlisting>
3635
   </para>
3636
3637
   <para>
3638
    <function>LIKE</function> pattern matching always covers the entire
3639
    string.  Therefore, if it's desired to match a sequence anywhere within
3640
    a string, the pattern must start and end with a percent sign.
3641
   </para>
3642
3643
   <para>
3644
    To match a literal underscore or percent sign without matching
3645
    other characters, the respective character in
3646
    <replaceable>pattern</replaceable> must be
3647
    preceded by the escape character.  The default escape
3648
    character is the backslash but a different one can be selected by
3649
    using the <literal>ESCAPE</literal> clause.  To match the escape
3650
    character itself, write two escape characters.
3651
   </para>
3652
3653
   <note>
3654
    <para>
3655
     If you have <xref linkend="guc-standard-conforming-strings"> turned off,
3656
     any backslashes you write in literal string constants will need to be
3657
     doubled.  See <xref linkend="sql-syntax-strings"> for more information.
3658
    </para>
3659
   </note>
3660
3661
   <para>
3662
    It's also possible to select no escape character by writing
3663
    <literal>ESCAPE ''</literal>.  This effectively disables the
3664
    escape mechanism, which makes it impossible to turn off the
3665
    special meaning of underscore and percent signs in the pattern.
3666
   </para>
3667
3668
   <para>
3669
    The key word <token>ILIKE</token> can be used instead of
3670
    <token>LIKE</token> to make the match case-insensitive according
3671
    to the active locale.  This is not in the <acronym>SQL</acronym> standard but is a
3672
    <productname>PostgreSQL</productname> extension.
3673
   </para>
3674
3675
   <para>
3676
    The operator <literal>~~</literal> is equivalent to
3677
    <function>LIKE</function>, and <literal>~~*</literal> corresponds to
3678
    <function>ILIKE</function>.  There are also
3679
    <literal>!~~</literal> and <literal>!~~*</literal> operators that
3680
    represent <function>NOT LIKE</function> and <function>NOT
3681
    ILIKE</function>, respectively.  All of these operators are
3682
    <productname>PostgreSQL</productname>-specific.
3683
   </para>
3684
  </sect2>
3685
3686
3687
  <sect2 id="functions-similarto-regexp">
3688
   <title><function>SIMILAR TO</function> Regular Expressions</title>
3689
3690
   <indexterm>
3691
    <primary>regular expression</primary>
3692
    <!-- <seealso>pattern matching</seealso> breaks index build -->
3693
   </indexterm>
3694
3695
   <indexterm>
3696
    <primary>SIMILAR TO</primary>
3697
   </indexterm>
3698
   <indexterm>
3699
    <primary>substring</primary>
3700
   </indexterm>
3701
3702
<synopsis>
3703
<replaceable>string</replaceable> SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3704
<replaceable>string</replaceable> NOT SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
3705
</synopsis>
3706
3707
   <para>
3708
    The <function>SIMILAR TO</function> operator returns true or
3709
    false depending on whether its pattern matches the given string.
3710
    It is similar to <function>LIKE</function>, except that it
3711
    interprets the pattern using the SQL standard's definition of a
3712
    regular expression.  SQL regular expressions are a curious cross
3713
    between <function>LIKE</function> notation and common regular
3714
    expression notation.
3715
   </para>
3716
3717
   <para>
3718
    Like <function>LIKE</function>, the <function>SIMILAR TO</function>
3719
    operator succeeds only if its pattern matches the entire string;
3720
    this is unlike common regular expression behavior where the pattern
3721
    can match any part of the string.
3722
    Also like
3723
    <function>LIKE</function>, <function>SIMILAR TO</function> uses
3724
    <literal>_</> and <literal>%</> as wildcard characters denoting
3725
    any single character and any string, respectively (these are
3726
    comparable to <literal>.</> and <literal>.*</> in POSIX regular
3727
    expressions).
3728
   </para>
3729
3730
   <para>
3731
    In addition to these facilities borrowed from <function>LIKE</function>,
3732
    <function>SIMILAR TO</function> supports these pattern-matching
3733
    metacharacters borrowed from POSIX regular expressions:
3734
3735
   <itemizedlist>
3736
    <listitem>
3737
     <para>
3738
      <literal>|</literal> denotes alternation (either of two alternatives).
3739
     </para>
3740
    </listitem>
3741
    <listitem>
3742
     <para>
3743
      <literal>*</literal> denotes repetition of the previous item zero
3744
      or more times.
3745
     </para>
3746
    </listitem>
3747
    <listitem>
3748
     <para>
3749
      <literal>+</literal> denotes repetition of the previous item one
3750
      or more times.
3751
     </para>
3752
    </listitem>
3753
    <listitem>
3754
     <para>
3755
      <literal>?</literal> denotes repetition of the previous item zero
3756
      or one time.
3757
     </para>
3758
    </listitem>
3759
    <listitem>
3760
     <para>
3761
      <literal>{</><replaceable>m</><literal>}</literal> denotes repetition
3762
      of the previous item exactly <replaceable>m</> times.
3763
     </para>
3764
    </listitem>
3765
    <listitem>
3766
     <para>
3767
      <literal>{</><replaceable>m</><literal>,}</literal> denotes repetition
3768
      of the previous item <replaceable>m</> or more times.
3769
     </para>
3770
    </listitem>
3771
    <listitem>
3772
     <para>
3773
      <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</>
3774
      denotes repetition of the previous item at least <replaceable>m</> and
3775
      not more than <replaceable>n</> times.
3776
     </para>
3777
    </listitem>
3778
    <listitem>
3779
     <para>
3780
      Parentheses <literal>()</literal> can be used to group items into
3781
      a single logical item.
3782
     </para>
3783
    </listitem>
3784
    <listitem>
3785
     <para>
3786
      A bracket expression <literal>[...]</literal> specifies a character
3787
      class, just as in POSIX regular expressions.
3788
     </para>
3789
    </listitem>
3790
   </itemizedlist>
3791
3792
    Notice that the period (<literal>.</>) is not a metacharacter
3793
    for <function>SIMILAR TO</>.
3794
   </para>
3795
3796
   <para>
3797
    As with <function>LIKE</>, a backslash disables the special meaning
3798
    of any of these metacharacters; or a different escape character can
3799
    be specified with <literal>ESCAPE</>.
3800
   </para>
3801
3802
   <para>
3803
    Some examples:
3804
<programlisting>
3805
'abc' SIMILAR TO 'abc'      <lineannotation>true</lineannotation>
3806
'abc' SIMILAR TO 'a'        <lineannotation>false</lineannotation>
3807
'abc' SIMILAR TO '%(b|d)%'  <lineannotation>true</lineannotation>
3808
'abc' SIMILAR TO '(b|c)%'   <lineannotation>false</lineannotation>
3809
</programlisting>
3810
   </para>
3811
3812
   <para>
3813
    The <function>substring</> function with three parameters,
3814
    <function>substring(<replaceable>string</replaceable> from
3815
    <replaceable>pattern</replaceable> for
3816
    <replaceable>escape-character</replaceable>)</function>, provides
3817
    extraction of a substring that matches an SQL
3818
    regular expression pattern.  As with <literal>SIMILAR TO</>, the
3819
    specified pattern must match the entire data string, or else the
3820
    function fails and returns null.  To indicate the part of the
3821
    pattern that should be returned on success, the pattern must contain
3822
    two occurrences of the escape character followed by a double quote
3823
    (<literal>"</>). <!-- " font-lock sanity -->
3824
    The text matching the portion of the pattern
3825
    between these markers is returned.
3826
   </para>
3827
3828
   <para>
3829
    Some examples, with <literal>#&quot;</> delimiting the return string:
3830
<programlisting>
3831
substring('foobar' from '%#"o_b#"%' for '#')   <lineannotation>oob</lineannotation>
3832
substring('foobar' from '#"o_b#"%' for '#')    <lineannotation>NULL</lineannotation>
3833
</programlisting>
3834
   </para>
3835
  </sect2>
3836
3837
  <sect2 id="functions-posix-regexp">
3838
   <title><acronym>POSIX</acronym> Regular Expressions</title>
3839
3840
   <indexterm zone="functions-posix-regexp">
3841
    <primary>regular expression</primary>
3842
    <seealso>pattern matching</seealso>
3843
   </indexterm>
3844
   <indexterm>
3845
    <primary>substring</primary>
3846
   </indexterm>
3847
   <indexterm>
3848
    <primary>regexp_replace</primary>
3849
   </indexterm>
3850
   <indexterm>
3851
    <primary>regexp_matches</primary>
3852
   </indexterm>
3853
   <indexterm>
3854
    <primary>regexp_split_to_table</primary>
3855
   </indexterm>
3856
   <indexterm>
3857
    <primary>regexp_split_to_array</primary>
3858
   </indexterm>
3859
3860
   <para>
3861
    <xref linkend="functions-posix-table"> lists the available
3862
    operators for pattern matching using POSIX regular expressions.
3863
   </para>
3864
3865
   <table id="functions-posix-table">
3866
    <title>Regular Expression Match Operators</title>
3867
3868
    <tgroup cols="3">
3869
     <thead>
3870
      <row>
3871
       <entry>Operator</entry>
3872
       <entry>Description</entry>
3873
       <entry>Example</entry>
3874
      </row>
3875
     </thead>
3876
3877
      <tbody>
3878
       <row>
3879
        <entry> <literal>~</literal> </entry>
3880
        <entry>Matches regular expression, case sensitive</entry>
3881
        <entry><literal>'thomas' ~ '.*thomas.*'</literal></entry>
3882
       </row>
3883
3884
       <row>
3885
        <entry> <literal>~*</literal> </entry>
3886
        <entry>Matches regular expression, case insensitive</entry>
3887
        <entry><literal>'thomas' ~* '.*Thomas.*'</literal></entry>
3888
       </row>
3889
3890
       <row>
3891
        <entry> <literal>!~</literal> </entry>
3892
        <entry>Does not match regular expression, case sensitive</entry>
3893
        <entry><literal>'thomas' !~ '.*Thomas.*'</literal></entry>
3894
       </row>
3895
3896
       <row>
3897
        <entry> <literal>!~*</literal> </entry>
3898
        <entry>Does not match regular expression, case insensitive</entry>
3899
        <entry><literal>'thomas' !~* '.*vadim.*'</literal></entry>
3900
       </row>
3901
      </tbody>
3902
     </tgroup>
3903
    </table>
3904
3905
    <para>
3906
     <acronym>POSIX</acronym> regular expressions provide a more
3907
     powerful means for pattern matching than the <function>LIKE</function> and
3908
     <function>SIMILAR TO</> operators.
3909
     Many Unix tools such as <command>egrep</command>,
3910
     <command>sed</command>, or <command>awk</command> use a pattern
3911
     matching language that is similar to the one described here.
3912
    </para>
3913
3914
    <para>
3915
     A regular expression is a character sequence that is an
3916
     abbreviated definition of a set of strings (a <firstterm>regular
3917
     set</firstterm>).  A string is said to match a regular expression
3918
     if it is a member of the regular set described by the regular
3919
     expression.  As with <function>LIKE</function>, pattern characters
3920
     match string characters exactly unless they are special characters
3921
     in the regular expression language &mdash; but regular expressions use
3922
     different special characters than <function>LIKE</function> does.
3923
     Unlike <function>LIKE</function> patterns, a
3924
     regular expression is allowed to match anywhere within a string, unless
3925
     the regular expression is explicitly anchored to the beginning or
3926
     end of the string.
3927
    </para>
3928
3929
    <para>
3930
     Some examples:
3931
<programlisting>
3932
'abc' ~ 'abc'    <lineannotation>true</lineannotation>
3933
'abc' ~ '^a'     <lineannotation>true</lineannotation>
3934
'abc' ~ '(b|d)'  <lineannotation>true</lineannotation>
3935
'abc' ~ '^(b|c)' <lineannotation>false</lineannotation>
3936
</programlisting>
3937
    </para>
3938
3939
    <para>
3940
     The <acronym>POSIX</acronym> pattern language is described in much
3941
     greater detail below.
3942
    </para>
3943
3944
    <para>
3945
     The <function>substring</> function with two parameters,
3946
     <function>substring(<replaceable>string</replaceable> from
3947
     <replaceable>pattern</replaceable>)</function>, provides extraction of a
3948
     substring
3949
     that matches a POSIX regular expression pattern.  It returns null if
3950
     there is no match, otherwise the portion of the text that matched the
3951
     pattern.  But if the pattern contains any parentheses, the portion
3952
     of the text that matched the first parenthesized subexpression (the
3953
     one whose left parenthesis comes first) is
3954
     returned.  You can put parentheses around the whole expression
3955
     if you want to use parentheses within it without triggering this
3956
     exception.  If you need parentheses in the pattern before the
3957
     subexpression you want to extract, see the non-capturing parentheses
3958
     described below.
3959
    </para>
3960
3961
   <para>
3962
    Some examples:
3963
<programlisting>
3964
substring('foobar' from 'o.b')     <lineannotation>oob</lineannotation>
3965
substring('foobar' from 'o(.)b')   <lineannotation>o</lineannotation>
3966
</programlisting>
3967
   </para>
3968
3969
    <para>
3970
     The <function>regexp_replace</> function provides substitution of
3971
     new text for substrings that match POSIX regular expression patterns.
3972
     It has the syntax
3973
     <function>regexp_replace</function>(<replaceable>source</>,
3974
     <replaceable>pattern</>, <replaceable>replacement</>
3975
     <optional>, <replaceable>flags</> </optional>).
3976
     The <replaceable>source</> string is returned unchanged if
3977
     there is no match to the <replaceable>pattern</>.  If there is a
3978
     match, the <replaceable>source</> string is returned with the
3979
     <replaceable>replacement</> string substituted for the matching
3980
     substring.  The <replaceable>replacement</> string can contain
3981
     <literal>\</><replaceable>n</>, where <replaceable>n</> is 1
3982
     through 9, to indicate that the source substring matching the
3983
     <replaceable>n</>'th parenthesized subexpression of the pattern should be
3984
     inserted, and it can contain <literal>\&amp;</> to indicate that the
3985
     substring matching the entire pattern should be inserted.  Write
3986
     <literal>\\</> if you need to put a literal backslash in the replacement
3987
     text.
3988
     The <replaceable>flags</> parameter is an optional text
3989
     string containing zero or more single-letter flags that change the
3990
     function's behavior.  Flag <literal>i</> specifies case-insensitive
3991
     matching, while flag <literal>g</> specifies replacement of each matching
3992
     substring rather than only the first one.  Other supported flags are
3993
     described in <xref linkend="posix-embedded-options-table">.
3994
    </para>
3995
3996
   <para>
3997
    Some examples:
3998
<programlisting>
3999
regexp_replace('foobarbaz', 'b..', 'X')
4000
                                   <lineannotation>fooXbaz</lineannotation>
4001
regexp_replace('foobarbaz', 'b..', 'X', 'g')
4002
                                   <lineannotation>fooXX</lineannotation>
4003
regexp_replace('foobarbaz', 'b(..)', E'X\\1Y', 'g')
4004
                                   <lineannotation>fooXarYXazY</lineannotation>
4005
</programlisting>
4006
   </para>
4007
4008
    <para>
4009
     The <function>regexp_matches</> function returns a text array of
4010
     all of the captured substrings resulting from matching a POSIX
4011
     regular expression pattern.  It has the syntax
4012
     <function>regexp_matches</function>(<replaceable>string</>, <replaceable>pattern</>
4013
     <optional>, <replaceable>flags</> </optional>).
4014
     The function can return no rows, one row, or multiple rows (see
4015
     the <literal>g</> flag below).  If the <replaceable>pattern</>
4016
     does not match, the function returns no rows.  If the pattern
4017
     contains no parenthesized subexpressions, then each row
4018
     returned is a single-element text array containing the substring
4019
     matching the whole pattern.  If the pattern contains parenthesized
4020
     subexpressions, the function returns a text array whose
4021
     <replaceable>n</>'th element is the substring matching the
4022
     <replaceable>n</>'th parenthesized subexpression of the pattern
4023
     (not counting <quote>non-capturing</> parentheses; see below for
4024
     details).
4025
     The <replaceable>flags</> parameter is an optional text
4026
     string containing zero or more single-letter flags that change the
4027
     function's behavior.  Flag <literal>g</> causes the function to find
4028
     each match in the string, not only the first one, and return a row for
4029
     each such match.  Other supported
4030
     flags are described in <xref linkend="posix-embedded-options-table">.
4031
    </para>
4032
4033
   <para>
4034
    Some examples:
4035
<programlisting>
4036
SELECT regexp_matches('foobarbequebaz', '(bar)(beque)');
4037
 regexp_matches 
4038
----------------
4039
 {bar,beque}
4040
(1 row)
4041
4042
SELECT regexp_matches('foobarbequebazilbarfbonk', '(b[^b]+)(b[^b]+)', 'g');
4043
 regexp_matches 
4044
----------------
4045
 {bar,beque}
4046
 {bazil,barf}
4047
(2 rows)
4048
4049
SELECT regexp_matches('foobarbequebaz', 'barbeque');
4050
 regexp_matches 
4051
----------------
4052
 {barbeque}
4053
(1 row)
4054
</programlisting>
4055
   </para>
4056
4057
   <para>
4058
    It is possible to force <function>regexp_matches()</> to always
4059
    return one row by using a sub-select;  this is particularly useful
4060
    in a <literal>SELECT</> target list when you want all rows
4061
    returned, even non-matching ones:
4062
<programlisting>
4063
SELECT col1, (SELECT regexp_matches(col2, '(bar)(beque)')) FROM tab;
4064
</programlisting>
4065
   </para>
4066
4067
    <para>
4068
     The <function>regexp_split_to_table</> function splits a string using a POSIX
4069
     regular expression pattern as a delimiter.  It has the syntax
4070
     <function>regexp_split_to_table</function>(<replaceable>string</>, <replaceable>pattern</>
4071
     <optional>, <replaceable>flags</> </optional>).
4072
     If there is no match to the <replaceable>pattern</>, the function returns the
4073
     <replaceable>string</>.  If there is at least one match, for each match it returns
4074
     the text from the end of the last match (or the beginning of the string)
4075
     to the beginning of the match.  When there are no more matches, it
4076
     returns the text from the end of the last match to the end of the string.
4077
     The <replaceable>flags</> parameter is an optional text string containing
4078
     zero or more single-letter flags that change the function's behavior.
4079
     <function>regexp_split_to_table</function> supports the flags described in
4080
     <xref linkend="posix-embedded-options-table">.
4081
    </para>
4082
4083
    <para>
4084
     The <function>regexp_split_to_array</> function behaves the same as
4085
     <function>regexp_split_to_table</>, except that <function>regexp_split_to_array</>
4086
     returns its result as an array of <type>text</>.  It has the syntax
4087
     <function>regexp_split_to_array</function>(<replaceable>string</>, <replaceable>pattern</>
4088
     <optional>, <replaceable>flags</> </optional>).
4089
     The parameters are the same as for <function>regexp_split_to_table</>.
4090
    </para>
4091
4092
   <para>
4093
    Some examples:
4094
<programlisting>
4095
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
4096
SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', E'\\s+') AS foo;
1 by Martin Pitt
Import upstream version 9.3~beta1
4097
  foo   
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
4098
-------
1 by Martin Pitt
Import upstream version 9.3~beta1
4099
 the    
4100
 quick  
4101
 brown  
4102
 fox    
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
4103
 jumps 
1 by Martin Pitt
Import upstream version 9.3~beta1
4104
 over   
4105
 the    
4106
 lazy   
4107
 dog    
4108
(9 rows)
4109
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
4110
SELECT regexp_split_to_array('the quick brown fox jumps over the lazy dog', E'\\s+');
1 by Martin Pitt
Import upstream version 9.3~beta1
4111
              regexp_split_to_array             
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
4112
-----------------------------------------------
4113
 {the,quick,brown,fox,jumps,over,the,lazy,dog}
1 by Martin Pitt
Import upstream version 9.3~beta1
4114
(1 row)
4115
4116
SELECT foo FROM regexp_split_to_table('the quick brown fox', E'\\s*') AS foo;
4117
 foo 
4118
-----
4119
 t         
4120
 h         
4121
 e         
4122
 q         
4123
 u         
4124
 i         
4125
 c         
4126
 k         
4127
 b         
4128
 r         
4129
 o         
4130
 w         
4131
 n         
4132
 f         
4133
 o         
4134
 x         
4135
(16 rows)
4136
</programlisting>
4137
   </para>
4138
4139
   <para>
4140
    As the last example demonstrates, the regexp split functions ignore
4141
    zero-length matches that occur at the start or end of the string
4142
    or immediately after a previous match.  This is contrary to the strict
4143
    definition of regexp matching that is implemented by
4144
    <function>regexp_matches</>, but is usually the most convenient behavior
4145
    in practice.  Other software systems such as Perl use similar definitions.
4146
   </para>
4147
4148
<!-- derived from the re_syntax.n man page -->
4149
4150
   <sect3 id="posix-syntax-details">
4151
    <title>Regular Expression Details</title>
4152
4153
   <para>
4154
    <productname>PostgreSQL</productname>'s regular expressions are implemented
4155
    using a software package written by Henry Spencer.  Much of
4156
    the description of regular expressions below is copied verbatim from his
4157
    manual.
4158
   </para>
4159
4160
   <para>
4161
    Regular expressions (<acronym>RE</acronym>s), as defined in
4162
    <acronym>POSIX</acronym> 1003.2, come in two forms:
4163
    <firstterm>extended</> <acronym>RE</acronym>s or <acronym>ERE</>s
4164
    (roughly those of <command>egrep</command>), and
4165
    <firstterm>basic</> <acronym>RE</acronym>s or <acronym>BRE</>s
4166
    (roughly those of <command>ed</command>).
4167
    <productname>PostgreSQL</productname> supports both forms, and
4168
    also implements some extensions
4169
    that are not in the POSIX standard, but have become widely used
4170
    due to their availability in programming languages such as Perl and Tcl.
4171
    <acronym>RE</acronym>s using these non-POSIX extensions are called
4172
    <firstterm>advanced</> <acronym>RE</acronym>s or <acronym>ARE</>s
4173
    in this documentation.  AREs are almost an exact superset of EREs,
4174
    but BREs have several notational incompatibilities (as well as being
4175
    much more limited).
4176
    We first describe the ARE and ERE forms, noting features that apply
4177
    only to AREs, and then describe how BREs differ.
4178
   </para>
4179
4180
   <note>
4181
    <para>
4182
     <productname>PostgreSQL</> always initially presumes that a regular
4183
     expression follows the ARE rules.  However, the more limited ERE or
4184
     BRE rules can be chosen by prepending an <firstterm>embedded option</>
4185
     to the RE pattern, as described in <xref linkend="posix-metasyntax">.
4186
     This can be useful for compatibility with applications that expect
4187
     exactly the <acronym>POSIX</acronym> 1003.2 rules.
4188
    </para>
4189
   </note>
4190
4191
   <para>
4192
    A regular expression is defined as one or more
4193
    <firstterm>branches</firstterm>, separated by
4194
    <literal>|</literal>.  It matches anything that matches one of the
4195
    branches.
4196
   </para>
4197
4198
   <para>
4199
    A branch is zero or more <firstterm>quantified atoms</> or
4200
    <firstterm>constraints</>, concatenated.
4201
    It matches a match for the first, followed by a match for the second, etc;
4202
    an empty branch matches the empty string.
4203
   </para>
4204
4205
   <para>
4206
    A quantified atom is an <firstterm>atom</> possibly followed
4207
    by a single <firstterm>quantifier</>.
4208
    Without a quantifier, it matches a match for the atom.
4209
    With a quantifier, it can match some number of matches of the atom.
4210
    An <firstterm>atom</firstterm> can be any of the possibilities
4211
    shown in <xref linkend="posix-atoms-table">.
4212
    The possible quantifiers and their meanings are shown in
4213
    <xref linkend="posix-quantifiers-table">.
4214
   </para>
4215
4216
   <para>
4217
    A <firstterm>constraint</> matches an empty string, but matches only when
4218
    specific conditions are met.  A constraint can be used where an atom
4219
    could be used, except it cannot be followed by a quantifier.
4220
    The simple constraints are shown in
4221
    <xref linkend="posix-constraints-table">;
4222
    some more constraints are described later.
4223
   </para>
4224
4225
4226
   <table id="posix-atoms-table">
4227
    <title>Regular Expression Atoms</title>
4228
4229
    <tgroup cols="2">
4230
     <thead>
4231
      <row>
4232
       <entry>Atom</entry>
4233
       <entry>Description</entry>
4234
      </row>
4235
     </thead>
4236
4237
      <tbody>
4238
       <row>
4239
       <entry> <literal>(</><replaceable>re</><literal>)</> </entry>
4240
       <entry> (where <replaceable>re</> is any regular expression)
4241
       matches a match for
4242
       <replaceable>re</>, with the match noted for possible reporting </entry>
4243
       </row>
4244
4245
       <row>
4246
       <entry> <literal>(?:</><replaceable>re</><literal>)</> </entry>
4247
       <entry> as above, but the match is not noted for reporting
4248
       (a <quote>non-capturing</> set of parentheses)
4249
       (AREs only) </entry>
4250
       </row>
4251
4252
       <row>
4253
       <entry> <literal>.</> </entry>
4254
       <entry> matches any single character </entry>
4255
       </row>
4256
4257
       <row>
4258
       <entry> <literal>[</><replaceable>chars</><literal>]</> </entry>
4259
       <entry> a <firstterm>bracket expression</>,
4260
       matching any one of the <replaceable>chars</> (see
4261
       <xref linkend="posix-bracket-expressions"> for more detail) </entry>
4262
       </row>
4263
4264
       <row>
4265
       <entry> <literal>\</><replaceable>k</> </entry>
4266
       <entry> (where <replaceable>k</> is a non-alphanumeric character)
4267
       matches that character taken as an ordinary character,
4268
       e.g., <literal>\\</> matches a backslash character </entry>
4269
       </row>
4270
4271
       <row>
4272
       <entry> <literal>\</><replaceable>c</> </entry>
4273
       <entry> where <replaceable>c</> is alphanumeric
4274
       (possibly followed by other characters)
4275
       is an <firstterm>escape</>, see <xref linkend="posix-escape-sequences">
4276
       (AREs only; in EREs and BREs, this matches <replaceable>c</>) </entry>
4277
       </row>
4278
4279
       <row>
4280
       <entry> <literal>{</> </entry>
4281
       <entry> when followed by a character other than a digit,
4282
       matches the left-brace character <literal>{</>;
4283
       when followed by a digit, it is the beginning of a
4284
       <replaceable>bound</> (see below) </entry>
4285
       </row>
4286
4287
       <row>
4288
       <entry> <replaceable>x</> </entry>
4289
       <entry> where <replaceable>x</> is a single character with no other
4290
       significance, matches that character </entry>
4291
       </row>
4292
      </tbody>
4293
     </tgroup>
4294
    </table>
4295
4296
   <para>
4297
    An RE cannot end with a backslash (<literal>\</>).
4298
   </para>
4299
4300
   <note>
4301
    <para>
4302
     If you have <xref linkend="guc-standard-conforming-strings"> turned off,
4303
     any backslashes you write in literal string constants will need to be
4304
     doubled.  See <xref linkend="sql-syntax-strings"> for more information.
4305
    </para>
4306
   </note>
4307
4308
   <table id="posix-quantifiers-table">
4309
    <title>Regular Expression Quantifiers</title>
4310
4311
    <tgroup cols="2">
4312
     <thead>
4313
      <row>
4314
       <entry>Quantifier</entry>
4315
       <entry>Matches</entry>
4316
      </row>
4317
     </thead>
4318
4319
      <tbody>
4320
       <row>
4321
       <entry> <literal>*</> </entry>
4322
       <entry> a sequence of 0 or more matches of the atom </entry>
4323
       </row>
4324
4325
       <row>
4326
       <entry> <literal>+</> </entry>
4327
       <entry> a sequence of 1 or more matches of the atom </entry>
4328
       </row>
4329
4330
       <row>
4331
       <entry> <literal>?</> </entry>
4332
       <entry> a sequence of 0 or 1 matches of the atom </entry>
4333
       </row>
4334
4335
       <row>
4336
       <entry> <literal>{</><replaceable>m</><literal>}</> </entry>
4337
       <entry> a sequence of exactly <replaceable>m</> matches of the atom </entry>
4338
       </row>
4339
4340
       <row>
4341
       <entry> <literal>{</><replaceable>m</><literal>,}</> </entry>
4342
       <entry> a sequence of <replaceable>m</> or more matches of the atom </entry>
4343
       </row>
4344
4345
       <row>
4346
       <entry>
4347
       <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
4348
       <entry> a sequence of <replaceable>m</> through <replaceable>n</>
4349
       (inclusive) matches of the atom; <replaceable>m</> cannot exceed
4350
       <replaceable>n</> </entry>
4351
       </row>
4352
4353
       <row>
4354
       <entry> <literal>*?</> </entry>
4355
       <entry> non-greedy version of <literal>*</> </entry>
4356
       </row>
4357
4358
       <row>
4359
       <entry> <literal>+?</> </entry>
4360
       <entry> non-greedy version of <literal>+</> </entry>
4361
       </row>
4362
4363
       <row>
4364
       <entry> <literal>??</> </entry>
4365
       <entry> non-greedy version of <literal>?</> </entry>
4366
       </row>
4367
4368
       <row>
4369
       <entry> <literal>{</><replaceable>m</><literal>}?</> </entry>
4370
       <entry> non-greedy version of <literal>{</><replaceable>m</><literal>}</> </entry>
4371
       </row>
4372
4373
       <row>
4374
       <entry> <literal>{</><replaceable>m</><literal>,}?</> </entry>
4375
       <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,}</> </entry>
4376
       </row>
4377
4378
       <row>
4379
       <entry>
4380
       <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</> </entry>
4381
       <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
4382
       </row>
4383
      </tbody>
4384
     </tgroup>
4385
    </table>
4386
4387
   <para>
4388
    The forms using <literal>{</><replaceable>...</><literal>}</>
4389
    are known as <firstterm>bounds</>.
4390
    The numbers <replaceable>m</> and <replaceable>n</> within a bound are
4391
    unsigned decimal integers with permissible values from 0 to 255 inclusive.
4392
   </para>
4393
4394
    <para>
4395
     <firstterm>Non-greedy</> quantifiers (available in AREs only) match the
4396
     same possibilities as their corresponding normal (<firstterm>greedy</>)
4397
     counterparts, but prefer the smallest number rather than the largest
4398
     number of matches.
4399
     See <xref linkend="posix-matching-rules"> for more detail.
4400
   </para>
4401
4402
   <note>
4403
    <para>
4404
     A quantifier cannot immediately follow another quantifier, e.g.,
4405
     <literal>**</> is invalid.
4406
     A quantifier cannot
4407
     begin an expression or subexpression or follow
4408
     <literal>^</literal> or <literal>|</literal>.
4409
    </para>
4410
   </note>
4411
4412
   <table id="posix-constraints-table">
4413
    <title>Regular Expression Constraints</title>
4414
4415
    <tgroup cols="2">
4416
     <thead>
4417
      <row>
4418
       <entry>Constraint</entry>
4419
       <entry>Description</entry>
4420
      </row>
4421
     </thead>
4422
4423
      <tbody>
4424
       <row>
4425
       <entry> <literal>^</> </entry>
4426
       <entry> matches at the beginning of the string </entry>
4427
       </row>
4428
4429
       <row>
4430
       <entry> <literal>$</> </entry>
4431
       <entry> matches at the end of the string </entry>
4432
       </row>
4433
4434
       <row>
4435
       <entry> <literal>(?=</><replaceable>re</><literal>)</> </entry>
4436
       <entry> <firstterm>positive lookahead</> matches at any point
4437
       where a substring matching <replaceable>re</> begins
4438
       (AREs only) </entry>
4439
       </row>
4440
4441
       <row>
4442
       <entry> <literal>(?!</><replaceable>re</><literal>)</> </entry>
4443
       <entry> <firstterm>negative lookahead</> matches at any point
4444
       where no substring matching <replaceable>re</> begins
4445
       (AREs only) </entry>
4446
       </row>
4447
      </tbody>
4448
     </tgroup>
4449
    </table>
4450
4451
   <para>
4452
    Lookahead constraints cannot contain <firstterm>back references</>
4453
    (see <xref linkend="posix-escape-sequences">),
4454
    and all parentheses within them are considered non-capturing.
4455
   </para>
4456
   </sect3>
4457
4458
   <sect3 id="posix-bracket-expressions">
4459
    <title>Bracket Expressions</title>
4460
4461
   <para>
4462
    A <firstterm>bracket expression</firstterm> is a list of
4463
    characters enclosed in <literal>[]</literal>.  It normally matches
4464
    any single character from the list (but see below).  If the list
4465
    begins with <literal>^</literal>, it matches any single character
4466
    <emphasis>not</> from the rest of the list.
4467
    If two characters
4468
    in the list are separated by <literal>-</literal>, this is
4469
    shorthand for the full range of characters between those two
4470
    (inclusive) in the collating sequence,
4471
    e.g., <literal>[0-9]</literal> in <acronym>ASCII</acronym> matches
4472
    any decimal digit.  It is illegal for two ranges to share an
4473
    endpoint, e.g.,  <literal>a-c-e</literal>.  Ranges are very
4474
    collating-sequence-dependent, so portable programs should avoid
4475
    relying on them.
4476
   </para>
4477
4478
   <para>
4479
    To include a literal <literal>]</literal> in the list, make it the
4480
    first character (after <literal>^</literal>, if that is used).  To
4481
    include a literal <literal>-</literal>, make it the first or last
4482
    character, or the second endpoint of a range.  To use a literal
4483
    <literal>-</literal> as the first endpoint of a range, enclose it
4484
    in <literal>[.</literal> and <literal>.]</literal> to make it a
4485
    collating element (see below).  With the exception of these characters,
4486
    some combinations using <literal>[</literal>
4487
    (see next paragraphs), and escapes (AREs only), all other special
4488
    characters lose their special significance within a bracket expression.
4489
    In particular, <literal>\</literal> is not special when following
4490
    ERE or BRE rules, though it is special (as introducing an escape)
4491
    in AREs.
4492
   </para>
4493
4494
   <para>
4495
    Within a bracket expression, a collating element (a character, a
4496
    multiple-character sequence that collates as if it were a single
4497
    character, or a collating-sequence name for either) enclosed in
4498
    <literal>[.</literal> and <literal>.]</literal> stands for the
4499
    sequence of characters of that collating element.  The sequence is
4500
    treated as a single element of the bracket expression's list.  This
4501
    allows a bracket
4502
    expression containing a multiple-character collating element to
4503
    match more than one character, e.g., if the collating sequence
4504
    includes a <literal>ch</literal> collating element, then the RE
4505
    <literal>[[.ch.]]*c</literal> matches the first five characters of
4506
    <literal>chchcc</literal>.
4507
   </para>
4508
4509
   <note>
4510
    <para>
4511
     <productname>PostgreSQL</> currently does not support multi-character collating
4512
     elements. This information describes possible future behavior.
4513
    </para>
4514
   </note>
4515
4516
   <para>
4517
    Within a bracket expression, a collating element enclosed in
4518
    <literal>[=</literal> and <literal>=]</literal> is an <firstterm>equivalence
4519
    class</>, standing for the sequences of characters of all collating
4520
    elements equivalent to that one, including itself.  (If there are
4521
    no other equivalent collating elements, the treatment is as if the
4522
    enclosing delimiters were <literal>[.</literal> and
4523
    <literal>.]</literal>.)  For example, if <literal>o</literal> and
4524
    <literal>^</literal> are the members of an equivalence class, then
4525
    <literal>[[=o=]]</literal>, <literal>[[=^=]]</literal>, and
4526
    <literal>[o^]</literal> are all synonymous.  An equivalence class
4527
    cannot be an endpoint of a range.
4528
   </para>
4529
4530
   <para>
4531
    Within a bracket expression, the name of a character class
4532
    enclosed in <literal>[:</literal> and <literal>:]</literal> stands
4533
    for the list of all characters belonging to that class.  Standard
4534
    character class names are: <literal>alnum</literal>,
4535
    <literal>alpha</literal>, <literal>blank</literal>,
4536
    <literal>cntrl</literal>, <literal>digit</literal>,
4537
    <literal>graph</literal>, <literal>lower</literal>,
4538
    <literal>print</literal>, <literal>punct</literal>,
4539
    <literal>space</literal>, <literal>upper</literal>,
4540
    <literal>xdigit</literal>.  These stand for the character classes
4541
    defined in
4542
    <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>.
4543
    A locale can provide others.  A character class cannot be used as
4544
    an endpoint of a range.
4545
   </para>
4546
4547
   <para>
4548
    There are two special cases of bracket expressions:  the bracket
4549
    expressions <literal>[[:&lt;:]]</literal> and
4550
    <literal>[[:&gt;:]]</literal> are constraints,
4551
    matching empty strings at the beginning
4552
    and end of a word respectively.  A word is defined as a sequence
4553
    of word characters that is neither preceded nor followed by word
4554
    characters.  A word character is an <literal>alnum</> character (as
4555
    defined by
4556
    <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>)
4557
    or an underscore.  This is an extension, compatible with but not
4558
    specified by <acronym>POSIX</acronym> 1003.2, and should be used with
4559
    caution in software intended to be portable to other systems.
4560
    The constraint escapes described below are usually preferable; they
4561
    are no more standard, but are easier to type.
4562
   </para>
4563
   </sect3>
4564
4565
   <sect3 id="posix-escape-sequences">
4566
    <title>Regular Expression Escapes</title>
4567
4568
   <para>
4569
    <firstterm>Escapes</> are special sequences beginning with <literal>\</>
4570
    followed by an alphanumeric character. Escapes come in several varieties:
4571
    character entry, class shorthands, constraint escapes, and back references.
4572
    A <literal>\</> followed by an alphanumeric character but not constituting
4573
    a valid escape is illegal in AREs.
4574
    In EREs, there are no escapes: outside a bracket expression,
4575
    a <literal>\</> followed by an alphanumeric character merely stands for
4576
    that character as an ordinary character, and inside a bracket expression,
4577
    <literal>\</> is an ordinary character.
4578
    (The latter is the one actual incompatibility between EREs and AREs.)
4579
   </para>
4580
4581
   <para>
4582
    <firstterm>Character-entry escapes</> exist to make it easier to specify
4583
    non-printing and other inconvenient characters in REs.  They are
4584
    shown in <xref linkend="posix-character-entry-escapes-table">.
4585
   </para>
4586
4587
   <para>
4588
    <firstterm>Class-shorthand escapes</> provide shorthands for certain
4589
    commonly-used character classes.  They are
4590
    shown in <xref linkend="posix-class-shorthand-escapes-table">.
4591
   </para>
4592
4593
   <para>
4594
    A <firstterm>constraint escape</> is a constraint,
4595
    matching the empty string if specific conditions are met,
4596
    written as an escape.  They are
4597
    shown in <xref linkend="posix-constraint-escapes-table">.
4598
   </para>
4599
4600
   <para>
4601
    A <firstterm>back reference</> (<literal>\</><replaceable>n</>) matches the
4602
    same string matched by the previous parenthesized subexpression specified
4603
    by the number <replaceable>n</>
4604
    (see <xref linkend="posix-constraint-backref-table">).  For example,
4605
    <literal>([bc])\1</> matches <literal>bb</> or <literal>cc</>
4606
    but not <literal>bc</> or <literal>cb</>.
4607
    The subexpression must entirely precede the back reference in the RE.
4608
    Subexpressions are numbered in the order of their leading parentheses.
4609
    Non-capturing parentheses do not define subexpressions.
4610
   </para>
4611
4612
   <note>
4613
    <para>
4614
     Keep in mind that an escape's leading <literal>\</> will need to be
4615
     doubled when entering the pattern as an SQL string constant.  For example:
4616
<programlisting>
4617
'123' ~ E'^\\d{3}' <lineannotation>true</lineannotation>
4618
</programlisting>
4619
    </para>
4620
   </note>
4621
4622
   <table id="posix-character-entry-escapes-table">
4623
    <title>Regular Expression Character-entry Escapes</title>
4624
4625
    <tgroup cols="2">
4626
     <thead>
4627
      <row>
4628
       <entry>Escape</entry>
4629
       <entry>Description</entry>
4630
      </row>
4631
     </thead>
4632
4633
      <tbody>
4634
       <row>
4635
       <entry> <literal>\a</> </entry>
4636
       <entry> alert (bell) character, as in C </entry>
4637
       </row>
4638
4639
       <row>
4640
       <entry> <literal>\b</> </entry>
4641
       <entry> backspace, as in C </entry>
4642
       </row>
4643
4644
       <row>
4645
       <entry> <literal>\B</> </entry>
4646
       <entry> synonym for backslash (<literal>\</>) to help reduce the need for backslash
4647
       doubling </entry>
4648
       </row>
4649
4650
       <row>
4651
       <entry> <literal>\c</><replaceable>X</> </entry>
4652
       <entry> (where <replaceable>X</> is any character) the character whose
4653
       low-order 5 bits are the same as those of
4654
       <replaceable>X</>, and whose other bits are all zero </entry>
4655
       </row>
4656
4657
       <row>
4658
       <entry> <literal>\e</> </entry>
4659
       <entry> the character whose collating-sequence name
4660
       is <literal>ESC</>,
1.2.3 by Martin Pitt
Import upstream version 9.3.10
4661
       or failing that, the character with octal value <literal>033</> </entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
4662
       </row>
4663
4664
       <row>
4665
       <entry> <literal>\f</> </entry>
4666
       <entry> form feed, as in C </entry>
4667
       </row>
4668
4669
       <row>
4670
       <entry> <literal>\n</> </entry>
4671
       <entry> newline, as in C </entry>
4672
       </row>
4673
4674
       <row>
4675
       <entry> <literal>\r</> </entry>
4676
       <entry> carriage return, as in C </entry>
4677
       </row>
4678
4679
       <row>
4680
       <entry> <literal>\t</> </entry>
4681
       <entry> horizontal tab, as in C </entry>
4682
       </row>
4683
4684
       <row>
4685
       <entry> <literal>\u</><replaceable>wxyz</> </entry>
4686
       <entry> (where <replaceable>wxyz</> is exactly four hexadecimal digits)
1.2.3 by Martin Pitt
Import upstream version 9.3.10
4687
       the character whose hexadecimal value is
4688
       <literal>0x</><replaceable>wxyz</>
4689
       </entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
4690
       </row>
4691
4692
       <row>
4693
       <entry> <literal>\U</><replaceable>stuvwxyz</> </entry>
4694
       <entry> (where <replaceable>stuvwxyz</> is exactly eight hexadecimal
4695
       digits)
1.2.3 by Martin Pitt
Import upstream version 9.3.10
4696
       the character whose hexadecimal value is
4697
       <literal>0x</><replaceable>stuvwxyz</>
1 by Martin Pitt
Import upstream version 9.3~beta1
4698
       </entry>
4699
       </row>
4700
4701
       <row>
4702
       <entry> <literal>\v</> </entry>
4703
       <entry> vertical tab, as in C </entry>
4704
       </row>
4705
4706
       <row>
4707
       <entry> <literal>\x</><replaceable>hhh</> </entry>
4708
       <entry> (where <replaceable>hhh</> is any sequence of hexadecimal
4709
       digits)
4710
       the character whose hexadecimal value is
4711
       <literal>0x</><replaceable>hhh</>
4712
       (a single character no matter how many hexadecimal digits are used)
4713
       </entry>
4714
       </row>
4715
4716
       <row>
4717
       <entry> <literal>\0</> </entry>
4718
       <entry> the character whose value is <literal>0</> (the null byte)</entry>
4719
       </row>
4720
4721
       <row>
4722
       <entry> <literal>\</><replaceable>xy</> </entry>
4723
       <entry> (where <replaceable>xy</> is exactly two octal digits,
4724
       and is not a <firstterm>back reference</>)
4725
       the character whose octal value is
4726
       <literal>0</><replaceable>xy</> </entry>
4727
       </row>
4728
4729
       <row>
4730
       <entry> <literal>\</><replaceable>xyz</> </entry>
4731
       <entry> (where <replaceable>xyz</> is exactly three octal digits,
4732
       and is not a <firstterm>back reference</>)
4733
       the character whose octal value is
4734
       <literal>0</><replaceable>xyz</> </entry>
4735
       </row>
4736
      </tbody>
4737
     </tgroup>
4738
    </table>
4739
4740
   <para>
4741
    Hexadecimal digits are <literal>0</>-<literal>9</>,
4742
    <literal>a</>-<literal>f</>, and <literal>A</>-<literal>F</>.
4743
    Octal digits are <literal>0</>-<literal>7</>.
4744
   </para>
4745
4746
   <para>
1.2.3 by Martin Pitt
Import upstream version 9.3.10
4747
    Numeric character-entry escapes specifying values outside the ASCII range
4748
    (0-127) have meanings dependent on the database encoding.  When the
4749
    encoding is UTF-8, escape values are equivalent to Unicode code points,
4750
    for example <literal>\u1234</> means the character <literal>U+1234</>.
4751
    For other multibyte encodings, character-entry escapes usually just
4752
    specify the concatenation of the byte values for the character.  If the
4753
    escape value does not correspond to any legal character in the database
4754
    encoding, no error will be raised, but it will never match any data.
4755
   </para>
4756
4757
   <para>
1 by Martin Pitt
Import upstream version 9.3~beta1
4758
    The character-entry escapes are always taken as ordinary characters.
4759
    For example, <literal>\135</> is <literal>]</> in ASCII, but
4760
    <literal>\135</> does not terminate a bracket expression.
4761
   </para>
4762
4763
   <table id="posix-class-shorthand-escapes-table">
4764
    <title>Regular Expression Class-shorthand Escapes</title>
4765
4766
    <tgroup cols="2">
4767
     <thead>
4768
      <row>
4769
       <entry>Escape</entry>
4770
       <entry>Description</entry>
4771
      </row>
4772
     </thead>
4773
4774
      <tbody>
4775
       <row>
4776
       <entry> <literal>\d</> </entry>
4777
       <entry> <literal>[[:digit:]]</> </entry>
4778
       </row>
4779
4780
       <row>
4781
       <entry> <literal>\s</> </entry>
4782
       <entry> <literal>[[:space:]]</> </entry>
4783
       </row>
4784
4785
       <row>
4786
       <entry> <literal>\w</> </entry>
4787
       <entry> <literal>[[:alnum:]_]</>
4788
       (note underscore is included) </entry>
4789
       </row>
4790
4791
       <row>
4792
       <entry> <literal>\D</> </entry>
4793
       <entry> <literal>[^[:digit:]]</> </entry>
4794
       </row>
4795
4796
       <row>
4797
       <entry> <literal>\S</> </entry>
4798
       <entry> <literal>[^[:space:]]</> </entry>
4799
       </row>
4800
4801
       <row>
4802
       <entry> <literal>\W</> </entry>
4803
       <entry> <literal>[^[:alnum:]_]</>
4804
       (note underscore is included) </entry>
4805
       </row>
4806
      </tbody>
4807
     </tgroup>
4808
    </table>
4809
4810
   <para>
4811
    Within bracket expressions, <literal>\d</>, <literal>\s</>,
4812
    and <literal>\w</> lose their outer brackets,
4813
    and <literal>\D</>, <literal>\S</>, and <literal>\W</> are illegal.
4814
    (So, for example, <literal>[a-c\d]</> is equivalent to
4815
    <literal>[a-c[:digit:]]</>.
4816
    Also, <literal>[a-c\D]</>, which is equivalent to
4817
    <literal>[a-c^[:digit:]]</>, is illegal.)
4818
   </para>
4819
4820
   <table id="posix-constraint-escapes-table">
4821
    <title>Regular Expression Constraint Escapes</title>
4822
4823
    <tgroup cols="2">
4824
     <thead>
4825
      <row>
4826
       <entry>Escape</entry>
4827
       <entry>Description</entry>
4828
      </row>
4829
     </thead>
4830
4831
      <tbody>
4832
       <row>
4833
       <entry> <literal>\A</> </entry>
4834
       <entry> matches only at the beginning of the string
4835
       (see <xref linkend="posix-matching-rules"> for how this differs from
4836
       <literal>^</>) </entry>
4837
       </row>
4838
4839
       <row>
4840
       <entry> <literal>\m</> </entry>
4841
       <entry> matches only at the beginning of a word </entry>
4842
       </row>
4843
4844
       <row>
4845
       <entry> <literal>\M</> </entry>
4846
       <entry> matches only at the end of a word </entry>
4847
       </row>
4848
4849
       <row>
4850
       <entry> <literal>\y</> </entry>
4851
       <entry> matches only at the beginning or end of a word </entry>
4852
       </row>
4853
4854
       <row>
4855
       <entry> <literal>\Y</> </entry>
4856
       <entry> matches only at a point that is not the beginning or end of a
4857
       word </entry>
4858
       </row>
4859
4860
       <row>
4861
       <entry> <literal>\Z</> </entry>
4862
       <entry> matches only at the end of the string
4863
       (see <xref linkend="posix-matching-rules"> for how this differs from
4864
       <literal>$</>) </entry>
4865
       </row>
4866
      </tbody>
4867
     </tgroup>
4868
    </table>
4869
4870
   <para>
4871
    A word is defined as in the specification of
4872
    <literal>[[:&lt;:]]</> and <literal>[[:&gt;:]]</> above.
4873
    Constraint escapes are illegal within bracket expressions.
4874
   </para>
4875
4876
   <table id="posix-constraint-backref-table">
4877
    <title>Regular Expression Back References</title>
4878
4879
    <tgroup cols="2">
4880
     <thead>
4881
      <row>
4882
       <entry>Escape</entry>
4883
       <entry>Description</entry>
4884
      </row>
4885
     </thead>
4886
4887
      <tbody>
4888
       <row>
4889
       <entry> <literal>\</><replaceable>m</> </entry>
4890
       <entry> (where <replaceable>m</> is a nonzero digit)
4891
       a back reference to the <replaceable>m</>'th subexpression </entry>
4892
       </row>
4893
4894
       <row>
4895
       <entry> <literal>\</><replaceable>mnn</> </entry>
4896
       <entry> (where <replaceable>m</> is a nonzero digit, and
4897
       <replaceable>nn</> is some more digits, and the decimal value
4898
       <replaceable>mnn</> is not greater than the number of closing capturing
4899
       parentheses seen so far)
4900
       a back reference to the <replaceable>mnn</>'th subexpression </entry>
4901
       </row>
4902
      </tbody>
4903
     </tgroup>
4904
    </table>
4905
4906
   <note>
4907
    <para>
4908
     There is an inherent ambiguity between octal character-entry
4909
     escapes and back references, which is resolved by the following heuristics,
4910
     as hinted at above.
4911
     A leading zero always indicates an octal escape.
4912
     A single non-zero digit, not followed by another digit,
4913
     is always taken as a back reference.
4914
     A multi-digit sequence not starting with a zero is taken as a back
4915
     reference if it comes after a suitable subexpression
4916
     (i.e., the number is in the legal range for a back reference),
4917
     and otherwise is taken as octal.
4918
    </para>
4919
   </note>
4920
   </sect3>
4921
4922
   <sect3 id="posix-metasyntax">
4923
    <title>Regular Expression Metasyntax</title>
4924
4925
   <para>
4926
    In addition to the main syntax described above, there are some special
4927
    forms and miscellaneous syntactic facilities available.
4928
   </para>
4929
4930
   <para>
4931
    An RE can begin with one of two special <firstterm>director</> prefixes.
4932
    If an RE begins with <literal>***:</>,
4933
    the rest of the RE is taken as an ARE.  (This normally has no effect in
4934
    <productname>PostgreSQL</>, since REs are assumed to be AREs;
4935
    but it does have an effect if ERE or BRE mode had been specified by
4936
    the <replaceable>flags</> parameter to a regex function.)
4937
    If an RE begins with <literal>***=</>,
4938
    the rest of the RE is taken to be a literal string,
4939
    with all characters considered ordinary characters.
4940
   </para>
4941
4942
   <para>
4943
    An ARE can begin with <firstterm>embedded options</>:
4944
    a sequence <literal>(?</><replaceable>xyz</><literal>)</>
4945
    (where <replaceable>xyz</> is one or more alphabetic characters)
4946
    specifies options affecting the rest of the RE.
4947
    These options override any previously determined options &mdash;
4948
    in particular, they can override the case-sensitivity behavior implied by
4949
    a regex operator, or the <replaceable>flags</> parameter to a regex
4950
    function.
4951
    The available option letters are
4952
    shown in <xref linkend="posix-embedded-options-table">.
4953
    Note that these same option letters are used in the <replaceable>flags</>
4954
    parameters of regex functions.
4955
   </para>
4956
4957
   <table id="posix-embedded-options-table">
4958
    <title>ARE Embedded-option Letters</title>
4959
4960
    <tgroup cols="2">
4961
     <thead>
4962
      <row>
4963
       <entry>Option</entry>
4964
       <entry>Description</entry>
4965
      </row>
4966
     </thead>
4967
4968
      <tbody>
4969
       <row>
4970
       <entry> <literal>b</> </entry>
4971
       <entry> rest of RE is a BRE </entry>
4972
       </row>
4973
4974
       <row>
4975
       <entry> <literal>c</> </entry>
4976
       <entry> case-sensitive matching (overrides operator type) </entry>
4977
       </row>
4978
4979
       <row>
4980
       <entry> <literal>e</> </entry>
4981
       <entry> rest of RE is an ERE </entry>
4982
       </row>
4983
4984
       <row>
4985
       <entry> <literal>i</> </entry>
4986
       <entry> case-insensitive matching (see
4987
       <xref linkend="posix-matching-rules">) (overrides operator type) </entry>
4988
       </row>
4989
4990
       <row>
4991
       <entry> <literal>m</> </entry>
4992
       <entry> historical synonym for <literal>n</> </entry>
4993
       </row>
4994
4995
       <row>
4996
       <entry> <literal>n</> </entry>
4997
       <entry> newline-sensitive matching (see
4998
       <xref linkend="posix-matching-rules">) </entry>
4999
       </row>
5000
5001
       <row>
5002
       <entry> <literal>p</> </entry>
5003
       <entry> partial newline-sensitive matching (see
5004
       <xref linkend="posix-matching-rules">) </entry>
5005
       </row>
5006
5007
       <row>
5008
       <entry> <literal>q</> </entry>
5009
       <entry> rest of RE is a literal (<quote>quoted</>) string, all ordinary
5010
       characters </entry>
5011
       </row>
5012
5013
       <row>
5014
       <entry> <literal>s</> </entry>
5015
       <entry> non-newline-sensitive matching (default) </entry>
5016
       </row>
5017
5018
       <row>
5019
       <entry> <literal>t</> </entry>
5020
       <entry> tight syntax (default; see below) </entry>
5021
       </row>
5022
5023
       <row>
5024
       <entry> <literal>w</> </entry>
5025
       <entry> inverse partial newline-sensitive (<quote>weird</>) matching
5026
       (see <xref linkend="posix-matching-rules">) </entry>
5027
       </row>
5028
5029
       <row>
5030
       <entry> <literal>x</> </entry>
5031
       <entry> expanded syntax (see below) </entry>
5032
       </row>
5033
      </tbody>
5034
     </tgroup>
5035
    </table>
5036
5037
   <para>
5038
    Embedded options take effect at the <literal>)</> terminating the sequence.
5039
    They can appear only at the start of an ARE (after the
5040
    <literal>***:</> director if any).
5041
   </para>
5042
5043
   <para>
5044
    In addition to the usual (<firstterm>tight</>) RE syntax, in which all
5045
    characters are significant, there is an <firstterm>expanded</> syntax,
5046
    available by specifying the embedded <literal>x</> option.
5047
    In the expanded syntax,
5048
    white-space characters in the RE are ignored, as are
5049
    all characters between a <literal>#</>
5050
    and the following newline (or the end of the RE).  This
5051
    permits paragraphing and commenting a complex RE.
5052
    There are three exceptions to that basic rule:
5053
5054
    <itemizedlist>
5055
     <listitem>
5056
      <para>
5057
       a white-space character or <literal>#</> preceded by <literal>\</> is
5058
       retained
5059
      </para>
5060
     </listitem>
5061
     <listitem>
5062
      <para>
5063
       white space or <literal>#</> within a bracket expression is retained
5064
      </para>
5065
     </listitem>
5066
     <listitem>
5067
      <para>
5068
       white space and comments cannot appear within multi-character symbols,
5069
       such as <literal>(?:</>
5070
      </para>
5071
     </listitem>
5072
    </itemizedlist>
5073
5074
    For this purpose, white-space characters are blank, tab, newline, and
5075
    any character that belongs to the <replaceable>space</> character class.
5076
   </para>
5077
5078
   <para>
5079
    Finally, in an ARE, outside bracket expressions, the sequence
5080
    <literal>(?#</><replaceable>ttt</><literal>)</>
5081
    (where <replaceable>ttt</> is any text not containing a <literal>)</>)
5082
    is a comment, completely ignored.
5083
    Again, this is not allowed between the characters of
5084
    multi-character symbols, like <literal>(?:</>.
5085
    Such comments are more a historical artifact than a useful facility,
5086
    and their use is deprecated; use the expanded syntax instead.
5087
   </para>
5088
5089
   <para>
5090
    <emphasis>None</> of these metasyntax extensions is available if
5091
    an initial <literal>***=</> director
5092
    has specified that the user's input be treated as a literal string
5093
    rather than as an RE.
5094
   </para>
5095
   </sect3>
5096
5097
   <sect3 id="posix-matching-rules">
5098
    <title>Regular Expression Matching Rules</title>
5099
5100
   <para>
5101
    In the event that an RE could match more than one substring of a given
5102
    string, the RE matches the one starting earliest in the string.
5103
    If the RE could match more than one substring starting at that point,
5104
    either the longest possible match or the shortest possible match will
5105
    be taken, depending on whether the RE is <firstterm>greedy</> or
5106
    <firstterm>non-greedy</>.
5107
   </para>
5108
5109
   <para>
5110
    Whether an RE is greedy or not is determined by the following rules:
5111
    <itemizedlist>
5112
     <listitem>
5113
      <para>
5114
       Most atoms, and all constraints, have no greediness attribute (because
5115
       they cannot match variable amounts of text anyway).
5116
      </para>
5117
     </listitem>
5118
     <listitem>
5119
      <para>
5120
       Adding parentheses around an RE does not change its greediness.
5121
      </para>
5122
     </listitem>
5123
     <listitem>
5124
      <para>
5125
       A quantified atom with a fixed-repetition quantifier
5126
       (<literal>{</><replaceable>m</><literal>}</>
5127
       or
5128
       <literal>{</><replaceable>m</><literal>}?</>)
5129
       has the same greediness (possibly none) as the atom itself.
5130
      </para>
5131
     </listitem>
5132
     <listitem>
5133
      <para>
5134
       A quantified atom with other normal quantifiers (including
5135
       <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</>
5136
       with <replaceable>m</> equal to <replaceable>n</>)
5137
       is greedy (prefers longest match).
5138
      </para>
5139
     </listitem>
5140
     <listitem>
5141
      <para>
5142
       A quantified atom with a non-greedy quantifier (including
5143
       <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</>
5144
       with <replaceable>m</> equal to <replaceable>n</>)
5145
       is non-greedy (prefers shortest match).
5146
      </para>
5147
     </listitem>
5148
     <listitem>
5149
      <para>
5150
       A branch &mdash; that is, an RE that has no top-level
5151
       <literal>|</> operator &mdash; has the same greediness as the first
5152
       quantified atom in it that has a greediness attribute.
5153
      </para>
5154
     </listitem>
5155
     <listitem>
5156
      <para>
5157
       An RE consisting of two or more branches connected by the
5158
       <literal>|</> operator is always greedy.
5159
      </para>
5160
     </listitem>
5161
    </itemizedlist>
5162
   </para>
5163
5164
   <para>
5165
    The above rules associate greediness attributes not only with individual
5166
    quantified atoms, but with branches and entire REs that contain quantified
5167
    atoms.  What that means is that the matching is done in such a way that
5168
    the branch, or whole RE, matches the longest or shortest possible
5169
    substring <emphasis>as a whole</>.  Once the length of the entire match
5170
    is determined, the part of it that matches any particular subexpression
5171
    is determined on the basis of the greediness attribute of that
5172
    subexpression, with subexpressions starting earlier in the RE taking
5173
    priority over ones starting later.
5174
   </para>
5175
5176
   <para>
5177
    An example of what this means:
5178
<screen>
5179
SELECT SUBSTRING('XY1234Z', 'Y*([0-9]{1,3})');
5180
<lineannotation>Result: </lineannotation><computeroutput>123</computeroutput>
5181
SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{1,3})');
5182
<lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
5183
</screen>
5184
    In the first case, the RE as a whole is greedy because <literal>Y*</>
5185
    is greedy.  It can match beginning at the <literal>Y</>, and it matches
5186
    the longest possible string starting there, i.e., <literal>Y123</>.
5187
    The output is the parenthesized part of that, or <literal>123</>.
5188
    In the second case, the RE as a whole is non-greedy because <literal>Y*?</>
5189
    is non-greedy.  It can match beginning at the <literal>Y</>, and it matches
5190
    the shortest possible string starting there, i.e., <literal>Y1</>.
5191
    The subexpression <literal>[0-9]{1,3}</> is greedy but it cannot change
5192
    the decision as to the overall match length; so it is forced to match
5193
    just <literal>1</>.
5194
   </para>
5195
5196
   <para>
5197
    In short, when an RE contains both greedy and non-greedy subexpressions,
5198
    the total match length is either as long as possible or as short as
5199
    possible, according to the attribute assigned to the whole RE.  The
5200
    attributes assigned to the subexpressions only affect how much of that
5201
    match they are allowed to <quote>eat</> relative to each other.
5202
   </para>
5203
5204
   <para>
5205
    The quantifiers <literal>{1,1}</> and <literal>{1,1}?</>
5206
    can be used to force greediness or non-greediness, respectively,
5207
    on a subexpression or a whole RE.
1.2.3 by Martin Pitt
Import upstream version 9.3.10
5208
    This is useful when you need the whole RE to have a greediness attribute
5209
    different from what's deduced from its elements.  As an example,
5210
    suppose that we are trying to separate a string containing some digits
5211
    into the digits and the parts before and after them.  We might try to
5212
    do that like this:
5213
<screen>
5214
SELECT regexp_matches('abc01234xyz', '(.*)(\d+)(.*)');
5215
<lineannotation>Result: </lineannotation><computeroutput>{abc0123,4,xyz}</computeroutput>
5216
</screen>
5217
    That didn't work: the first <literal>.*</> is greedy so
5218
    it <quote>eats</> as much as it can, leaving the <literal>\d+</> to
5219
    match at the last possible place, the last digit.  We might try to fix
5220
    that by making it non-greedy:
5221
<screen>
5222
SELECT regexp_matches('abc01234xyz', '(.*?)(\d+)(.*)');
5223
<lineannotation>Result: </lineannotation><computeroutput>{abc,0,""}</computeroutput>
5224
</screen>
5225
    That didn't work either, because now the RE as a whole is non-greedy
5226
    and so it ends the overall match as soon as possible.  We can get what
5227
    we want by forcing the RE as a whole to be greedy:
5228
<screen>
5229
SELECT regexp_matches('abc01234xyz', '(?:(.*?)(\d+)(.*)){1,1}');
5230
<lineannotation>Result: </lineannotation><computeroutput>{abc,01234,xyz}</computeroutput>
5231
</screen>
5232
    Controlling the RE's overall greediness separately from its components'
5233
    greediness allows great flexibility in handling variable-length patterns.
1 by Martin Pitt
Import upstream version 9.3~beta1
5234
   </para>
5235
5236
   <para>
1.2.3 by Martin Pitt
Import upstream version 9.3.10
5237
    When deciding what is a longer or shorter match,
5238
    match lengths are measured in characters, not collating elements.
1 by Martin Pitt
Import upstream version 9.3~beta1
5239
    An empty string is considered longer than no match at all.
5240
    For example:
5241
    <literal>bb*</>
5242
    matches the three middle characters of <literal>abbbc</>;
5243
    <literal>(week|wee)(night|knights)</>
5244
    matches all ten characters of <literal>weeknights</>;
5245
    when <literal>(.*).*</>
5246
    is matched against <literal>abc</> the parenthesized subexpression
5247
    matches all three characters; and when
5248
    <literal>(a*)*</> is matched against <literal>bc</>
5249
    both the whole RE and the parenthesized
5250
    subexpression match an empty string.
5251
   </para>
5252
5253
   <para>
5254
    If case-independent matching is specified,
5255
    the effect is much as if all case distinctions had vanished from the
5256
    alphabet.
5257
    When an alphabetic that exists in multiple cases appears as an
5258
    ordinary character outside a bracket expression, it is effectively
5259
    transformed into a bracket expression containing both cases,
5260
    e.g., <literal>x</> becomes <literal>[xX]</>.
5261
    When it appears inside a bracket expression, all case counterparts
5262
    of it are added to the bracket expression, e.g.,
5263
    <literal>[x]</> becomes <literal>[xX]</>
5264
    and <literal>[^x]</> becomes <literal>[^xX]</>.
5265
   </para>
5266
5267
   <para>
5268
    If newline-sensitive matching is specified, <literal>.</>
5269
    and bracket expressions using <literal>^</>
5270
    will never match the newline character
5271
    (so that matches will never cross newlines unless the RE
5272
    explicitly arranges it)
5273
    and <literal>^</> and <literal>$</>
5274
    will match the empty string after and before a newline
5275
    respectively, in addition to matching at beginning and end of string
5276
    respectively.
5277
    But the ARE escapes <literal>\A</> and <literal>\Z</>
5278
    continue to match beginning or end of string <emphasis>only</>.
5279
   </para>
5280
5281
   <para>
5282
    If partial newline-sensitive matching is specified,
5283
    this affects <literal>.</> and bracket expressions
5284
    as with newline-sensitive matching, but not <literal>^</>
5285
    and <literal>$</>.
5286
   </para>
5287
5288
   <para>
5289
    If inverse partial newline-sensitive matching is specified,
5290
    this affects <literal>^</> and <literal>$</>
5291
    as with newline-sensitive matching, but not <literal>.</>
5292
    and bracket expressions.
5293
    This isn't very useful but is provided for symmetry.
5294
   </para>
5295
   </sect3>
5296
5297
   <sect3 id="posix-limits-compatibility">
5298
    <title>Limits and Compatibility</title>
5299
5300
   <para>
5301
    No particular limit is imposed on the length of REs in this
5302
    implementation.  However,
5303
    programs intended to be highly portable should not employ REs longer
5304
    than 256 bytes,
5305
    as a POSIX-compliant implementation can refuse to accept such REs.
5306
   </para>
5307
5308
   <para>
5309
    The only feature of AREs that is actually incompatible with
5310
    POSIX EREs is that <literal>\</> does not lose its special
5311
    significance inside bracket expressions.
5312
    All other ARE features use syntax which is illegal or has
5313
    undefined or unspecified effects in POSIX EREs;
5314
    the <literal>***</> syntax of directors likewise is outside the POSIX
5315
    syntax for both BREs and EREs.
5316
   </para>
5317
5318
   <para>
5319
    Many of the ARE extensions are borrowed from Perl, but some have
5320
    been changed to clean them up, and a few Perl extensions are not present.
5321
    Incompatibilities of note include <literal>\b</>, <literal>\B</>,
5322
    the lack of special treatment for a trailing newline,
5323
    the addition of complemented bracket expressions to the things
5324
    affected by newline-sensitive matching,
5325
    the restrictions on parentheses and back references in lookahead
5326
    constraints, and the longest/shortest-match (rather than first-match)
5327
    matching semantics.
5328
   </para>
5329
5330
   <para>
5331
    Two significant incompatibilities exist between AREs and the ERE syntax
5332
    recognized by pre-7.4 releases of <productname>PostgreSQL</>:
5333
5334
    <itemizedlist>
5335
     <listitem>
5336
      <para>
5337
       In AREs, <literal>\</> followed by an alphanumeric character is either
5338
       an escape or an error, while in previous releases, it was just another
5339
       way of writing the alphanumeric.
5340
       This should not be much of a problem because there was no reason to
5341
       write such a sequence in earlier releases.
5342
      </para>
5343
     </listitem>
5344
     <listitem>
5345
      <para>
5346
       In AREs, <literal>\</> remains a special character within
5347
       <literal>[]</>, so a literal <literal>\</> within a bracket
5348
       expression must be written <literal>\\</>.
5349
      </para>
5350
     </listitem>
5351
    </itemizedlist>
5352
   </para>
5353
   </sect3>
5354
5355
   <sect3 id="posix-basic-regexes">
5356
    <title>Basic Regular Expressions</title>
5357
5358
   <para>
5359
    BREs differ from EREs in several respects.
5360
    In BREs, <literal>|</>, <literal>+</>, and <literal>?</>
5361
    are ordinary characters and there is no equivalent
5362
    for their functionality.
5363
    The delimiters for bounds are
5364
    <literal>\{</> and <literal>\}</>,
5365
    with <literal>{</> and <literal>}</>
5366
    by themselves ordinary characters.
5367
    The parentheses for nested subexpressions are
5368
    <literal>\(</> and <literal>\)</>,
5369
    with <literal>(</> and <literal>)</> by themselves ordinary characters.
5370
    <literal>^</> is an ordinary character except at the beginning of the
5371
    RE or the beginning of a parenthesized subexpression,
5372
    <literal>$</> is an ordinary character except at the end of the
5373
    RE or the end of a parenthesized subexpression,
5374
    and <literal>*</> is an ordinary character if it appears at the beginning
5375
    of the RE or the beginning of a parenthesized subexpression
5376
    (after a possible leading <literal>^</>).
5377
    Finally, single-digit back references are available, and
5378
    <literal>\&lt;</> and <literal>\&gt;</>
5379
    are synonyms for
5380
    <literal>[[:&lt;:]]</> and <literal>[[:&gt;:]]</>
5381
    respectively; no other escapes are available in BREs.
5382
   </para>
5383
   </sect3>
5384
5385
<!-- end re_syntax.n man page -->
5386
5387
  </sect2>
5388
 </sect1>
5389
5390
5391
  <sect1 id="functions-formatting">
5392
   <title>Data Type Formatting Functions</title>
5393
5394
   <indexterm>
5395
    <primary>formatting</primary>
5396
   </indexterm>
5397
5398
   <para>
5399
    The <productname>PostgreSQL</productname> formatting functions
5400
    provide a powerful set of tools for converting various data types
5401
    (date/time, integer, floating point, numeric) to formatted strings
5402
    and for converting from formatted strings to specific data types.
5403
    <xref linkend="functions-formatting-table"> lists them.
5404
    These functions all follow a common calling convention: the first
5405
    argument is the value to be formatted and the second argument is a
5406
    template that defines the output or input format.
5407
   </para>
5408
   <para>
5409
    A single-argument <function>to_timestamp</function> function is also
5410
    available;  it accepts a
5411
    <type>double precision</type> argument and converts from Unix epoch
5412
    (seconds since 1970-01-01 00:00:00+00) to
5413
    <type>timestamp with time zone</type>.
5414
    (<type>Integer</type> Unix epochs are implicitly cast to
5415
    <type>double precision</type>.)
5416
   </para>
5417
5418
    <table id="functions-formatting-table">
5419
     <title>Formatting Functions</title>
5420
     <tgroup cols="4">
5421
      <thead>
5422
       <row>
5423
        <entry>Function</entry>
5424
        <entry>Return Type</entry>
5425
        <entry>Description</entry>
5426
        <entry>Example</entry>
5427
       </row>
5428
      </thead>
5429
      <tbody>
5430
       <row>
5431
        <entry>
5432
         <indexterm>
5433
          <primary>to_char</primary>
5434
         </indexterm>
5435
         <literal><function>to_char(<type>timestamp</type>, <type>text</type>)</function></literal>
5436
        </entry>
5437
        <entry><type>text</type></entry>
5438
        <entry>convert time stamp to string</entry>
5439
        <entry><literal>to_char(current_timestamp, 'HH12:MI:SS')</literal></entry>
5440
       </row>
5441
       <row>
5442
        <entry><literal><function>to_char(<type>interval</type>, <type>text</type>)</function></literal></entry>
5443
        <entry><type>text</type></entry>
5444
        <entry>convert interval to string</entry>
5445
        <entry><literal>to_char(interval '15h&nbsp;2m&nbsp;12s', 'HH24:MI:SS')</literal></entry>
5446
       </row>
5447
       <row>
5448
        <entry><literal><function>to_char(<type>int</type>, <type>text</type>)</function></literal></entry>
5449
        <entry><type>text</type></entry>
5450
        <entry>convert integer to string</entry>
5451
        <entry><literal>to_char(125, '999')</literal></entry>
5452
       </row>
5453
       <row>
5454
        <entry><literal><function>to_char</function>(<type>double precision</type>,
5455
        <type>text</type>)</literal></entry>
5456
        <entry><type>text</type></entry>
5457
        <entry>convert real/double precision to string</entry>
5458
        <entry><literal>to_char(125.8::real, '999D9')</literal></entry>
5459
       </row>
5460
       <row>
5461
        <entry><literal><function>to_char(<type>numeric</type>, <type>text</type>)</function></literal></entry>
5462
        <entry><type>text</type></entry>
5463
        <entry>convert numeric to string</entry>
5464
        <entry><literal>to_char(-125.8, '999D99S')</literal></entry>
5465
       </row>
5466
       <row>
5467
        <entry>
5468
         <indexterm>
5469
          <primary>to_date</primary>
5470
         </indexterm>
5471
         <literal><function>to_date(<type>text</type>, <type>text</type>)</function></literal>
5472
        </entry>
5473
        <entry><type>date</type></entry>
5474
        <entry>convert string to date</entry>
5475
        <entry><literal>to_date('05&nbsp;Dec&nbsp;2000', 'DD&nbsp;Mon&nbsp;YYYY')</literal></entry>
5476
       </row>
5477
       <row>
5478
        <entry>
5479
         <indexterm>
5480
          <primary>to_number</primary>
5481
         </indexterm>
5482
         <literal><function>to_number(<type>text</type>, <type>text</type>)</function></literal>
5483
        </entry>
5484
        <entry><type>numeric</type></entry>
5485
        <entry>convert string to numeric</entry>
5486
        <entry><literal>to_number('12,454.8-', '99G999D9S')</literal></entry>
5487
       </row>
5488
       <row>
5489
        <entry>
5490
         <indexterm>
5491
          <primary>to_timestamp</primary>
5492
         </indexterm>
5493
         <literal><function>to_timestamp(<type>text</type>, <type>text</type>)</function></literal>
5494
        </entry>
5495
        <entry><type>timestamp with time zone</type></entry>
5496
        <entry>convert string to time stamp</entry>
5497
        <entry><literal>to_timestamp('05&nbsp;Dec&nbsp;2000', 'DD&nbsp;Mon&nbsp;YYYY')</literal></entry>
5498
       </row>
5499
       <row>
5500
        <entry><literal><function>to_timestamp(<type>double precision</type>)</function></literal></entry>
5501
        <entry><type>timestamp with time zone</type></entry>
5502
        <entry>convert Unix epoch to time stamp</entry>
5503
        <entry><literal>to_timestamp(1284352323)</literal></entry>
5504
       </row>
5505
      </tbody>
5506
     </tgroup>
5507
    </table>
5508
5509
   <para>
5510
    In a <function>to_char</> output template string, there are certain
5511
    patterns that are recognized and replaced with appropriately-formatted
5512
    data based on the given value.  Any text that is not a template pattern is
5513
    simply copied verbatim.  Similarly, in an input template string (for the
5514
    other functions), template patterns identify the values to be supplied by
5515
    the input data string.
5516
   </para>
5517
5518
  <para>
5519
   <xref linkend="functions-formatting-datetime-table"> shows the
5520
   template patterns available for formatting date and time values.
5521
  </para>
5522
5523
    <table id="functions-formatting-datetime-table">
5524
     <title>Template Patterns for Date/Time Formatting</title>
5525
     <tgroup cols="2">
5526
      <thead>
5527
       <row>
5528
        <entry>Pattern</entry>
5529
        <entry>Description</entry>
5530
       </row>
5531
      </thead>
5532
      <tbody>
5533
       <row>
5534
        <entry><literal>HH</literal></entry>
5535
        <entry>hour of day (01-12)</entry>
5536
       </row>
5537
       <row>
5538
        <entry><literal>HH12</literal></entry>
5539
        <entry>hour of day (01-12)</entry>
5540
       </row>
5541
       <row>
5542
        <entry><literal>HH24</literal></entry>
5543
        <entry>hour of day (00-23)</entry>
5544
       </row>
5545
       <row>
5546
        <entry><literal>MI</literal></entry>
5547
        <entry>minute (00-59)</entry>
5548
       </row>
5549
       <row>
5550
        <entry><literal>SS</literal></entry>
5551
        <entry>second (00-59)</entry>
5552
       </row>
5553
       <row>
5554
        <entry><literal>MS</literal></entry>
5555
        <entry>millisecond (000-999)</entry>
5556
       </row>
5557
       <row>
5558
        <entry><literal>US</literal></entry>
5559
        <entry>microsecond (000000-999999)</entry>
5560
       </row>
5561
       <row>
5562
        <entry><literal>SSSS</literal></entry>
5563
        <entry>seconds past midnight (0-86399)</entry>
5564
       </row>
5565
       <row>
5566
        <entry><literal>AM</literal>, <literal>am</literal>,
5567
        <literal>PM</literal> or <literal>pm</literal></entry>
5568
        <entry>meridiem indicator (without periods)</entry>
5569
       </row>
5570
       <row>
5571
        <entry><literal>A.M.</literal>, <literal>a.m.</literal>,
5572
        <literal>P.M.</literal> or <literal>p.m.</literal></entry>
5573
        <entry>meridiem indicator (with periods)</entry>
5574
       </row>
5575
       <row>
5576
        <entry><literal>Y,YYY</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5577
        <entry>year (4 or more digits) with comma</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5578
       </row>
5579
       <row>
5580
        <entry><literal>YYYY</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5581
        <entry>year (4 or more digits)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5582
       </row>
5583
       <row>
5584
        <entry><literal>YYY</literal></entry>
5585
        <entry>last 3 digits of year</entry>
5586
       </row>
5587
       <row>
5588
        <entry><literal>YY</literal></entry>
5589
        <entry>last 2 digits of year</entry>
5590
       </row>
5591
       <row>
5592
        <entry><literal>Y</literal></entry>
5593
        <entry>last digit of year</entry>
5594
       </row>
5595
       <row>
5596
        <entry><literal>IYYY</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5597
        <entry>ISO 8601 week-numbering year (4 or more digits)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5598
       </row>
5599
       <row>
5600
        <entry><literal>IYY</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5601
        <entry>last 3 digits of ISO 8601 week-numbering year</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5602
       </row>
5603
       <row>
5604
        <entry><literal>IY</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5605
        <entry>last 2 digits of ISO 8601 week-numbering year</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5606
       </row>
5607
       <row>
5608
        <entry><literal>I</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5609
        <entry>last digit of ISO 8601 week-numbering year</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5610
       </row>
5611
       <row>
5612
        <entry><literal>BC</literal>, <literal>bc</literal>,
5613
        <literal>AD</literal> or <literal>ad</literal></entry>
5614
        <entry>era indicator (without periods)</entry>
5615
       </row>
5616
       <row>
5617
        <entry><literal>B.C.</literal>, <literal>b.c.</literal>,
5618
        <literal>A.D.</literal> or <literal>a.d.</literal></entry>
5619
        <entry>era indicator (with periods)</entry>
5620
       </row>
5621
       <row>
5622
        <entry><literal>MONTH</literal></entry>
5623
        <entry>full upper case month name (blank-padded to 9 chars)</entry>
5624
       </row>
5625
       <row>
5626
        <entry><literal>Month</literal></entry>
5627
        <entry>full capitalized month name (blank-padded to 9 chars)</entry>
5628
       </row>
5629
       <row>
5630
        <entry><literal>month</literal></entry>
5631
        <entry>full lower case month name (blank-padded to 9 chars)</entry>
5632
       </row>
5633
       <row>
5634
        <entry><literal>MON</literal></entry>
5635
        <entry>abbreviated upper case month name (3 chars in English, localized lengths vary)</entry>
5636
       </row>
5637
       <row>
5638
        <entry><literal>Mon</literal></entry>
5639
        <entry>abbreviated capitalized month name (3 chars in English, localized lengths vary)</entry>
5640
       </row>
5641
       <row>
5642
        <entry><literal>mon</literal></entry>
5643
        <entry>abbreviated lower case month name (3 chars in English, localized lengths vary)</entry>
5644
       </row>
5645
       <row>
5646
        <entry><literal>MM</literal></entry>
5647
        <entry>month number (01-12)</entry>
5648
       </row>
5649
       <row>
5650
        <entry><literal>DAY</literal></entry>
5651
        <entry>full upper case day name (blank-padded to 9 chars)</entry>
5652
       </row>
5653
       <row>
5654
        <entry><literal>Day</literal></entry>
5655
        <entry>full capitalized day name (blank-padded to 9 chars)</entry>
5656
       </row>
5657
       <row>
5658
        <entry><literal>day</literal></entry>
5659
        <entry>full lower case day name (blank-padded to 9 chars)</entry>
5660
       </row>
5661
       <row>
5662
        <entry><literal>DY</literal></entry>
5663
        <entry>abbreviated upper case day name (3 chars in English, localized lengths vary)</entry>
5664
       </row>
5665
       <row>
5666
        <entry><literal>Dy</literal></entry>
5667
        <entry>abbreviated capitalized day name (3 chars in English, localized lengths vary)</entry>
5668
       </row>
5669
       <row>
5670
        <entry><literal>dy</literal></entry>
5671
        <entry>abbreviated lower case day name (3 chars in English, localized lengths vary)</entry>
5672
       </row>
5673
       <row>
5674
        <entry><literal>DDD</literal></entry>
5675
        <entry>day of year (001-366)</entry>
5676
       </row>
5677
       <row>
5678
        <entry><literal>IDDD</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5679
        <entry>day of ISO 8601 week-numbering year (001-371; day 1 of the year is Monday of the first ISO week)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5680
       </row>
5681
       <row>
5682
        <entry><literal>DD</literal></entry>
5683
        <entry>day of month (01-31)</entry>
5684
       </row>
5685
       <row>
5686
        <entry><literal>D</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5687
        <entry>day of the week, Sunday (<literal>1</>) to Saturday (<literal>7</>)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5688
       </row>
5689
       <row>
5690
        <entry><literal>ID</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5691
        <entry>ISO 8601 day of the week, Monday (<literal>1</>) to Sunday (<literal>7</>)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5692
       </row>
5693
       <row>
5694
        <entry><literal>W</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5695
        <entry>week of month (1-5) (the first week starts on the first day of the month)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5696
       </row>
5697
       <row>
5698
        <entry><literal>WW</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5699
        <entry>week number of year (1-53) (the first week starts on the first day of the year)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5700
       </row>
5701
       <row>
5702
        <entry><literal>IW</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5703
        <entry>week number of ISO 8601 week-numbering year (01-53; the first Thursday of the year is in week 1)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5704
       </row>
5705
       <row>
5706
        <entry><literal>CC</literal></entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5707
        <entry>century (2 digits) (the twenty-first century starts on 2001-01-01)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5708
       </row>
5709
       <row>
5710
        <entry><literal>J</literal></entry>
1.1.2 by Martin Pitt
Import upstream version 9.3~rc1
5711
        <entry>Julian Day (integer days since November 24, 4714 BC at midnight UTC)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5712
       </row>
5713
       <row>
5714
        <entry><literal>Q</literal></entry>
5715
        <entry>quarter (ignored by <function>to_date</> and <function>to_timestamp</>)</entry>
5716
       </row>
5717
       <row>
5718
        <entry><literal>RM</literal></entry>
5719
        <entry>month in upper case Roman numerals (I-XII; I=January)</entry>
5720
       </row>
5721
       <row>
5722
        <entry><literal>rm</literal></entry>
5723
        <entry>month in lower case Roman numerals (i-xii; i=January)</entry>
5724
       </row>
5725
       <row>
5726
        <entry><literal>TZ</literal></entry>
5727
        <entry>upper case time-zone name</entry>
5728
       </row>
5729
       <row>
5730
        <entry><literal>tz</literal></entry>
5731
        <entry>lower case time-zone name</entry>
5732
       </row>
5733
      </tbody>
5734
     </tgroup>
5735
    </table>
5736
5737
   <para>
5738
    Modifiers can be applied to any template pattern to alter its
5739
    behavior.  For example, <literal>FMMonth</literal>
5740
    is the <literal>Month</literal> pattern with the
5741
    <literal>FM</literal> modifier.
5742
    <xref linkend="functions-formatting-datetimemod-table"> shows the
5743
    modifier patterns for date/time formatting.
5744
   </para>
5745
5746
    <table id="functions-formatting-datetimemod-table">
5747
     <title>Template Pattern Modifiers for Date/Time Formatting</title>
5748
     <tgroup cols="3">
5749
      <thead>
5750
       <row>
5751
        <entry>Modifier</entry>
5752
        <entry>Description</entry>
5753
        <entry>Example</entry>
5754
       </row>
5755
      </thead>
5756
      <tbody>
5757
       <row>
5758
        <entry><literal>FM</literal> prefix</entry>
1.2.3 by Martin Pitt
Import upstream version 9.3.10
5759
        <entry>fill mode (suppress leading zeroes and padding blanks)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
5760
        <entry><literal>FMMonth</literal></entry>
5761
       </row>
5762
       <row>
5763
        <entry><literal>TH</literal> suffix</entry>
5764
        <entry>upper case ordinal number suffix</entry>
5765
        <entry><literal>DDTH</literal>, e.g., <literal>12TH</></entry>
5766
       </row>
5767
       <row>
5768
        <entry><literal>th</literal> suffix</entry>
5769
        <entry>lower case ordinal number suffix</entry>
5770
        <entry><literal>DDth</literal>, e.g., <literal>12th</></entry>
5771
       </row>
5772
       <row>
5773
        <entry><literal>FX</literal> prefix</entry>
5774
        <entry>fixed format global option (see usage notes)</entry>
5775
        <entry><literal>FX&nbsp;Month&nbsp;DD&nbsp;Day</literal></entry>
5776
       </row>
5777
       <row>
5778
        <entry><literal>TM</literal> prefix</entry>
5779
        <entry>translation mode (print localized day and month names based on
5780
         <xref linkend="guc-lc-time">)</entry>
5781
        <entry><literal>TMMonth</literal></entry>
5782
       </row>
5783
       <row>
5784
        <entry><literal>SP</literal> suffix</entry>
5785
        <entry>spell mode (not implemented)</entry>
5786
        <entry><literal>DDSP</literal></entry>
5787
       </row>
5788
      </tbody>
5789
     </tgroup>
5790
    </table>
5791
5792
   <para>
5793
    Usage notes for date/time formatting:
5794
5795
    <itemizedlist>
5796
     <listitem>
5797
      <para>
5798
       <literal>FM</literal> suppresses leading zeroes and trailing blanks
5799
       that would otherwise be added to make the output of a pattern be
5800
       fixed-width.  In <productname>PostgreSQL</productname>,
5801
       <literal>FM</literal> modifies only the next specification, while in
5802
       Oracle <literal>FM</literal> affects all subsequent
5803
       specifications, and repeated <literal>FM</literal> modifiers
5804
       toggle fill mode on and off.
5805
      </para>
5806
     </listitem>
5807
5808
     <listitem>
5809
      <para>
5810
       <literal>TM</literal> does not include trailing blanks.
5811
      </para>
5812
     </listitem>
5813
5814
     <listitem>
5815
      <para>
5816
       <function>to_timestamp</function> and <function>to_date</function>
5817
       skip multiple blank spaces in the input string unless the
5818
       <literal>FX</literal> option is used. For example,
5819
       <literal>to_timestamp('2000&nbsp;&nbsp;&nbsp;&nbsp;JUN', 'YYYY MON')</literal> works, but
5820
       <literal>to_timestamp('2000&nbsp;&nbsp;&nbsp;&nbsp;JUN', 'FXYYYY MON')</literal> returns an error
5821
       because <function>to_timestamp</function> expects one space only.
5822
       <literal>FX</literal> must be specified as the first item in
5823
       the template.
5824
      </para>
5825
     </listitem>
5826
5827
     <listitem>
5828
      <para>
5829
       Ordinary text is allowed in <function>to_char</function>
5830
       templates and will be output literally.  You can put a substring
5831
       in double quotes to force it to be interpreted as literal text
5832
       even if it contains pattern key words.  For example, in
5833
       <literal>'"Hello Year "YYYY'</literal>, the <literal>YYYY</literal>
5834
       will be replaced by the year data, but the single <literal>Y</literal> in <literal>Year</literal>
5835
       will not be.  In <function>to_date</>, <function>to_number</>,
5836
       and <function>to_timestamp</>, double-quoted strings skip the number of
5837
       input characters contained in the string, e.g. <literal>"XX"</>
5838
       skips two input characters.
5839
      </para>
5840
     </listitem>
5841
5842
     <listitem>
5843
      <para>
5844
       If you want to have a double quote in the output you must
5845
       precede it with a backslash, for example <literal>'\"YYYY
5846
       Month\"'</literal>. <!-- "" font-lock sanity :-) -->
5847
      </para>
5848
     </listitem>
5849
5850
     <listitem>
5851
      <para>
5852
       If the year format specification is less than four digits, e.g.
5853
       <literal>YYY</>, and the supplied year is less than four digits,
5854
       the year will be adjusted to be nearest to the year 2020, e.g.
5855
       <literal>95</> becomes 1995.
5856
      </para>
5857
     </listitem>
5858
5859
     <listitem>
5860
      <para>
5861
       The <literal>YYYY</literal> conversion from string to <type>timestamp</type> or
5862
       <type>date</type> has a restriction when processing years with more than 4 digits. You must
5863
       use some non-digit character or template after <literal>YYYY</literal>,
5864
       otherwise the year is always interpreted as 4 digits. For example
5865
       (with the year 20000):
5866
       <literal>to_date('200001131', 'YYYYMMDD')</literal> will be
5867
       interpreted as a 4-digit year; instead use a non-digit
5868
       separator after the year, like
5869
       <literal>to_date('20000-1131', 'YYYY-MMDD')</literal> or
5870
       <literal>to_date('20000Nov31', 'YYYYMonDD')</literal>.
5871
      </para>
5872
     </listitem>
5873
5874
     <listitem>
5875
      <para>
5876
       In conversions from string to <type>timestamp</type> or
5877
       <type>date</type>, the <literal>CC</literal> (century) field is ignored
5878
       if there is a <literal>YYY</literal>, <literal>YYYY</literal> or
5879
       <literal>Y,YYY</literal> field. If <literal>CC</literal> is used with
5880
       <literal>YY</literal> or <literal>Y</literal> then the year is computed
5881
       as the year in the specified century.  If the century is
5882
       specified but the year is not, the first year of the century
5883
       is assumed.
5884
      </para>
5885
     </listitem>
5886
5887
     <listitem>
5888
      <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5889
       An ISO 8601 week-numbering date (as distinct from a Gregorian date)
5890
       can be specified to <function>to_timestamp</function> and
1 by Martin Pitt
Import upstream version 9.3~beta1
5891
       <function>to_date</function> in one of two ways:
5892
       <itemizedlist>
5893
        <listitem>
5894
         <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5895
          Year, week number, and weekday:  for
5896
          example <literal>to_date('2006-42-4', 'IYYY-IW-ID')</literal>
5897
          returns the date <literal>2006-10-19</literal>.
5898
          If you omit the weekday it is assumed to be 1 (Monday).
1 by Martin Pitt
Import upstream version 9.3~beta1
5899
         </para>
5900
        </listitem>
5901
        <listitem>
5902
         <para>
5903
          Year and day of year:  for example <literal>to_date('2006-291',
5904
          'IYYY-IDDD')</literal> also returns <literal>2006-10-19</literal>.
5905
         </para>
5906
        </listitem>
5907
       </itemizedlist>
5908
      </para>
5909
      <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5910
       Attempting to enter a date using a mixture of ISO 8601 week-numbering
5911
       fields and Gregorian date fields is nonsensical, and will cause an
5912
       error.  In the context of an ISO 8601 week-numbering year, the
5913
       concept of a <quote>month</> or <quote>day of month</> has no
5914
       meaning.  In the context of a Gregorian year, the ISO week has no
5915
       meaning.
1 by Martin Pitt
Import upstream version 9.3~beta1
5916
      </para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
5917
      <caution>
5918
       <para>
5919
        While <function>to_date</function> will reject a mixture of
5920
        Gregorian and ISO week-numbering date
5921
        fields, <function>to_char</function> will not, since output format
5922
        specifications like <literal>YYYY-MM-DD (IYYY-IDDD)</> can be
5923
        useful.  But avoid writing something like <literal>IYYY-MM-DD</>;
5924
        that would yield surprising results near the start of the year.
5925
        (See <xref linkend="functions-datetime-extract"> for more
5926
        information.)
5927
       </para>
5928
      </caution>
1 by Martin Pitt
Import upstream version 9.3~beta1
5929
     </listitem>
5930
5931
     <listitem>
5932
      <para>
5933
       In a conversion from string to <type>timestamp</type>, millisecond
5934
       (<literal>MS</literal>) or microsecond (<literal>US</literal>)
5935
       values are used as the
5936
       seconds digits after the decimal point. For example
5937
       <literal>to_timestamp('12:3', 'SS:MS')</literal> is not 3 milliseconds,
5938
       but 300, because the conversion counts it as 12 + 0.3 seconds.
5939
       This means for the format <literal>SS:MS</literal>, the input values
5940
       <literal>12:3</literal>, <literal>12:30</literal>, and <literal>12:300</literal> specify the
5941
       same number of milliseconds. To get three milliseconds, one must use
5942
       <literal>12:003</literal>, which the conversion counts as
5943
       12 + 0.003 = 12.003 seconds.
5944
      </para>
5945
5946
      <para>
5947
       Here is a more
5948
       complex example:
5949
       <literal>to_timestamp('15:12:02.020.001230', 'HH:MI:SS.MS.US')</literal>
5950
       is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds +
5951
       1230 microseconds = 2.021230 seconds.
5952
      </para>
5953
     </listitem>
5954
5955
     <listitem>
5956
      <para>
5957
        <function>to_char(..., 'ID')</function>'s day of the week numbering
5958
        matches the <function>extract(isodow from ...)</function> function, but
5959
        <function>to_char(..., 'D')</function>'s does not match
5960
        <function>extract(dow from ...)</function>'s day numbering.
5961
      </para>
5962
     </listitem>
5963
5964
     <listitem>
5965
      <para>
5966
        <function>to_char(interval)</function> formats <literal>HH</> and
5967
        <literal>HH12</> as shown on a 12-hour clock, i.e. zero hours
5968
        and 36 hours output as <literal>12</>, while <literal>HH24</>
5969
        outputs the full hour value, which can exceed 23 for intervals.
5970
      </para>
5971
     </listitem>
5972
5973
    </itemizedlist>
5974
   </para>
5975
5976
  <para>
5977
   <xref linkend="functions-formatting-numeric-table"> shows the
5978
   template patterns available for formatting numeric values.
5979
  </para>
5980
5981
    <table id="functions-formatting-numeric-table">
5982
     <title>Template Patterns for Numeric Formatting</title>
5983
     <tgroup cols="2">
5984
      <thead>
5985
       <row>
5986
        <entry>Pattern</entry>
5987
        <entry>Description</entry>
5988
       </row>
5989
      </thead>
5990
      <tbody>
5991
       <row>
5992
        <entry><literal>9</literal></entry>
5993
        <entry>value with the specified number of digits</entry>
5994
       </row>
5995
       <row>
5996
        <entry><literal>0</literal></entry>
5997
        <entry>value with leading zeros</entry>
5998
       </row>
5999
       <row>
6000
        <entry><literal>.</literal> (period)</entry>
6001
        <entry>decimal point</entry>
6002
       </row>
6003
       <row>
6004
        <entry><literal>,</literal> (comma)</entry>
6005
        <entry>group (thousand) separator</entry>
6006
       </row>
6007
       <row>
6008
        <entry><literal>PR</literal></entry>
6009
        <entry>negative value in angle brackets</entry>
6010
       </row>
6011
       <row>
6012
        <entry><literal>S</literal></entry>
6013
        <entry>sign anchored to number (uses locale)</entry>
6014
       </row>
6015
       <row>
6016
        <entry><literal>L</literal></entry>
6017
        <entry>currency symbol (uses locale)</entry>
6018
       </row>
6019
       <row>
6020
        <entry><literal>D</literal></entry>
6021
        <entry>decimal point (uses locale)</entry>
6022
       </row>
6023
       <row>
6024
        <entry><literal>G</literal></entry>
6025
        <entry>group separator (uses locale)</entry>
6026
       </row>
6027
       <row>
6028
        <entry><literal>MI</literal></entry>
6029
        <entry>minus sign in specified position (if number &lt; 0)</entry>
6030
       </row>
6031
       <row>
6032
        <entry><literal>PL</literal></entry>
6033
        <entry>plus sign in specified position (if number &gt; 0)</entry>
6034
       </row>
6035
       <row>
6036
        <entry><literal>SG</literal></entry>
6037
        <entry>plus/minus sign in specified position</entry>
6038
       </row>
6039
       <row>
6040
        <entry><literal>RN</literal></entry>
6041
        <entry>Roman numeral (input between 1 and 3999)</entry>
6042
       </row>
6043
       <row>
6044
        <entry><literal>TH</literal> or <literal>th</literal></entry>
6045
        <entry>ordinal number suffix</entry>
6046
       </row>
6047
       <row>
6048
        <entry><literal>V</literal></entry>
6049
        <entry>shift specified number of digits (see notes)</entry>
6050
       </row>
6051
       <row>
6052
        <entry><literal>EEEE</literal></entry>
6053
        <entry>exponent for scientific notation</entry>
6054
       </row>
6055
      </tbody>
6056
     </tgroup>
6057
    </table>
6058
6059
   <para>
6060
    Usage notes for numeric formatting:
6061
6062
    <itemizedlist>
6063
     <listitem>
6064
      <para>
6065
       A sign formatted using <literal>SG</literal>, <literal>PL</literal>, or
6066
       <literal>MI</literal> is not anchored to
6067
       the number; for example,
6068
       <literal>to_char(-12, 'MI9999')</literal> produces <literal>'-&nbsp;&nbsp;12'</literal>
6069
       but <literal>to_char(-12, 'S9999')</literal> produces <literal>'&nbsp;&nbsp;-12'</literal>.
6070
       The Oracle implementation does not allow the use of
6071
       <literal>MI</literal> before <literal>9</literal>, but rather
6072
       requires that <literal>9</literal> precede
6073
       <literal>MI</literal>.
6074
      </para>
6075
     </listitem>
6076
6077
     <listitem>
6078
      <para>
6079
       <literal>9</literal> results in a value with the same number of
6080
       digits as there are <literal>9</literal>s. If a digit is
6081
       not available it outputs a space.
6082
      </para>
6083
     </listitem>
6084
6085
     <listitem>
6086
      <para>
6087
       <literal>TH</literal> does not convert values less than zero
6088
       and does not convert fractional numbers.
6089
      </para>
6090
     </listitem>
6091
6092
     <listitem>
6093
      <para>
6094
       <literal>PL</literal>, <literal>SG</literal>, and
6095
       <literal>TH</literal> are <productname>PostgreSQL</productname>
6096
       extensions.
6097
      </para>
6098
     </listitem>
6099
6100
     <listitem>
6101
      <para>
6102
       <literal>V</literal> effectively
6103
       multiplies the input values by
6104
       <literal>10^<replaceable>n</replaceable></literal>, where
6105
       <replaceable>n</replaceable> is the number of digits following
6106
       <literal>V</literal>.
6107
       <function>to_char</function> does not support the use of
6108
       <literal>V</literal> combined with a decimal point
6109
       (e.g., <literal>99.9V99</literal> is not allowed).
6110
      </para>
6111
     </listitem>
6112
6113
     <listitem>
6114
      <para>
6115
       <literal>EEEE</literal> (scientific notation) cannot be used in
6116
       combination with any of the other formatting patterns or
6117
       modifiers other than digit and decimal point patterns, and must be at the end of the format string
6118
       (e.g., <literal>9.99EEEE</literal> is a valid pattern).
6119
      </para>
6120
     </listitem>
6121
    </itemizedlist>
6122
   </para>
6123
6124
   <para>
6125
    Certain modifiers can be applied to any template pattern to alter its
6126
    behavior.  For example, <literal>FM9999</literal>
6127
    is the <literal>9999</literal> pattern with the
6128
    <literal>FM</literal> modifier.
6129
    <xref linkend="functions-formatting-numericmod-table"> shows the
6130
    modifier patterns for numeric formatting.
6131
   </para>
6132
6133
    <table id="functions-formatting-numericmod-table">
6134
     <title>Template Pattern Modifiers for Numeric Formatting</title>
6135
     <tgroup cols="3">
6136
      <thead>
6137
       <row>
6138
        <entry>Modifier</entry>
6139
        <entry>Description</entry>
6140
        <entry>Example</entry>
6141
       </row>
6142
      </thead>
6143
      <tbody>
6144
       <row>
6145
        <entry><literal>FM</literal> prefix</entry>
1.2.3 by Martin Pitt
Import upstream version 9.3.10
6146
        <entry>fill mode (suppress leading zeroes and padding blanks)</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
6147
        <entry><literal>FM9999</literal></entry>
6148
       </row>
6149
       <row>
6150
        <entry><literal>TH</literal> suffix</entry>
6151
        <entry>upper case ordinal number suffix</entry>
6152
        <entry><literal>999TH</literal></entry>
6153
       </row>
6154
       <row>
6155
        <entry><literal>th</literal> suffix</entry>
6156
        <entry>lower case ordinal number suffix</entry>
6157
        <entry><literal>999th</literal></entry>
6158
       </row>
6159
      </tbody>
6160
     </tgroup>
6161
    </table>
6162
6163
  <para>
6164
   <xref linkend="functions-formatting-examples-table"> shows some
6165
   examples of the use of the <function>to_char</function> function.
6166
  </para>
6167
6168
    <table id="functions-formatting-examples-table">
6169
     <title><function>to_char</function> Examples</title>
6170
     <tgroup cols="2">
6171
      <thead>
6172
       <row>
6173
        <entry>Expression</entry>
6174
        <entry>Result</entry>
6175
       </row>
6176
      </thead>
6177
      <tbody>
6178
       <row>
6179
        <entry><literal>to_char(current_timestamp, 'Day,&nbsp;DD&nbsp;&nbsp;HH12:MI:SS')</literal></entry>
6180
        <entry><literal>'Tuesday&nbsp;&nbsp;,&nbsp;06&nbsp;&nbsp;05:39:18'</literal></entry>
6181
       </row>
6182
       <row>
6183
        <entry><literal>to_char(current_timestamp, 'FMDay,&nbsp;FMDD&nbsp;&nbsp;HH12:MI:SS')</literal></entry>
6184
        <entry><literal>'Tuesday,&nbsp;6&nbsp;&nbsp;05:39:18'</literal></entry>
6185
       </row>
6186
       <row>
6187
        <entry><literal>to_char(-0.1, '99.99')</literal></entry>
6188
        <entry><literal>'&nbsp;&nbsp;-.10'</literal></entry>
6189
       </row>
6190
       <row>
6191
        <entry><literal>to_char(-0.1, 'FM9.99')</literal></entry>
6192
        <entry><literal>'-.1'</literal></entry>
6193
       </row>
6194
       <row>
6195
        <entry><literal>to_char(0.1, '0.9')</literal></entry>
6196
        <entry><literal>'&nbsp;0.1'</literal></entry>
6197
       </row>
6198
       <row>
6199
        <entry><literal>to_char(12, '9990999.9')</literal></entry>
6200
        <entry><literal>'&nbsp;&nbsp;&nbsp;&nbsp;0012.0'</literal></entry>
6201
       </row>
6202
       <row>
6203
        <entry><literal>to_char(12, 'FM9990999.9')</literal></entry>
6204
        <entry><literal>'0012.'</literal></entry>
6205
       </row>
6206
       <row>
6207
        <entry><literal>to_char(485, '999')</literal></entry>
6208
        <entry><literal>'&nbsp;485'</literal></entry>
6209
       </row>
6210
       <row>
6211
        <entry><literal>to_char(-485, '999')</literal></entry>
6212
        <entry><literal>'-485'</literal></entry>
6213
       </row>
6214
       <row>
6215
        <entry><literal>to_char(485, '9&nbsp;9&nbsp;9')</literal></entry>
6216
        <entry><literal>'&nbsp;4&nbsp;8&nbsp;5'</literal></entry>
6217
       </row>
6218
       <row>
6219
        <entry><literal>to_char(1485, '9,999')</literal></entry>
6220
        <entry><literal>'&nbsp;1,485'</literal></entry>
6221
       </row>
6222
       <row>
6223
        <entry><literal>to_char(1485, '9G999')</literal></entry>
6224
        <entry><literal>'&nbsp;1&nbsp;485'</literal></entry>
6225
       </row>
6226
       <row>
6227
        <entry><literal>to_char(148.5, '999.999')</literal></entry>
6228
        <entry><literal>'&nbsp;148.500'</literal></entry>
6229
       </row>
6230
       <row>
6231
        <entry><literal>to_char(148.5, 'FM999.999')</literal></entry>
6232
        <entry><literal>'148.5'</literal></entry>
6233
       </row>
6234
       <row>
6235
        <entry><literal>to_char(148.5, 'FM999.990')</literal></entry>
6236
        <entry><literal>'148.500'</literal></entry>
6237
       </row>
6238
       <row>
6239
        <entry><literal>to_char(148.5, '999D999')</literal></entry>
6240
        <entry><literal>'&nbsp;148,500'</literal></entry>
6241
       </row>
6242
       <row>
6243
        <entry><literal>to_char(3148.5, '9G999D999')</literal></entry>
6244
        <entry><literal>'&nbsp;3&nbsp;148,500'</literal></entry>
6245
       </row>
6246
       <row>
6247
        <entry><literal>to_char(-485, '999S')</literal></entry>
6248
        <entry><literal>'485-'</literal></entry>
6249
       </row>
6250
       <row>
6251
        <entry><literal>to_char(-485, '999MI')</literal></entry>
6252
        <entry><literal>'485-'</literal></entry>
6253
       </row>
6254
       <row>
6255
        <entry><literal>to_char(485, '999MI')</literal></entry>
6256
        <entry><literal>'485&nbsp;'</literal></entry>
6257
       </row>
6258
       <row>
6259
        <entry><literal>to_char(485, 'FM999MI')</literal></entry>
6260
        <entry><literal>'485'</literal></entry>
6261
       </row>
6262
       <row>
6263
        <entry><literal>to_char(485, 'PL999')</literal></entry>
6264
        <entry><literal>'+485'</literal></entry>
6265
       </row>
6266
       <row>
6267
        <entry><literal>to_char(485, 'SG999')</literal></entry>
6268
        <entry><literal>'+485'</literal></entry>
6269
       </row>
6270
       <row>
6271
        <entry><literal>to_char(-485, 'SG999')</literal></entry>
6272
        <entry><literal>'-485'</literal></entry>
6273
       </row>
6274
       <row>
6275
        <entry><literal>to_char(-485, '9SG99')</literal></entry>
6276
        <entry><literal>'4-85'</literal></entry>
6277
       </row>
6278
       <row>
6279
        <entry><literal>to_char(-485, '999PR')</literal></entry>
6280
        <entry><literal>'&lt;485&gt;'</literal></entry>
6281
       </row>
6282
       <row>
6283
        <entry><literal>to_char(485, 'L999')</literal></entry>
1.2.3 by Martin Pitt
Import upstream version 9.3.10
6284
        <entry><literal>'DM&nbsp;485'</literal></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
6285
       </row>
6286
       <row>
6287
        <entry><literal>to_char(485, 'RN')</literal></entry>
6288
        <entry><literal>'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CDLXXXV'</literal></entry>
6289
       </row>
6290
       <row>
6291
        <entry><literal>to_char(485, 'FMRN')</literal></entry>
6292
        <entry><literal>'CDLXXXV'</literal></entry>
6293
       </row>
6294
       <row>
6295
        <entry><literal>to_char(5.2, 'FMRN')</literal></entry>
6296
        <entry><literal>'V'</literal></entry>
6297
       </row>
6298
       <row>
6299
        <entry><literal>to_char(482, '999th')</literal></entry>
6300
        <entry><literal>'&nbsp;482nd'</literal></entry>
6301
       </row>
6302
       <row>
6303
        <entry><literal>to_char(485, '"Good&nbsp;number:"999')</literal></entry>
6304
        <entry><literal>'Good&nbsp;number:&nbsp;485'</literal></entry>
6305
       </row>
6306
       <row>
6307
        <entry><literal>to_char(485.8, '"Pre:"999"&nbsp;Post:"&nbsp;.999')</literal></entry>
6308
        <entry><literal>'Pre:&nbsp;485&nbsp;Post:&nbsp;.800'</literal></entry>
6309
       </row>
6310
       <row>
6311
        <entry><literal>to_char(12, '99V999')</literal></entry>
6312
        <entry><literal>'&nbsp;12000'</literal></entry>
6313
       </row>
6314
       <row>
6315
        <entry><literal>to_char(12.4, '99V999')</literal></entry>
6316
        <entry><literal>'&nbsp;12400'</literal></entry>
6317
       </row>
6318
       <row>
6319
        <entry><literal>to_char(12.45, '99V9')</literal></entry>
6320
        <entry><literal>'&nbsp;125'</literal></entry>
6321
       </row>
6322
       <row>
6323
        <entry><literal>to_char(0.0004859, '9.99EEEE')</literal></entry>
6324
        <entry><literal>' 4.86e-04'</literal></entry>
6325
       </row>
6326
      </tbody>
6327
     </tgroup>
6328
    </table>
6329
6330
  </sect1>
6331
6332
6333
  <sect1 id="functions-datetime">
6334
   <title>Date/Time Functions and Operators</title>
6335
6336
  <para>
6337
   <xref linkend="functions-datetime-table"> shows the available
6338
   functions for date/time value processing, with details appearing in
6339
   the following subsections.  <xref
6340
   linkend="operators-datetime-table"> illustrates the behaviors of
6341
   the basic arithmetic operators (<literal>+</literal>,
6342
   <literal>*</literal>, etc.).  For formatting functions, refer to
6343
   <xref linkend="functions-formatting">.  You should be familiar with
6344
   the background information on date/time data types from <xref
6345
   linkend="datatype-datetime">.
6346
  </para>
6347
6348
  <para>
6349
   All the functions and operators described below that take <type>time</type> or <type>timestamp</type>
6350
   inputs actually come in two variants: one that takes <type>time with time zone</type> or <type>timestamp
6351
   with time zone</type>, and one that takes <type>time without time zone</type> or <type>timestamp without time zone</type>.
6352
   For brevity, these variants are not shown separately.  Also, the
6353
   <literal>+</> and <literal>*</> operators come in commutative pairs (for
6354
   example both date + integer and integer + date); we show only one of each
6355
   such pair.
6356
  </para>
6357
6358
    <table id="operators-datetime-table">
6359
     <title>Date/Time Operators</title>
6360
6361
     <tgroup cols="3">
6362
      <thead>
6363
       <row>
6364
        <entry>Operator</entry>
6365
        <entry>Example</entry>
6366
        <entry>Result</entry>
6367
       </row>
6368
      </thead>
6369
6370
      <tbody>
6371
       <row>
6372
        <entry> <literal>+</literal> </entry>
6373
        <entry><literal>date '2001-09-28' + integer '7'</literal></entry>
6374
        <entry><literal>date '2001-10-05'</literal></entry>
6375
       </row>
6376
6377
       <row>
6378
        <entry> <literal>+</literal> </entry>
6379
        <entry><literal>date '2001-09-28' + interval '1 hour'</literal></entry>
6380
        <entry><literal>timestamp '2001-09-28 01:00:00'</literal></entry>
6381
       </row>
6382
6383
       <row>
6384
        <entry> <literal>+</literal> </entry>
6385
        <entry><literal>date '2001-09-28' + time '03:00'</literal></entry>
6386
        <entry><literal>timestamp '2001-09-28 03:00:00'</literal></entry>
6387
       </row>
6388
6389
       <row>
6390
        <entry> <literal>+</literal> </entry>
6391
        <entry><literal>interval '1 day' + interval '1 hour'</literal></entry>
6392
        <entry><literal>interval '1 day 01:00:00'</literal></entry>
6393
       </row>
6394
6395
       <row>
6396
        <entry> <literal>+</literal> </entry>
6397
        <entry><literal>timestamp '2001-09-28 01:00' + interval '23 hours'</literal></entry>
6398
        <entry><literal>timestamp '2001-09-29 00:00:00'</literal></entry>
6399
       </row>
6400
6401
       <row>
6402
        <entry> <literal>+</literal> </entry>
6403
        <entry><literal>time '01:00' + interval '3 hours'</literal></entry>
6404
        <entry><literal>time '04:00:00'</literal></entry>
6405
       </row>
6406
6407
       <row>
6408
        <entry> <literal>-</literal> </entry>
6409
        <entry><literal>- interval '23 hours'</literal></entry>
6410
        <entry><literal>interval '-23:00:00'</literal></entry>
6411
       </row>
6412
6413
       <row>
6414
        <entry> <literal>-</literal> </entry>
6415
        <entry><literal>date '2001-10-01' - date '2001-09-28'</literal></entry>
6416
        <entry><literal>integer '3'</literal> (days)</entry>
6417
       </row>
6418
6419
       <row>
6420
        <entry> <literal>-</literal> </entry>
6421
        <entry><literal>date '2001-10-01' - integer '7'</literal></entry>
6422
        <entry><literal>date '2001-09-24'</literal></entry>
6423
       </row>
6424
6425
       <row>
6426
        <entry> <literal>-</literal> </entry>
6427
        <entry><literal>date '2001-09-28' - interval '1 hour'</literal></entry>
6428
        <entry><literal>timestamp '2001-09-27 23:00:00'</literal></entry>
6429
       </row>
6430
6431
       <row>
6432
        <entry> <literal>-</literal> </entry>
6433
        <entry><literal>time '05:00' - time '03:00'</literal></entry>
6434
        <entry><literal>interval '02:00:00'</literal></entry>
6435
       </row>
6436
6437
       <row>
6438
        <entry> <literal>-</literal> </entry>
6439
        <entry><literal>time '05:00' - interval '2 hours'</literal></entry>
6440
        <entry><literal>time '03:00:00'</literal></entry>
6441
       </row>
6442
6443
       <row>
6444
        <entry> <literal>-</literal> </entry>
6445
        <entry><literal>timestamp '2001-09-28 23:00' - interval '23 hours'</literal></entry>
6446
        <entry><literal>timestamp '2001-09-28 00:00:00'</literal></entry>
6447
       </row>
6448
6449
       <row>
6450
        <entry> <literal>-</literal> </entry>
6451
        <entry><literal>interval '1 day' - interval '1 hour'</literal></entry>
6452
        <entry><literal>interval '1 day -01:00:00'</literal></entry>
6453
       </row>
6454
6455
       <row>
6456
        <entry> <literal>-</literal> </entry>
6457
        <entry><literal>timestamp '2001-09-29 03:00' - timestamp '2001-09-27 12:00'</literal></entry>
6458
        <entry><literal>interval '1 day 15:00:00'</literal></entry>
6459
       </row>
6460
6461
       <row>
6462
        <entry> <literal>*</literal> </entry>
6463
        <entry><literal>900 * interval '1 second'</literal></entry>
6464
        <entry><literal>interval '00:15:00'</literal></entry>
6465
       </row>
6466
6467
       <row>
6468
        <entry> <literal>*</literal> </entry>
6469
        <entry><literal>21 * interval '1 day'</literal></entry>
6470
        <entry><literal>interval '21 days'</literal></entry>
6471
       </row>
6472
6473
       <row>
6474
        <entry> <literal>*</literal> </entry>
6475
        <entry><literal>double precision '3.5' * interval '1 hour'</literal></entry>
6476
        <entry><literal>interval '03:30:00'</literal></entry>
6477
       </row>
6478
6479
       <row>
6480
        <entry> <literal>/</literal> </entry>
6481
        <entry><literal>interval '1 hour' / double precision '1.5'</literal></entry>
6482
        <entry><literal>interval '00:40:00'</literal></entry>
6483
       </row>
6484
      </tbody>
6485
     </tgroup>
6486
    </table>
6487
6488
    <table id="functions-datetime-table">
6489
     <title>Date/Time Functions</title>
6490
     <tgroup cols="5">
6491
      <thead>
6492
       <row>
6493
        <entry>Function</entry>
6494
        <entry>Return Type</entry>
6495
        <entry>Description</entry>
6496
        <entry>Example</entry>
6497
        <entry>Result</entry>
6498
       </row>
6499
      </thead>
6500
6501
      <tbody>
6502
       <row>
6503
        <entry>
6504
         <indexterm>
6505
          <primary>age</primary>
6506
         </indexterm>
6507
         <literal><function>age(<type>timestamp</type>, <type>timestamp</type>)</function></literal>
6508
        </entry>
6509
        <entry><type>interval</type></entry>
6510
        <entry>Subtract arguments, producing a <quote>symbolic</> result that
6511
        uses years and months</entry>
6512
        <entry><literal>age(timestamp '2001-04-10', timestamp '1957-06-13')</literal></entry>
6513
        <entry><literal>43 years 9 mons 27 days</literal></entry>
6514
       </row>
6515
6516
       <row>
6517
        <entry><literal><function>age(<type>timestamp</type>)</function></literal></entry>
6518
        <entry><type>interval</type></entry>
6519
        <entry>Subtract from <function>current_date</function> (at midnight)</entry>
6520
        <entry><literal>age(timestamp '1957-06-13')</literal></entry>
6521
        <entry><literal>43 years 8 mons 3 days</literal></entry>
6522
       </row>
6523
6524
       <row>
6525
        <entry>
6526
         <indexterm>
6527
          <primary>clock_timestamp</primary>
6528
         </indexterm>
6529
         <literal><function>clock_timestamp()</function></literal>
6530
        </entry>
6531
        <entry><type>timestamp with time zone</type></entry>
6532
        <entry>Current date and time (changes during statement execution);
6533
         see <xref linkend="functions-datetime-current">
6534
        </entry>
6535
        <entry></entry>
6536
        <entry></entry>
6537
       </row>
6538
6539
       <row>
6540
        <entry>
6541
         <indexterm>
6542
          <primary>current_date</primary>
6543
         </indexterm>
6544
         <literal><function>current_date</function></literal>
6545
        </entry>
6546
        <entry><type>date</type></entry>
6547
        <entry>Current date;
6548
         see <xref linkend="functions-datetime-current">
6549
        </entry>
6550
        <entry></entry>
6551
        <entry></entry>
6552
       </row>
6553
6554
       <row>
6555
        <entry>
6556
         <indexterm>
6557
          <primary>current_time</primary>
6558
         </indexterm>
6559
         <literal><function>current_time</function></literal>
6560
        </entry>
6561
        <entry><type>time with time zone</type></entry>
6562
        <entry>Current time of day;
6563
         see <xref linkend="functions-datetime-current">
6564
        </entry>
6565
        <entry></entry>
6566
        <entry></entry>
6567
       </row>
6568
6569
       <row>
6570
        <entry>
6571
         <indexterm>
6572
          <primary>current_timestamp</primary>
6573
         </indexterm>
6574
         <literal><function>current_timestamp</function></literal>
6575
        </entry>
6576
        <entry><type>timestamp with time zone</type></entry>
6577
        <entry>Current date and time (start of current transaction);
6578
         see <xref linkend="functions-datetime-current">
6579
        </entry>
6580
        <entry></entry>
6581
        <entry></entry>
6582
       </row>
6583
6584
       <row>
6585
        <entry>
6586
         <indexterm>
6587
          <primary>date_part</primary>
6588
         </indexterm>
6589
         <literal><function>date_part(<type>text</type>, <type>timestamp</type>)</function></literal>
6590
        </entry>
6591
        <entry><type>double precision</type></entry>
6592
        <entry>Get subfield (equivalent to <function>extract</function>);
6593
         see <xref linkend="functions-datetime-extract">
6594
        </entry>
6595
        <entry><literal>date_part('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
6596
        <entry><literal>20</literal></entry>
6597
       </row>
6598
6599
       <row>
6600
        <entry><literal><function>date_part(<type>text</type>, <type>interval</type>)</function></literal></entry>
6601
        <entry><type>double precision</type></entry>
6602
        <entry>Get subfield (equivalent to
6603
         <function>extract</function>); see <xref linkend="functions-datetime-extract">
6604
        </entry>
6605
        <entry><literal>date_part('month', interval '2 years 3 months')</literal></entry>
6606
        <entry><literal>3</literal></entry>
6607
       </row>
6608
6609
       <row>
6610
        <entry>
6611
         <indexterm>
6612
          <primary>date_trunc</primary>
6613
         </indexterm>
6614
         <literal><function>date_trunc(<type>text</type>, <type>timestamp</type>)</function></literal>
6615
        </entry>
6616
        <entry><type>timestamp</type></entry>
6617
        <entry>Truncate to specified precision; see also <xref linkend="functions-datetime-trunc">
6618
        </entry>
6619
        <entry><literal>date_trunc('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
6620
        <entry><literal>2001-02-16 20:00:00</literal></entry>
6621
       </row>
6622
6623
       <row>
6624
        <entry>
6625
         <indexterm>
6626
          <primary>extract</primary>
6627
         </indexterm>
6628
         <literal><function>extract</function>(<parameter>field</parameter> from
6629
         <type>timestamp</type>)</literal>
6630
        </entry>
6631
        <entry><type>double precision</type></entry>
6632
        <entry>Get subfield; see <xref linkend="functions-datetime-extract">
6633
        </entry>
6634
        <entry><literal>extract(hour from timestamp '2001-02-16 20:38:40')</literal></entry>
6635
        <entry><literal>20</literal></entry>
6636
       </row>
6637
6638
       <row>
6639
        <entry><literal><function>extract</function>(<parameter>field</parameter> from
6640
         <type>interval</type>)</literal></entry>
6641
        <entry><type>double precision</type></entry>
6642
        <entry>Get subfield; see <xref linkend="functions-datetime-extract">
6643
        </entry>
6644
        <entry><literal>extract(month from interval '2 years 3 months')</literal></entry>
6645
        <entry><literal>3</literal></entry>
6646
       </row>
6647
6648
       <row>
6649
        <entry>
6650
         <indexterm>
6651
          <primary>isfinite</primary>
6652
         </indexterm>
6653
         <literal><function>isfinite(<type>date</type>)</function></literal>
6654
        </entry>
6655
        <entry><type>boolean</type></entry>
6656
        <entry>Test for finite date (not +/-infinity)</entry>
6657
        <entry><literal>isfinite(date '2001-02-16')</literal></entry>
6658
        <entry><literal>true</literal></entry>
6659
       </row>
6660
6661
       <row>
6662
        <entry><literal><function>isfinite(<type>timestamp</type>)</function></literal></entry>
6663
        <entry><type>boolean</type></entry>
6664
        <entry>Test for finite time stamp (not +/-infinity)</entry>
6665
        <entry><literal>isfinite(timestamp '2001-02-16 21:28:30')</literal></entry>
6666
        <entry><literal>true</literal></entry>
6667
       </row>
6668
6669
       <row>
6670
        <entry><literal><function>isfinite(<type>interval</type>)</function></literal></entry>
6671
        <entry><type>boolean</type></entry>
6672
        <entry>Test for finite interval</entry>
6673
        <entry><literal>isfinite(interval '4 hours')</literal></entry>
6674
        <entry><literal>true</literal></entry>
6675
       </row>
6676
6677
       <row>
6678
        <entry>
6679
         <indexterm>
6680
          <primary>justify_days</primary>
6681
         </indexterm>
6682
         <literal><function>justify_days(<type>interval</type>)</function></literal>
6683
        </entry>
6684
        <entry><type>interval</type></entry>
6685
        <entry>Adjust interval so 30-day time periods are represented as months</entry>
6686
        <entry><literal>justify_days(interval '35 days')</literal></entry>
6687
        <entry><literal>1 mon 5 days</literal></entry>
6688
       </row>
6689
6690
       <row>
6691
        <entry>
6692
         <indexterm>
6693
          <primary>justify_hours</primary>
6694
         </indexterm>
6695
         <literal><function>justify_hours(<type>interval</type>)</function></literal>
6696
        </entry>
6697
        <entry><type>interval</type></entry>
6698
        <entry>Adjust interval so 24-hour time periods are represented as days</entry>
6699
        <entry><literal>justify_hours(interval '27 hours')</literal></entry>
6700
        <entry><literal>1 day 03:00:00</literal></entry>
6701
       </row>
6702
6703
       <row>
6704
        <entry>
6705
         <indexterm>
6706
          <primary>justify_interval</primary>
6707
         </indexterm>
6708
         <literal><function>justify_interval(<type>interval</type>)</function></literal>
6709
        </entry>
6710
        <entry><type>interval</type></entry>
6711
        <entry>Adjust interval using <function>justify_days</> and <function>justify_hours</>, with additional sign adjustments</entry>
6712
        <entry><literal>justify_interval(interval '1 mon -1 hour')</literal></entry>
6713
        <entry><literal>29 days 23:00:00</literal></entry>
6714
       </row>
6715
6716
       <row>
6717
        <entry>
6718
         <indexterm>
6719
          <primary>localtime</primary>
6720
         </indexterm>
6721
         <literal><function>localtime</function></literal>
6722
        </entry>
6723
        <entry><type>time</type></entry>
6724
        <entry>Current time of day;
6725
         see <xref linkend="functions-datetime-current">
6726
        </entry>
6727
        <entry></entry>
6728
        <entry></entry>
6729
       </row>
6730
6731
       <row>
6732
        <entry>
6733
         <indexterm>
6734
          <primary>localtimestamp</primary>
6735
         </indexterm>
6736
         <literal><function>localtimestamp</function></literal>
6737
        </entry>
6738
        <entry><type>timestamp</type></entry>
6739
        <entry>Current date and time (start of current transaction);
6740
         see <xref linkend="functions-datetime-current">
6741
        </entry>
6742
        <entry></entry>
6743
        <entry></entry>
6744
       </row>
6745
6746
       <row>
6747
        <entry>
6748
         <indexterm>
6749
          <primary>now</primary>
6750
         </indexterm>
6751
         <literal><function>now()</function></literal>
6752
        </entry>
6753
        <entry><type>timestamp with time zone</type></entry>
6754
        <entry>Current date and time (start of current transaction);
6755
         see <xref linkend="functions-datetime-current">
6756
        </entry>
6757
        <entry></entry>
6758
        <entry></entry>
6759
       </row>
6760
6761
       <row>
6762
        <entry>
6763
         <indexterm>
6764
          <primary>statement_timestamp</primary>
6765
         </indexterm>
6766
         <literal><function>statement_timestamp()</function></literal>
6767
        </entry>
6768
        <entry><type>timestamp with time zone</type></entry>
6769
        <entry>Current date and time (start of current statement);
6770
         see <xref linkend="functions-datetime-current">
6771
        </entry>
6772
        <entry></entry>
6773
        <entry></entry>
6774
       </row>
6775
6776
       <row>
6777
        <entry>
6778
         <indexterm>
6779
          <primary>timeofday</primary>
6780
         </indexterm>
6781
         <literal><function>timeofday()</function></literal>
6782
        </entry>
6783
        <entry><type>text</type></entry>
6784
        <entry>Current date and time
6785
         (like <function>clock_timestamp</>, but as a <type>text</> string);
6786
         see <xref linkend="functions-datetime-current">
6787
        </entry>
6788
        <entry></entry>
6789
        <entry></entry>
6790
       </row>
6791
6792
       <row>
6793
        <entry>
6794
         <indexterm>
6795
          <primary>transaction_timestamp</primary>
6796
         </indexterm>
6797
         <literal><function>transaction_timestamp()</function></literal>
6798
        </entry>
6799
        <entry><type>timestamp with time zone</type></entry>
6800
        <entry>Current date and time (start of current transaction);
6801
         see <xref linkend="functions-datetime-current">
6802
        </entry>
6803
        <entry></entry>
6804
        <entry></entry>
6805
       </row>
6806
      </tbody>
6807
     </tgroup>
6808
    </table>
6809
6810
   <para>
1.1.6 by Christoph Berg
Import upstream version 9.3.3
6811
    <indexterm>
6812
      <primary>OVERLAPS</primary>
6813
    </indexterm>
1 by Martin Pitt
Import upstream version 9.3~beta1
6814
    In addition to these functions, the SQL <literal>OVERLAPS</> operator is
6815
    supported:
6816
<synopsis>
6817
(<replaceable>start1</replaceable>, <replaceable>end1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>end2</replaceable>)
6818
(<replaceable>start1</replaceable>, <replaceable>length1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>length2</replaceable>)
6819
</synopsis>
6820
    This expression yields true when two time periods (defined by their
6821
    endpoints) overlap, false when they do not overlap.  The endpoints
6822
    can be specified as pairs of dates, times, or time stamps; or as
6823
    a date, time, or time stamp followed by an interval.  When a pair
6824
    of values is provided, either the start or the end can be written
6825
    first; <literal>OVERLAPS</> automatically takes the earlier value
6826
    of the pair as the start.  Each time period is considered to
6827
    represent the half-open interval <replaceable>start</> <literal>&lt;=</>
6828
    <replaceable>time</> <literal>&lt;</> <replaceable>end</>, unless
6829
    <replaceable>start</> and <replaceable>end</> are equal in which case it
6830
    represents that single time instant.  This means for instance that two
6831
    time periods with only an endpoint in common do not overlap.
6832
   </para>
6833
6834
<screen>
6835
SELECT (DATE '2001-02-16', DATE '2001-12-21') OVERLAPS
6836
       (DATE '2001-10-30', DATE '2002-10-30');
6837
<lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
6838
SELECT (DATE '2001-02-16', INTERVAL '100 days') OVERLAPS
6839
       (DATE '2001-10-30', DATE '2002-10-30');
6840
<lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
6841
SELECT (DATE '2001-10-29', DATE '2001-10-30') OVERLAPS
6842
       (DATE '2001-10-30', DATE '2001-10-31');
6843
<lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
6844
SELECT (DATE '2001-10-30', DATE '2001-10-30') OVERLAPS
6845
       (DATE '2001-10-30', DATE '2001-10-31');
6846
<lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
6847
</screen>
6848
6849
  <para>
6850
   When adding an <type>interval</type> value to (or subtracting an
6851
   <type>interval</type> value from) a <type>timestamp with time zone</type>
6852
   value, the days component advances (or decrements) the date of the
6853
   <type>timestamp with time zone</type> by the indicated number of days.
6854
   Across daylight saving time changes (with the session time zone set to a
6855
   time zone that recognizes DST), this means <literal>interval '1 day'</literal>
6856
   does not necessarily equal <literal>interval '24 hours'</literal>.
6857
   For example, with the session time zone set to <literal>CST7CDT</literal>,
6858
   <literal>timestamp with time zone '2005-04-02 12:00-07' + interval '1 day' </literal>
6859
   will produce <literal>timestamp with time zone '2005-04-03 12:00-06'</literal>,
6860
   while adding <literal>interval '24 hours'</literal> to the same initial
6861
   <type>timestamp with time zone</type> produces
6862
   <literal>timestamp with time zone '2005-04-03 13:00-06'</literal>, as there is
6863
   a change in daylight saving time at <literal>2005-04-03 02:00</literal> in time zone
6864
   <literal>CST7CDT</literal>.
6865
  </para>
6866
6867
  <para>
6868
   Note there can be ambiguity in the <literal>months</> returned by
6869
   <function>age</> because different months have a different number of
6870
   days.  <productname>PostgreSQL</>'s approach uses the month from the
6871
   earlier of the two dates when calculating partial months.  For example,
6872
   <literal>age('2004-06-01', '2004-04-30')</> uses April to yield
6873
   <literal>1 mon 1 day</>, while using May would yield <literal>1 mon 2
6874
   days</> because May has 31 days, while April has only 30.
6875
  </para>
6876
6877
  <sect2 id="functions-datetime-extract">
6878
   <title><function>EXTRACT</function>, <function>date_part</function></title>
6879
6880
   <indexterm>
6881
    <primary>date_part</primary>
6882
   </indexterm>
6883
   <indexterm>
6884
    <primary>extract</primary>
6885
   </indexterm>
6886
6887
<synopsis>
6888
EXTRACT(<replaceable>field</replaceable> FROM <replaceable>source</replaceable>)
6889
</synopsis>
6890
6891
   <para>
6892
    The <function>extract</function> function retrieves subfields
6893
    such as year or hour from date/time values.
6894
    <replaceable>source</replaceable> must be a value expression of
6895
    type <type>timestamp</type>, <type>time</type>, or <type>interval</type>.
6896
    (Expressions of type <type>date</type> are
6897
    cast to <type>timestamp</type> and can therefore be used as
6898
    well.)  <replaceable>field</replaceable> is an identifier or
6899
    string that selects what field to extract from the source value.
6900
    The <function>extract</function> function returns values of type
6901
    <type>double precision</type>.
6902
    The following are valid field names:
6903
6904
    <!-- alphabetical -->
6905
    <variablelist>
6906
     <varlistentry>
6907
      <term><literal>century</literal></term>
6908
      <listitem>
6909
       <para>
6910
        The century
6911
       </para>
6912
6913
<screen>
6914
SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');
6915
<lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
6916
SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
6917
<lineannotation>Result: </lineannotation><computeroutput>21</computeroutput>
6918
</screen>
6919
6920
       <para>
6921
        The first century starts at 0001-01-01 00:00:00 AD, although
6922
        they did not know it at the time. This definition applies to all
6923
        Gregorian calendar countries. There is no century number 0,
6924
        you go from -1 century to 1 century.
6925
6926
        If you disagree with this, please write your complaint to:
6927
        Pope, Cathedral Saint-Peter of Roma, Vatican.
6928
       </para>
6929
6930
       <para>
6931
        <productname>PostgreSQL</productname> releases before 8.0 did not
6932
        follow the conventional numbering of centuries, but just returned
6933
        the year field divided by 100.
6934
       </para>
6935
      </listitem>
6936
     </varlistentry>
6937
6938
     <varlistentry>
6939
      <term><literal>day</literal></term>
6940
      <listitem>
6941
       <para>
6942
        For <type>timestamp</type> values, the day (of the month) field
6943
        (1 - 31) ; for <type>interval</type> values, the number of days
6944
       </para>
6945
6946
<screen>
6947
SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
6948
<lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
6949
6950
SELECT EXTRACT(DAY FROM INTERVAL '40 days 1 minute');
6951
<lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
6952
</screen>
6953
6954
6955
6956
      </listitem>
6957
     </varlistentry>
6958
6959
     <varlistentry>
6960
      <term><literal>decade</literal></term>
6961
      <listitem>
6962
       <para>
6963
        The year field divided by 10
6964
       </para>
6965
6966
<screen>
6967
SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
6968
<lineannotation>Result: </lineannotation><computeroutput>200</computeroutput>
6969
</screen>
6970
      </listitem>
6971
     </varlistentry>
6972
6973
     <varlistentry>
6974
      <term><literal>dow</literal></term>
6975
      <listitem>
6976
       <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
6977
        The day of the week as Sunday (<literal>0</>) to
6978
        Saturday (<literal>6</>)
1 by Martin Pitt
Import upstream version 9.3~beta1
6979
       </para>
6980
6981
<screen>
6982
SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
6983
<lineannotation>Result: </lineannotation><computeroutput>5</computeroutput>
6984
</screen>
6985
       <para>
6986
        Note that <function>extract</function>'s day of the week numbering
6987
        differs from that of the <function>to_char(...,
6988
        'D')</function> function.
6989
       </para>
6990
6991
      </listitem>
6992
     </varlistentry>
6993
6994
     <varlistentry>
6995
      <term><literal>doy</literal></term>
6996
      <listitem>
6997
       <para>
6998
        The day of the year (1 - 365/366)
6999
       </para>
7000
7001
<screen>
7002
SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
7003
<lineannotation>Result: </lineannotation><computeroutput>47</computeroutput>
7004
</screen>
7005
      </listitem>
7006
     </varlistentry>
7007
7008
     <varlistentry>
7009
      <term><literal>epoch</literal></term>
7010
      <listitem>
7011
       <para>
7012
        For <type>timestamp with time zone</type> values, the
7013
        number of seconds since 1970-01-01 00:00:00 UTC (can be negative);
7014
        for <type>date</type> and <type>timestamp</type> values, the
7015
        number of seconds since 1970-01-01 00:00:00 local time;
7016
        for <type>interval</type> values, the total number
7017
        of seconds in the interval
7018
       </para>
7019
7020
<screen>
7021
SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');
7022
<lineannotation>Result: </lineannotation><computeroutput>982384720.12</computeroutput>
7023
7024
SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
7025
<lineannotation>Result: </lineannotation><computeroutput>442800</computeroutput>
7026
</screen>
7027
7028
       <para>
7029
        Here is how you can convert an epoch value back to a time
7030
        stamp:
7031
       </para>
7032
<screen>
7033
SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 982384720.12 * INTERVAL '1 second';
7034
</screen>
7035
       <para>
7036
        (The <function>to_timestamp</> function encapsulates the above
7037
        conversion.)
7038
       </para>
7039
      </listitem>
7040
     </varlistentry>
7041
7042
     <varlistentry>
7043
      <term><literal>hour</literal></term>
7044
      <listitem>
7045
       <para>
7046
        The hour field (0 - 23)
7047
       </para>
7048
7049
<screen>
7050
SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
7051
<lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
7052
</screen>
7053
      </listitem>
7054
     </varlistentry>
7055
7056
     <varlistentry>
7057
      <term><literal>isodow</literal></term>
7058
      <listitem>
7059
       <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
7060
        The day of the week as Monday (<literal>1</>) to
7061
        Sunday (<literal>7</>)
1 by Martin Pitt
Import upstream version 9.3~beta1
7062
       </para>
7063
7064
<screen>
7065
SELECT EXTRACT(ISODOW FROM TIMESTAMP '2001-02-18 20:38:40');
7066
<lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
7067
</screen>
7068
       <para>
7069
        This is identical to <literal>dow</> except for Sunday.  This
7070
        matches the <acronym>ISO</> 8601 day of the week numbering.
7071
       </para>
7072
7073
      </listitem>
7074
     </varlistentry>
7075
7076
     <varlistentry>
7077
      <term><literal>isoyear</literal></term>
7078
      <listitem>
7079
       <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
7080
        The <acronym>ISO</acronym> 8601 week-numbering year that the date
7081
        falls in (not applicable to intervals)
1 by Martin Pitt
Import upstream version 9.3~beta1
7082
       </para>
7083
7084
<screen>
7085
SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-01');
7086
<lineannotation>Result: </lineannotation><computeroutput>2005</computeroutput>
7087
SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-02');
7088
<lineannotation>Result: </lineannotation><computeroutput>2006</computeroutput>
7089
</screen>
7090
7091
       <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
7092
        Each <acronym>ISO</acronym> 8601 week-numbering year begins with the
7093
        Monday of the week containing the 4th of January, so in early
7094
        January or late December the <acronym>ISO</acronym> year may be
7095
        different from the Gregorian year.  See the <literal>week</literal>
7096
        field for more information.
1 by Martin Pitt
Import upstream version 9.3~beta1
7097
       </para>
7098
       <para>
7099
        This field is not available in PostgreSQL releases prior to 8.3.
7100
       </para>
7101
      </listitem>
7102
     </varlistentry>
7103
7104
     <varlistentry>
7105
      <term><literal>microseconds</literal></term>
7106
      <listitem>
7107
       <para>
7108
        The seconds field, including fractional parts, multiplied by 1
7109
        000 000;  note that this includes full seconds
7110
       </para>
7111
7112
<screen>
7113
SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
7114
<lineannotation>Result: </lineannotation><computeroutput>28500000</computeroutput>
7115
</screen>
7116
      </listitem>
7117
     </varlistentry>
7118
7119
     <varlistentry>
7120
      <term><literal>millennium</literal></term>
7121
      <listitem>
7122
       <para>
7123
        The millennium
7124
       </para>
7125
7126
<screen>
7127
SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
7128
<lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
7129
</screen>
7130
7131
       <para>
7132
        Years in the 1900s are in the second millennium.
7133
        The third millennium started January 1, 2001.
7134
       </para>
7135
7136
       <para>
7137
        <productname>PostgreSQL</productname> releases before 8.0 did not
7138
        follow the conventional numbering of millennia, but just returned
7139
        the year field divided by 1000.
7140
       </para>
7141
      </listitem>
7142
     </varlistentry>
7143
7144
     <varlistentry>
7145
      <term><literal>milliseconds</literal></term>
7146
      <listitem>
7147
       <para>
7148
        The seconds field, including fractional parts, multiplied by
7149
        1000.  Note that this includes full seconds.
7150
       </para>
7151
7152
<screen>
7153
SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
7154
<lineannotation>Result: </lineannotation><computeroutput>28500</computeroutput>
7155
</screen>
7156
      </listitem>
7157
     </varlistentry>
7158
7159
     <varlistentry>
7160
      <term><literal>minute</literal></term>
7161
      <listitem>
7162
       <para>
7163
        The minutes field (0 - 59)
7164
       </para>
7165
7166
<screen>
7167
SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
7168
<lineannotation>Result: </lineannotation><computeroutput>38</computeroutput>
7169
</screen>
7170
      </listitem>
7171
     </varlistentry>
7172
7173
     <varlistentry>
7174
      <term><literal>month</literal></term>
7175
      <listitem>
7176
       <para>
7177
        For <type>timestamp</type> values, the number of the month
7178
        within the year (1 - 12) ; for <type>interval</type> values,
7179
        the number of months, modulo 12 (0 - 11)
7180
       </para>
7181
7182
<screen>
7183
SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
7184
<lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
7185
7186
SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
7187
<lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
7188
7189
SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
7190
<lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
7191
</screen>
7192
      </listitem>
7193
     </varlistentry>
7194
7195
     <varlistentry>
7196
      <term><literal>quarter</literal></term>
7197
      <listitem>
7198
       <para>
7199
        The quarter of the year (1 - 4) that the date is in
7200
       </para>
7201
7202
<screen>
7203
SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
7204
<lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
7205
</screen>
7206
      </listitem>
7207
     </varlistentry>
7208
7209
     <varlistentry>
7210
      <term><literal>second</literal></term>
7211
      <listitem>
7212
       <para>
7213
        The seconds field, including fractional parts (0 -
7214
        59<footnote><simpara>60 if leap seconds are
7215
        implemented by the operating system</simpara></footnote>)
7216
       </para>
7217
7218
<screen>
7219
SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
7220
<lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
7221
7222
SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
7223
<lineannotation>Result: </lineannotation><computeroutput>28.5</computeroutput>
7224
</screen>
7225
      </listitem>
7226
     </varlistentry>
7227
     <varlistentry>
7228
      <term><literal>timezone</literal></term>
7229
      <listitem>
7230
       <para>
7231
        The time zone offset from UTC, measured in seconds.  Positive values
7232
        correspond to time zones east of UTC, negative values to
7233
        zones west of UTC.  (Technically,
7234
        <productname>PostgreSQL</productname> uses <acronym>UT1</> because
7235
        leap seconds are not handled.)
7236
       </para>
7237
      </listitem>
7238
     </varlistentry>
7239
7240
     <varlistentry>
7241
      <term><literal>timezone_hour</literal></term>
7242
      <listitem>
7243
       <para>
7244
        The hour component of the time zone offset
7245
       </para>
7246
      </listitem>
7247
     </varlistentry>
7248
7249
     <varlistentry>
7250
      <term><literal>timezone_minute</literal></term>
7251
      <listitem>
7252
       <para>
7253
        The minute component of the time zone offset
7254
       </para>
7255
      </listitem>
7256
     </varlistentry>
7257
7258
     <varlistentry>
7259
      <term><literal>week</literal></term>
7260
      <listitem>
7261
       <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
7262
        The number of the <acronym>ISO</acronym> 8601 week-numbering week of
7263
        the year.  By definition, ISO weeks start on Mondays and the first
1 by Martin Pitt
Import upstream version 9.3~beta1
7264
        week of a year contains January 4 of that year.  In other words, the
7265
        first Thursday of a year is in week 1 of that year.
7266
       </para>
7267
       <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
7268
        In the ISO week-numbering system, it is possible for early-January
7269
        dates to be part of the 52nd or 53rd week of the previous year, and for
1 by Martin Pitt
Import upstream version 9.3~beta1
7270
        late-December dates to be part of the first week of the next year.
7271
        For example, <literal>2005-01-01</> is part of the 53rd week of year
7272
        2004, and <literal>2006-01-01</> is part of the 52nd week of year
7273
        2005, while <literal>2012-12-31</> is part of the first week of 2013.
7274
        It's recommended to use the <literal>isoyear</> field together with
7275
        <literal>week</> to get consistent results.
7276
       </para>
7277
7278
<screen>
7279
SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
7280
<lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
7281
</screen>
7282
      </listitem>
7283
     </varlistentry>
7284
7285
     <varlistentry>
7286
      <term><literal>year</literal></term>
7287
      <listitem>
7288
       <para>
7289
        The year field.  Keep in mind there is no <literal>0 AD</>, so subtracting
7290
        <literal>BC</> years from <literal>AD</> years should be done with care.
7291
       </para>
7292
7293
<screen>
7294
SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
7295
<lineannotation>Result: </lineannotation><computeroutput>2001</computeroutput>
7296
</screen>
7297
      </listitem>
7298
     </varlistentry>
7299
7300
    </variablelist>
7301
   </para>
7302
7303
   <para>
7304
    The <function>extract</function> function is primarily intended
7305
    for computational processing.  For formatting date/time values for
7306
    display, see <xref linkend="functions-formatting">.
7307
   </para>
7308
7309
   <para>
7310
    The <function>date_part</function> function is modeled on the traditional
7311
    <productname>Ingres</productname> equivalent to the
7312
    <acronym>SQL</acronym>-standard function <function>extract</function>:
7313
<synopsis>
7314
date_part('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
7315
</synopsis>
7316
    Note that here the <replaceable>field</replaceable> parameter needs to
7317
    be a string value, not a name.  The valid field names for
7318
    <function>date_part</function> are the same as for
7319
    <function>extract</function>.
7320
   </para>
7321
7322
<screen>
7323
SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
7324
<lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
7325
7326
SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
7327
<lineannotation>Result: </lineannotation><computeroutput>4</computeroutput>
7328
</screen>
7329
7330
  </sect2>
7331
7332
  <sect2 id="functions-datetime-trunc">
7333
   <title><function>date_trunc</function></title>
7334
7335
   <indexterm>
7336
    <primary>date_trunc</primary>
7337
   </indexterm>
7338
7339
   <para>
7340
    The function <function>date_trunc</function> is conceptually
7341
    similar to the <function>trunc</function> function for numbers.
7342
   </para>
7343
7344
   <para>
7345
<synopsis>
7346
date_trunc('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
7347
</synopsis>
7348
    <replaceable>source</replaceable> is a value expression of type
7349
    <type>timestamp</type> or <type>interval</>.
7350
    (Values of type <type>date</type> and
7351
    <type>time</type> are cast automatically to <type>timestamp</type> or
7352
    <type>interval</>, respectively.)
7353
    <replaceable>field</replaceable> selects to which precision to
7354
    truncate the input value.  The return value is of type
7355
    <type>timestamp</type> or <type>interval</>
7356
    with all fields that are less significant than the
7357
    selected one set to zero (or one, for day and month).
7358
   </para>
7359
7360
   <para>
7361
    Valid values for <replaceable>field</replaceable> are:
7362
    <simplelist>
7363
     <member><literal>microseconds</literal></member>
7364
     <member><literal>milliseconds</literal></member>
7365
     <member><literal>second</literal></member>
7366
     <member><literal>minute</literal></member>
7367
     <member><literal>hour</literal></member>
7368
     <member><literal>day</literal></member>
7369
     <member><literal>week</literal></member>
7370
     <member><literal>month</literal></member>
7371
     <member><literal>quarter</literal></member>
7372
     <member><literal>year</literal></member>
7373
     <member><literal>decade</literal></member>
7374
     <member><literal>century</literal></member>
7375
     <member><literal>millennium</literal></member>
7376
    </simplelist>
7377
   </para>
7378
7379
   <para>
7380
    Examples:
7381
<screen>
7382
SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
7383
<lineannotation>Result: </lineannotation><computeroutput>2001-02-16 20:00:00</computeroutput>
7384
7385
SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
7386
<lineannotation>Result: </lineannotation><computeroutput>2001-01-01 00:00:00</computeroutput>
7387
</screen>
7388
   </para>
7389
  </sect2>
7390
7391
  <sect2 id="functions-datetime-zoneconvert">
7392
   <title><literal>AT TIME ZONE</literal></title>
7393
7394
   <indexterm>
7395
    <primary>time zone</primary>
7396
    <secondary>conversion</secondary>
7397
   </indexterm>
7398
7399
   <indexterm>
7400
    <primary>AT TIME ZONE</primary>
7401
   </indexterm>
7402
7403
   <para>
7404
    The <literal>AT TIME ZONE</literal> construct allows conversions
7405
    of time stamps to different time zones.  <xref
7406
    linkend="functions-datetime-zoneconvert-table"> shows its
7407
    variants.
7408
   </para>
7409
7410
    <table id="functions-datetime-zoneconvert-table">
7411
     <title><literal>AT TIME ZONE</literal> Variants</title>
7412
     <tgroup cols="3">
7413
      <thead>
7414
       <row>
7415
        <entry>Expression</entry>
7416
        <entry>Return Type</entry>
7417
        <entry>Description</entry>
7418
       </row>
7419
      </thead>
7420
7421
      <tbody>
7422
       <row>
7423
        <entry>
7424
         <literal><type>timestamp without time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7425
        </entry>
7426
        <entry><type>timestamp with time zone</type></entry>
7427
        <entry>Treat given time stamp <emphasis>without time zone</> as located in the specified time zone</entry>
7428
       </row>
7429
7430
       <row>
7431
        <entry>
7432
         <literal><type>timestamp with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7433
        </entry>
7434
        <entry><type>timestamp without time zone</type></entry>
7435
        <entry>Convert given time stamp <emphasis>with time zone</> to the new time
7436
        zone, with no time zone designation</entry>
7437
       </row>
7438
7439
       <row>
7440
        <entry>
7441
         <literal><type>time with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
7442
        </entry>
7443
        <entry><type>time with time zone</type></entry>
7444
        <entry>Convert given time <emphasis>with time zone</> to the new time zone</entry>
7445
       </row>
7446
      </tbody>
7447
     </tgroup>
7448
    </table>
7449
7450
   <para>
7451
    In these expressions, the desired time zone <replaceable>zone</> can be
7452
    specified either as a text string (e.g., <literal>'PST'</literal>)
7453
    or as an interval (e.g., <literal>INTERVAL '-08:00'</literal>).
7454
    In the text case, a time zone name can be specified in any of the ways
7455
    described in <xref linkend="datatype-timezones">.
7456
   </para>
7457
7458
   <para>
7459
    Examples (assuming the local time zone is <literal>PST8PDT</>):
7460
<screen>
7461
SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'MST';
7462
<lineannotation>Result: </lineannotation><computeroutput>2001-02-16 19:38:40-08</computeroutput>
7463
7464
SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'MST';
7465
<lineannotation>Result: </lineannotation><computeroutput>2001-02-16 18:38:40</computeroutput>
7466
</screen>
7467
    The first example takes a time stamp without time zone and interprets it as MST time
7468
    (UTC-7), which is then converted to PST (UTC-8) for display.  The second example takes
7469
    a time stamp specified in EST (UTC-5) and converts it to local time in MST (UTC-7).
7470
   </para>
7471
7472
   <para>
7473
    The function <literal><function>timezone</function>(<replaceable>zone</>,
7474
    <replaceable>timestamp</>)</literal> is equivalent to the SQL-conforming construct
7475
    <literal><replaceable>timestamp</> AT TIME ZONE
7476
    <replaceable>zone</></literal>.
7477
   </para>
7478
  </sect2>
7479
7480
  <sect2 id="functions-datetime-current">
7481
   <title>Current Date/Time</title>
7482
7483
   <indexterm>
7484
    <primary>date</primary>
7485
    <secondary>current</secondary>
7486
   </indexterm>
7487
7488
   <indexterm>
7489
    <primary>time</primary>
7490
    <secondary>current</secondary>
7491
   </indexterm>
7492
7493
   <para>
7494
    <productname>PostgreSQL</productname> provides a number of functions
7495
    that return values related to the current date and time.  These
7496
    SQL-standard functions all return values based on the start time of
7497
    the current transaction:
7498
<synopsis>
7499
CURRENT_DATE
7500
CURRENT_TIME
7501
CURRENT_TIMESTAMP
7502
CURRENT_TIME(<replaceable>precision</replaceable>)
7503
CURRENT_TIMESTAMP(<replaceable>precision</replaceable>)
7504
LOCALTIME
7505
LOCALTIMESTAMP
7506
LOCALTIME(<replaceable>precision</replaceable>)
7507
LOCALTIMESTAMP(<replaceable>precision</replaceable>)
7508
</synopsis>
7509
    </para>
7510
7511
    <para>
7512
     <function>CURRENT_TIME</function> and
7513
     <function>CURRENT_TIMESTAMP</function> deliver values with time zone;
7514
     <function>LOCALTIME</function> and
7515
     <function>LOCALTIMESTAMP</function> deliver values without time zone.
7516
    </para>
7517
7518
    <para>
7519
     <function>CURRENT_TIME</function>,
7520
     <function>CURRENT_TIMESTAMP</function>,
7521
     <function>LOCALTIME</function>, and
7522
     <function>LOCALTIMESTAMP</function>
7523
     can optionally take
7524
     a precision parameter, which causes the result to be rounded
7525
     to that many fractional digits in the seconds field.  Without a precision parameter,
7526
     the result is given to the full available precision.
7527
    </para>
7528
7529
   <para>
7530
    Some examples:
7531
<screen>
7532
SELECT CURRENT_TIME;
7533
<lineannotation>Result: </lineannotation><computeroutput>14:39:53.662522-05</computeroutput>
7534
7535
SELECT CURRENT_DATE;
7536
<lineannotation>Result: </lineannotation><computeroutput>2001-12-23</computeroutput>
7537
7538
SELECT CURRENT_TIMESTAMP;
7539
<lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522-05</computeroutput>
7540
7541
SELECT CURRENT_TIMESTAMP(2);
7542
<lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.66-05</computeroutput>
7543
7544
SELECT LOCALTIMESTAMP;
7545
<lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522</computeroutput>
7546
</screen>
7547
   </para>
7548
7549
   <para>
7550
    Since these functions return
7551
    the start time of the current transaction, their values do not
7552
    change during the transaction. This is considered a feature:
7553
    the intent is to allow a single transaction to have a consistent
7554
    notion of the <quote>current</quote> time, so that multiple
7555
    modifications within the same transaction bear the same
7556
    time stamp.
7557
   </para>
7558
7559
   <note>
7560
    <para>
7561
     Other database systems might advance these values more
7562
     frequently.
7563
    </para>
7564
   </note>
7565
7566
   <para>
7567
    <productname>PostgreSQL</productname> also provides functions that
7568
    return the start time of the current statement, as well as the actual
7569
    current time at the instant the function is called.  The complete list
7570
    of non-SQL-standard time functions is:
7571
<synopsis>
7572
transaction_timestamp()
7573
statement_timestamp()
7574
clock_timestamp()
7575
timeofday()
7576
now()
7577
</synopsis>
7578
   </para>
7579
7580
   <para>
7581
    <function>transaction_timestamp()</> is equivalent to
7582
    <function>CURRENT_TIMESTAMP</function>, but is named to clearly reflect
7583
    what it returns.
7584
    <function>statement_timestamp()</> returns the start time of the current
7585
    statement (more specifically, the time of receipt of the latest command
7586
    message from the client).
7587
    <function>statement_timestamp()</> and <function>transaction_timestamp()</>
7588
    return the same value during the first command of a transaction, but might
7589
    differ during subsequent commands.
7590
    <function>clock_timestamp()</> returns the actual current time, and
7591
    therefore its value changes even within a single SQL command.
7592
    <function>timeofday()</> is a historical
7593
    <productname>PostgreSQL</productname> function.  Like
7594
    <function>clock_timestamp()</>, it returns the actual current time,
7595
    but as a formatted <type>text</> string rather than a <type>timestamp
7596
    with time zone</> value.
7597
    <function>now()</> is a traditional <productname>PostgreSQL</productname>
7598
    equivalent to <function>transaction_timestamp()</function>.
7599
   </para>
7600
7601
   <para>
7602
    All the date/time data types also accept the special literal value
7603
    <literal>now</literal> to specify the current date and time (again,
7604
    interpreted as the transaction start time).  Thus,
7605
    the following three all return the same result:
7606
<programlisting>
7607
SELECT CURRENT_TIMESTAMP;
7608
SELECT now();
7609
SELECT TIMESTAMP 'now';  -- incorrect for use with DEFAULT
7610
</programlisting>
7611
   </para>
7612
7613
    <tip>
7614
     <para>
7615
      You do not want to use the third form when specifying a <literal>DEFAULT</>
7616
      clause while creating a table.  The system will convert <literal>now</literal>
7617
      to a <type>timestamp</type> as soon as the constant is parsed, so that when
7618
      the default value is needed,
7619
      the time of the table creation would be used!  The first two
7620
      forms will not be evaluated until the default value is used,
7621
      because they are function calls.  Thus they will give the desired
7622
      behavior of defaulting to the time of row insertion.
7623
     </para>
7624
    </tip>
7625
  </sect2>
7626
7627
  <sect2 id="functions-datetime-delay">
7628
   <title>Delaying Execution</title>
7629
7630
   <indexterm>
7631
    <primary>pg_sleep</primary>
7632
   </indexterm>
7633
   <indexterm>
7634
    <primary>sleep</primary>
7635
   </indexterm>
7636
   <indexterm>
7637
    <primary>delay</primary>
7638
   </indexterm>
7639
7640
   <para>
7641
    The following function is available to delay execution of the server
7642
    process:
7643
<synopsis>
7644
pg_sleep(<replaceable>seconds</replaceable>)
7645
</synopsis>
7646
7647
    <function>pg_sleep</function> makes the current session's process
7648
    sleep until <replaceable>seconds</replaceable> seconds have
7649
    elapsed.  <replaceable>seconds</replaceable> is a value of type
7650
    <type>double precision</>, so fractional-second delays can be specified.
7651
    For example:
7652
7653
<programlisting>
7654
SELECT pg_sleep(1.5);
7655
</programlisting>
7656
   </para>
7657
7658
   <note>
7659
     <para>
7660
      The effective resolution of the sleep interval is platform-specific;
7661
      0.01 seconds is a common value.  The sleep delay will be at least as long
7662
      as specified. It might be longer depending on factors such as server load.
7663
     </para>
7664
   </note>
7665
7666
   <warning>
7667
     <para>
7668
      Make sure that your session does not hold more locks than necessary
7669
      when calling <function>pg_sleep</function>.  Otherwise other sessions
7670
      might have to wait for your sleeping process, slowing down the entire
7671
      system.
7672
     </para>
7673
   </warning>
7674
  </sect2>
7675
7676
 </sect1>
7677
7678
7679
 <sect1 id="functions-enum">
7680
  <title>Enum Support Functions</title>
7681
7682
  <para>
7683
   For enum types (described in <xref linkend="datatype-enum">),
7684
   there are several functions that allow cleaner programming without
7685
   hard-coding particular values of an enum type.
7686
   These are listed in <xref linkend="functions-enum-table">. The examples
7687
   assume an enum type created as:
7688
7689
<programlisting>
7690
CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'purple');
7691
</programlisting>
7692
7693
  </para>
7694
7695
  <table id="functions-enum-table">
7696
    <title>Enum Support Functions</title>
7697
    <tgroup cols="4">
7698
     <thead>
7699
      <row>
7700
       <entry>Function</entry>
7701
       <entry>Description</entry>
7702
       <entry>Example</entry>
7703
       <entry>Example Result</entry>
7704
      </row>
7705
     </thead>
7706
     <tbody>
7707
      <row>
7708
       <entry>
7709
         <indexterm>
7710
          <primary>enum_first</primary>
7711
         </indexterm>
7712
         <literal>enum_first(anyenum)</literal>
7713
       </entry>
7714
       <entry>Returns the first value of the input enum type</entry>
7715
       <entry><literal>enum_first(null::rainbow)</literal></entry>
7716
       <entry><literal>red</literal></entry>
7717
      </row>
7718
      <row>
7719
       <entry>
7720
         <indexterm>
7721
          <primary>enum_last</primary>
7722
         </indexterm>
7723
         <literal>enum_last(anyenum)</literal>
7724
       </entry>
7725
       <entry>Returns the last value of the input enum type</entry>
7726
       <entry><literal>enum_last(null::rainbow)</literal></entry>
7727
       <entry><literal>purple</literal></entry>
7728
      </row>
7729
      <row>
7730
       <entry>
7731
         <indexterm>
7732
          <primary>enum_range</primary>
7733
         </indexterm>
7734
         <literal>enum_range(anyenum)</literal>
7735
       </entry>
7736
       <entry>Returns all values of the input enum type in an ordered array</entry>
7737
       <entry><literal>enum_range(null::rainbow)</literal></entry>
7738
       <entry><literal>{red,orange,yellow,green,blue,purple}</literal></entry>
7739
      </row>
7740
      <row>
7741
       <entry morerows="2"><literal>enum_range(anyenum, anyenum)</literal></entry>
7742
       <entry morerows="2">
7743
        Returns the range between the two given enum values, as an ordered
7744
        array. The values must be from the same enum type. If the first
7745
        parameter is null, the result will start with the first value of
7746
        the enum type.
7747
        If the second parameter is null, the result will end with the last
7748
        value of the enum type.
7749
       </entry>
7750
       <entry><literal>enum_range('orange'::rainbow, 'green'::rainbow)</literal></entry>
7751
       <entry><literal>{orange,yellow,green}</literal></entry>
7752
      </row>
7753
      <row>
7754
       <entry><literal>enum_range(NULL, 'green'::rainbow)</literal></entry>
7755
       <entry><literal>{red,orange,yellow,green}</literal></entry>
7756
      </row>
7757
      <row>
7758
       <entry><literal>enum_range('orange'::rainbow, NULL)</literal></entry>
7759
       <entry><literal>{orange,yellow,green,blue,purple}</literal></entry>
7760
      </row>
7761
     </tbody>
7762
    </tgroup>
7763
   </table>
7764
7765
   <para>
7766
    Notice that except for the two-argument form of <function>enum_range</>,
7767
    these functions disregard the specific value passed to them; they care
7768
    only about its declared data type.  Either null or a specific value of
7769
    the type can be passed, with the same result.  It is more common to
7770
    apply these functions to a table column or function argument than to
7771
    a hardwired type name as suggested by the examples.
7772
   </para>
7773
 </sect1>
7774
7775
 <sect1 id="functions-geometry">
7776
  <title>Geometric Functions and Operators</title>
7777
7778
   <para>
7779
    The geometric types <type>point</type>, <type>box</type>,
7780
    <type>lseg</type>, <type>line</type>, <type>path</type>,
7781
    <type>polygon</type>, and <type>circle</type> have a large set of
7782
    native support functions and operators, shown in <xref
7783
    linkend="functions-geometry-op-table">, <xref
7784
    linkend="functions-geometry-func-table">, and <xref
7785
    linkend="functions-geometry-conv-table">.
7786
   </para>
7787
7788
   <caution>
7789
    <para>
7790
     Note that the <quote>same as</> operator, <literal>~=</>, represents
7791
     the usual notion of equality for the <type>point</type>,
7792
     <type>box</type>, <type>polygon</type>, and <type>circle</type> types.
7793
     Some of these types also have an <literal>=</> operator, but
7794
     <literal>=</> compares
7795
     for equal <emphasis>areas</> only.  The other scalar comparison operators
7796
     (<literal>&lt;=</> and so on) likewise compare areas for these types.
7797
    </para>
7798
   </caution>
7799
7800
   <table id="functions-geometry-op-table">
7801
     <title>Geometric Operators</title>
7802
     <tgroup cols="3">
7803
      <thead>
7804
       <row>
7805
        <entry>Operator</entry>
7806
        <entry>Description</entry>
7807
        <entry>Example</entry>
7808
       </row>
7809
      </thead>
7810
      <tbody>
7811
       <row>
7812
        <entry> <literal>+</literal> </entry>
7813
        <entry>Translation</entry>
7814
        <entry><literal>box '((0,0),(1,1))' + point '(2.0,0)'</literal></entry>
7815
       </row>
7816
       <row>
7817
        <entry> <literal>-</literal> </entry>
7818
        <entry>Translation</entry>
7819
        <entry><literal>box '((0,0),(1,1))' - point '(2.0,0)'</literal></entry>
7820
       </row>
7821
       <row>
7822
        <entry> <literal>*</literal> </entry>
7823
        <entry>Scaling/rotation</entry>
7824
        <entry><literal>box '((0,0),(1,1))' * point '(2.0,0)'</literal></entry>
7825
       </row>
7826
       <row>
7827
        <entry> <literal>/</literal> </entry>
7828
        <entry>Scaling/rotation</entry>
7829
        <entry><literal>box '((0,0),(2,2))' / point '(2.0,0)'</literal></entry>
7830
       </row>
7831
       <row>
7832
        <entry> <literal>#</literal> </entry>
7833
        <entry>Point or box of intersection</entry>
7834
        <entry><literal>'((1,-1),(-1,1))' # '((1,1),(-1,-1))'</literal></entry>
7835
       </row>
7836
       <row>
7837
        <entry> <literal>#</literal> </entry>
7838
        <entry>Number of points in path or polygon</entry>
7839
        <entry><literal># '((1,0),(0,1),(-1,0))'</literal></entry>
7840
       </row>
7841
       <row>
7842
        <entry> <literal>@-@</literal> </entry>
7843
        <entry>Length or circumference</entry>
7844
        <entry><literal>@-@ path '((0,0),(1,0))'</literal></entry>
7845
       </row>
7846
       <row>
7847
        <entry> <literal>@@</literal> </entry>
7848
        <entry>Center</entry>
7849
        <entry><literal>@@ circle '((0,0),10)'</literal></entry>
7850
       </row>
7851
       <row>
7852
        <entry> <literal>##</literal> </entry>
7853
        <entry>Closest point to first operand on second operand</entry>
7854
        <entry><literal>point '(0,0)' ## lseg '((2,0),(0,2))'</literal></entry>
7855
       </row>
7856
       <row>
7857
        <entry> <literal>&lt;-&gt;</literal> </entry>
7858
        <entry>Distance between</entry>
7859
        <entry><literal>circle '((0,0),1)' &lt;-&gt; circle '((5,0),1)'</literal></entry>
7860
       </row>
7861
       <row>
7862
        <entry> <literal>&amp;&amp;</literal> </entry>
7863
        <entry>Overlaps?  (One point in common makes this true.)</entry>
7864
        <entry><literal>box '((0,0),(1,1))' &amp;&amp; box '((0,0),(2,2))'</literal></entry>
7865
       </row>
7866
       <row>
7867
        <entry> <literal>&lt;&lt;</literal> </entry>
7868
        <entry>Is strictly left of?</entry>
7869
        <entry><literal>circle '((0,0),1)' &lt;&lt; circle '((5,0),1)'</literal></entry>
7870
       </row>
7871
       <row>
7872
        <entry> <literal>&gt;&gt;</literal> </entry>
7873
        <entry>Is strictly right of?</entry>
7874
        <entry><literal>circle '((5,0),1)' &gt;&gt; circle '((0,0),1)'</literal></entry>
7875
       </row>
7876
       <row>
7877
        <entry> <literal>&amp;&lt;</literal> </entry>
7878
        <entry>Does not extend to the right of?</entry>
7879
        <entry><literal>box '((0,0),(1,1))' &amp;&lt; box '((0,0),(2,2))'</literal></entry>
7880
       </row>
7881
       <row>
7882
        <entry> <literal>&amp;&gt;</literal> </entry>
7883
        <entry>Does not extend to the left of?</entry>
7884
        <entry><literal>box '((0,0),(3,3))' &amp;&gt; box '((0,0),(2,2))'</literal></entry>
7885
       </row>
7886
       <row>
7887
        <entry> <literal>&lt;&lt;|</literal> </entry>
7888
        <entry>Is strictly below?</entry>
7889
        <entry><literal>box '((0,0),(3,3))' &lt;&lt;| box '((3,4),(5,5))'</literal></entry>
7890
       </row>
7891
       <row>
7892
        <entry> <literal>|&gt;&gt;</literal> </entry>
7893
        <entry>Is strictly above?</entry>
7894
        <entry><literal>box '((3,4),(5,5))' |&gt;&gt; box '((0,0),(3,3))'</literal></entry>
7895
       </row>
7896
       <row>
7897
        <entry> <literal>&amp;&lt;|</literal> </entry>
7898
        <entry>Does not extend above?</entry>
7899
        <entry><literal>box '((0,0),(1,1))' &amp;&lt;| box '((0,0),(2,2))'</literal></entry>
7900
       </row>
7901
       <row>
7902
        <entry> <literal>|&amp;&gt;</literal> </entry>
7903
        <entry>Does not extend below?</entry>
7904
        <entry><literal>box '((0,0),(3,3))' |&amp;&gt; box '((0,0),(2,2))'</literal></entry>
7905
       </row>
7906
       <row>
7907
        <entry> <literal>&lt;^</literal> </entry>
7908
        <entry>Is below (allows touching)?</entry>
7909
        <entry><literal>circle '((0,0),1)' &lt;^ circle '((0,5),1)'</literal></entry>
7910
       </row>
7911
       <row>
7912
        <entry> <literal>&gt;^</literal> </entry>
7913
        <entry>Is above (allows touching)?</entry>
7914
        <entry><literal>circle '((0,5),1)' &gt;^ circle '((0,0),1)'</literal></entry>
7915
       </row>
7916
       <row>
7917
        <entry> <literal>?#</literal> </entry>
7918
        <entry>Intersects?</entry>
7919
        <entry><literal>lseg '((-1,0),(1,0))' ?# box '((-2,-2),(2,2))'</literal></entry>
7920
       </row>
7921
       <row>
7922
        <entry> <literal>?-</literal> </entry>
7923
        <entry>Is horizontal?</entry>
7924
        <entry><literal>?- lseg '((-1,0),(1,0))'</literal></entry>
7925
       </row>
7926
       <row>
7927
        <entry> <literal>?-</literal> </entry>
7928
        <entry>Are horizontally aligned?</entry>
7929
        <entry><literal>point '(1,0)' ?- point '(0,0)'</literal></entry>
7930
       </row>
7931
       <row>
7932
        <entry> <literal>?|</literal> </entry>
7933
        <entry>Is vertical?</entry>
7934
        <entry><literal>?| lseg '((-1,0),(1,0))'</literal></entry>
7935
       </row>
7936
       <row>
7937
        <entry> <literal>?|</literal> </entry>
7938
        <entry>Are vertically aligned?</entry>
7939
        <entry><literal>point '(0,1)' ?| point '(0,0)'</literal></entry>
7940
       </row>
7941
       <row>
7942
        <entry> <literal>?-|</literal> </entry>
7943
        <entry>Is perpendicular?</entry>
7944
        <entry><literal>lseg '((0,0),(0,1))' ?-| lseg '((0,0),(1,0))'</literal></entry>
7945
       </row>
7946
       <row>
7947
        <entry> <literal>?||</literal> </entry>
7948
        <entry>Are parallel?</entry>
7949
        <entry><literal>lseg '((-1,0),(1,0))' ?|| lseg '((-1,2),(1,2))'</literal></entry>
7950
       </row>
7951
       <row>
7952
        <entry> <literal>@&gt;</literal> </entry>
7953
        <entry>Contains?</entry>
7954
        <entry><literal>circle '((0,0),2)' @&gt; point '(1,1)'</literal></entry>
7955
       </row>
7956
       <row>
7957
        <entry> <literal>&lt;@</literal> </entry>
7958
        <entry>Contained in or on?</entry>
7959
        <entry><literal>point '(1,1)' &lt;@ circle '((0,0),2)'</literal></entry>
7960
       </row>
7961
       <row>
7962
        <entry> <literal>~=</literal> </entry>
7963
        <entry>Same as?</entry>
7964
        <entry><literal>polygon '((0,0),(1,1))' ~= polygon '((1,1),(0,0))'</literal></entry>
7965
       </row>
7966
      </tbody>
7967
     </tgroup>
7968
   </table>
7969
7970
   <note>
7971
    <para>
7972
     Before <productname>PostgreSQL</productname> 8.2, the containment
7973
     operators <literal>@&gt;</> and <literal>&lt;@</> were respectively
7974
     called <literal>~</> and <literal>@</>.  These names are still
7975
     available, but are deprecated and will eventually be removed.
7976
    </para>
7977
   </note>
7978
7979
   <indexterm>
7980
    <primary>area</primary>
7981
   </indexterm>
7982
   <indexterm>
7983
    <primary>center</primary>
7984
   </indexterm>
7985
   <indexterm>
7986
    <primary>diameter</primary>
7987
   </indexterm>
7988
   <indexterm>
7989
    <primary>height</primary>
7990
   </indexterm>
7991
   <indexterm>
7992
    <primary>isclosed</primary>
7993
   </indexterm>
7994
   <indexterm>
7995
    <primary>isopen</primary>
7996
   </indexterm>
7997
   <indexterm>
7998
    <primary>length</primary>
7999
   </indexterm>
8000
   <indexterm>
8001
    <primary>npoints</primary>
8002
   </indexterm>
8003
   <indexterm>
8004
    <primary>pclose</primary>
8005
   </indexterm>
8006
   <indexterm>
8007
    <primary>popen</primary>
8008
   </indexterm>
8009
   <indexterm>
8010
    <primary>radius</primary>
8011
   </indexterm>
8012
   <indexterm>
8013
    <primary>width</primary>
8014
   </indexterm>
8015
8016
   <table id="functions-geometry-func-table">
8017
     <title>Geometric Functions</title>
8018
     <tgroup cols="4">
8019
      <thead>
8020
       <row>
8021
        <entry>Function</entry>
8022
        <entry>Return Type</entry>
8023
        <entry>Description</entry>
8024
        <entry>Example</entry>
8025
       </row>
8026
      </thead>
8027
      <tbody>
8028
       <row>
8029
        <entry><literal><function>area(<replaceable>object</>)</function></literal></entry>
8030
        <entry><type>double precision</type></entry>
8031
        <entry>area</entry>
8032
        <entry><literal>area(box '((0,0),(1,1))')</literal></entry>
8033
       </row>
8034
       <row>
8035
        <entry><literal><function>center(<replaceable>object</>)</function></literal></entry>
8036
        <entry><type>point</type></entry>
8037
        <entry>center</entry>
8038
        <entry><literal>center(box '((0,0),(1,2))')</literal></entry>
8039
       </row>
8040
       <row>
8041
        <entry><literal><function>diameter(<type>circle</>)</function></literal></entry>
8042
        <entry><type>double precision</type></entry>
8043
        <entry>diameter of circle</entry>
8044
        <entry><literal>diameter(circle '((0,0),2.0)')</literal></entry>
8045
       </row>
8046
       <row>
8047
        <entry><literal><function>height(<type>box</>)</function></literal></entry>
8048
        <entry><type>double precision</type></entry>
8049
        <entry>vertical size of box</entry>
8050
        <entry><literal>height(box '((0,0),(1,1))')</literal></entry>
8051
       </row>
8052
       <row>
8053
        <entry><literal><function>isclosed(<type>path</>)</function></literal></entry>
8054
        <entry><type>boolean</type></entry>
8055
        <entry>a closed path?</entry>
8056
        <entry><literal>isclosed(path '((0,0),(1,1),(2,0))')</literal></entry>
8057
       </row>
8058
       <row>
8059
        <entry><literal><function>isopen(<type>path</>)</function></literal></entry>
8060
        <entry><type>boolean</type></entry>
8061
        <entry>an open path?</entry>
8062
        <entry><literal>isopen(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8063
       </row>
8064
       <row>
8065
        <entry><literal><function>length(<replaceable>object</>)</function></literal></entry>
8066
        <entry><type>double precision</type></entry>
8067
        <entry>length</entry>
8068
        <entry><literal>length(path '((-1,0),(1,0))')</literal></entry>
8069
       </row>
8070
       <row>
8071
        <entry><literal><function>npoints(<type>path</>)</function></literal></entry>
8072
        <entry><type>int</type></entry>
8073
        <entry>number of points</entry>
8074
        <entry><literal>npoints(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8075
       </row>
8076
       <row>
8077
        <entry><literal><function>npoints(<type>polygon</>)</function></literal></entry>
8078
        <entry><type>int</type></entry>
8079
        <entry>number of points</entry>
8080
        <entry><literal>npoints(polygon '((1,1),(0,0))')</literal></entry>
8081
       </row>
8082
       <row>
8083
        <entry><literal><function>pclose(<type>path</>)</function></literal></entry>
8084
        <entry><type>path</type></entry>
8085
        <entry>convert path to closed</entry>
8086
        <entry><literal>pclose(path '[(0,0),(1,1),(2,0)]')</literal></entry>
8087
       </row>
8088
<![IGNORE[
8089
<!-- Not defined by this name. Implements the intersection operator '#' -->
8090
       <row>
8091
        <entry><literal><function>point(<type>lseg</>, <type>lseg</>)</function></literal></entry>
8092
        <entry><type>point</type></entry>
8093
        <entry>intersection</entry>
8094
        <entry><literal>point(lseg '((-1,0),(1,0))',lseg '((-2,-2),(2,2))')</literal></entry>
8095
       </row>
8096
]]>
8097
       <row>
8098
        <entry><literal><function>popen(<type>path</>)</function></literal></entry>
8099
        <entry><type>path</type></entry>
8100
        <entry>convert path to open</entry>
8101
        <entry><literal>popen(path '((0,0),(1,1),(2,0))')</literal></entry>
8102
       </row>
8103
       <row>
8104
        <entry><literal><function>radius(<type>circle</type>)</function></literal></entry>
8105
        <entry><type>double precision</type></entry>
8106
        <entry>radius of circle</entry>
8107
        <entry><literal>radius(circle '((0,0),2.0)')</literal></entry>
8108
       </row>
8109
       <row>
8110
        <entry><literal><function>width(<type>box</>)</function></literal></entry>
8111
        <entry><type>double precision</type></entry>
8112
        <entry>horizontal size of box</entry>
8113
        <entry><literal>width(box '((0,0),(1,1))')</literal></entry>
8114
       </row>
8115
      </tbody>
8116
     </tgroup>
8117
   </table>
8118
8119
   <table id="functions-geometry-conv-table">
8120
     <title>Geometric Type Conversion Functions</title>
8121
     <tgroup cols="4">
8122
      <thead>
8123
       <row>
8124
        <entry>Function</entry>
8125
        <entry>Return Type</entry>
8126
        <entry>Description</entry>
8127
        <entry>Example</entry>
8128
       </row>
8129
      </thead>
8130
      <tbody>
8131
       <row>
8132
        <entry>
8133
         <indexterm>
8134
          <primary>box</primary>
8135
         </indexterm>
8136
         <literal><function>box(<type>circle</type>)</function></literal>
8137
        </entry>
8138
        <entry><type>box</type></entry>
8139
        <entry>circle to box</entry>
8140
        <entry><literal>box(circle '((0,0),2.0)')</literal></entry>
8141
       </row>
8142
       <row>
8143
        <entry><literal><function>box(<type>point</type>, <type>point</type>)</function></literal></entry>
8144
        <entry><type>box</type></entry>
8145
        <entry>points to box</entry>
8146
        <entry><literal>box(point '(0,0)', point '(1,1)')</literal></entry>
8147
       </row>
8148
       <row>
8149
        <entry><literal><function>box(<type>polygon</type>)</function></literal></entry>
8150
        <entry><type>box</type></entry>
8151
        <entry>polygon to box</entry>
8152
        <entry><literal>box(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8153
       </row>
8154
       <row>
8155
        <entry>
8156
         <indexterm>
8157
          <primary>circle</primary>
8158
         </indexterm>
8159
         <literal><function>circle(<type>box</type>)</function></literal>
8160
        </entry>
8161
        <entry><type>circle</type></entry>
8162
        <entry>box to circle</entry>
8163
        <entry><literal>circle(box '((0,0),(1,1))')</literal></entry>
8164
       </row>
8165
       <row>
8166
        <entry><literal><function>circle(<type>point</type>, <type>double precision</type>)</function></literal></entry>
8167
        <entry><type>circle</type></entry>
8168
        <entry>center and radius to circle</entry>
8169
        <entry><literal>circle(point '(0,0)', 2.0)</literal></entry>
8170
       </row>
8171
       <row>
8172
        <entry><literal><function>circle(<type>polygon</type>)</function></literal></entry>
8173
        <entry><type>circle</type></entry>
8174
        <entry>polygon to circle</entry>
8175
        <entry><literal>circle(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8176
       </row>
8177
       <row>
8178
        <entry>
8179
         <indexterm>
8180
          <primary>lseg</primary>
8181
         </indexterm>
8182
         <literal><function>lseg(<type>box</type>)</function></literal>
8183
        </entry>
8184
        <entry><type>lseg</type></entry>
8185
        <entry>box diagonal to line segment</entry>
8186
        <entry><literal>lseg(box '((-1,0),(1,0))')</literal></entry>
8187
       </row>
8188
       <row>
8189
        <entry><literal><function>lseg(<type>point</type>, <type>point</type>)</function></literal></entry>
8190
        <entry><type>lseg</type></entry>
8191
        <entry>points to line segment</entry>
8192
        <entry><literal>lseg(point '(-1,0)', point '(1,0)')</literal></entry>
8193
       </row>
8194
       <row>
8195
        <entry>
8196
         <indexterm>
8197
          <primary>path</primary>
8198
         </indexterm>
8199
         <literal><function>path(<type>polygon</type>)</function></literal>
8200
        </entry>
8201
        <entry><type>path</type></entry>
8202
        <entry>polygon to path</entry>
8203
        <entry><literal>path(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8204
       </row>
8205
       <row>
8206
        <entry>
8207
         <indexterm>
8208
          <primary>point</primary>
8209
         </indexterm>
8210
         <literal><function>point</function>(<type>double
8211
         precision</type>, <type>double precision</type>)</literal>
8212
        </entry>
8213
        <entry><type>point</type></entry>
8214
        <entry>construct point</entry>
8215
        <entry><literal>point(23.4, -44.5)</literal></entry>
8216
       </row>
8217
       <row>
8218
        <entry><literal><function>point(<type>box</type>)</function></literal></entry>
8219
        <entry><type>point</type></entry>
8220
        <entry>center of box</entry>
8221
        <entry><literal>point(box '((-1,0),(1,0))')</literal></entry>
8222
       </row>
8223
       <row>
8224
        <entry><literal><function>point(<type>circle</type>)</function></literal></entry>
8225
        <entry><type>point</type></entry>
8226
        <entry>center of circle</entry>
8227
        <entry><literal>point(circle '((0,0),2.0)')</literal></entry>
8228
       </row>
8229
       <row>
8230
        <entry><literal><function>point(<type>lseg</type>)</function></literal></entry>
8231
        <entry><type>point</type></entry>
8232
        <entry>center of line segment</entry>
8233
        <entry><literal>point(lseg '((-1,0),(1,0))')</literal></entry>
8234
       </row>
8235
       <row>
8236
        <entry><literal><function>point(<type>polygon</type>)</function></literal></entry>
8237
        <entry><type>point</type></entry>
8238
        <entry>center of polygon</entry>
8239
        <entry><literal>point(polygon '((0,0),(1,1),(2,0))')</literal></entry>
8240
       </row>
8241
       <row>
8242
        <entry>
8243
         <indexterm>
8244
          <primary>polygon</primary>
8245
         </indexterm>
8246
         <literal><function>polygon(<type>box</type>)</function></literal>
8247
        </entry>
8248
        <entry><type>polygon</type></entry>
8249
        <entry>box to 4-point polygon</entry>
8250
        <entry><literal>polygon(box '((0,0),(1,1))')</literal></entry>
8251
       </row>
8252
       <row>
8253
        <entry><literal><function>polygon(<type>circle</type>)</function></literal></entry>
8254
        <entry><type>polygon</type></entry>
8255
        <entry>circle to 12-point polygon</entry>
8256
        <entry><literal>polygon(circle '((0,0),2.0)')</literal></entry>
8257
       </row>
8258
       <row>
8259
        <entry><literal><function>polygon(<replaceable class="parameter">npts</replaceable>, <type>circle</type>)</function></literal></entry>
8260
        <entry><type>polygon</type></entry>
8261
        <entry>circle to <replaceable class="parameter">npts</replaceable>-point polygon</entry>
8262
        <entry><literal>polygon(12, circle '((0,0),2.0)')</literal></entry>
8263
       </row>
8264
       <row>
8265
        <entry><literal><function>polygon(<type>path</type>)</function></literal></entry>
8266
        <entry><type>polygon</type></entry>
8267
        <entry>path to polygon</entry>
8268
        <entry><literal>polygon(path '((0,0),(1,1),(2,0))')</literal></entry>
8269
       </row>
8270
      </tbody>
8271
     </tgroup>
8272
   </table>
8273
8274
    <para>
8275
     It is possible to access the two component numbers of a <type>point</>
8276
     as though the point were an array with indexes 0 and 1.  For example, if
8277
     <literal>t.p</> is a <type>point</> column then
8278
     <literal>SELECT p[0] FROM t</> retrieves the X coordinate and
8279
     <literal>UPDATE t SET p[1] = ...</> changes the Y coordinate.
8280
     In the same way, a value of type <type>box</> or <type>lseg</> can be treated
8281
     as an array of two <type>point</> values.
8282
    </para>
8283
8284
    <para>
8285
     The <function>area</function> function works for the types
8286
     <type>box</type>, <type>circle</type>, and <type>path</type>.
8287
     The <function>area</function> function only works on the
8288
     <type>path</type> data type if the points in the
8289
     <type>path</type> are non-intersecting.  For example, the
8290
     <type>path</type>
8291
     <literal>'((0,0),(0,1),(2,1),(2,2),(1,2),(1,0),(0,0))'::PATH</literal>
8292
     will not work;  however, the following visually identical
8293
     <type>path</type>
8294
     <literal>'((0,0),(0,1),(1,1),(1,2),(2,2),(2,1),(1,1),(1,0),(0,0))'::PATH</literal>
8295
     will work.  If the concept of an intersecting versus
8296
     non-intersecting <type>path</type> is confusing, draw both of the
8297
     above <type>path</type>s side by side on a piece of graph paper.
8298
    </para>
8299
8300
  </sect1>
8301
8302
8303
 <sect1 id="functions-net">
8304
  <title>Network Address Functions and Operators</title>
8305
8306
  <para>
8307
   <xref linkend="cidr-inet-operators-table"> shows the operators
8308
   available for the <type>cidr</type> and <type>inet</type> types.
8309
   The operators <literal>&lt;&lt;</literal>,
8310
   <literal>&lt;&lt;=</literal>, <literal>&gt;&gt;</literal>, and
8311
   <literal>&gt;&gt;=</literal> test for subnet inclusion.  They
8312
   consider only the network parts of the two addresses (ignoring any
8313
   host part) and determine whether one network is identical to
8314
   or a subnet of the other.
8315
  </para>
8316
8317
    <table id="cidr-inet-operators-table">
8318
     <title><type>cidr</type> and <type>inet</type> Operators</title>
8319
     <tgroup cols="3">
8320
      <thead>
8321
       <row>
8322
        <entry>Operator</entry>
8323
        <entry>Description</entry>
8324
        <entry>Example</entry>
8325
       </row>
8326
      </thead>
8327
      <tbody>
8328
       <row>
8329
        <entry> <literal>&lt;</literal> </entry>
8330
        <entry>is less than</entry>
8331
        <entry><literal>inet '192.168.1.5' &lt; inet '192.168.1.6'</literal></entry>
8332
       </row>
8333
       <row>
8334
        <entry> <literal>&lt;=</literal> </entry>
8335
        <entry>is less than or equal</entry>
8336
        <entry><literal>inet '192.168.1.5' &lt;= inet '192.168.1.5'</literal></entry>
8337
       </row>
8338
       <row>
8339
        <entry> <literal>=</literal> </entry>
8340
        <entry>equals</entry>
8341
        <entry><literal>inet '192.168.1.5' = inet '192.168.1.5'</literal></entry>
8342
       </row>
8343
       <row>
8344
        <entry> <literal>&gt;=</literal> </entry>
8345
        <entry>is greater or equal</entry>
8346
        <entry><literal>inet '192.168.1.5' &gt;= inet '192.168.1.5'</literal></entry>
8347
       </row>
8348
       <row>
8349
        <entry> <literal>&gt;</literal> </entry>
8350
        <entry>is greater than</entry>
8351
        <entry><literal>inet '192.168.1.5' &gt; inet '192.168.1.4'</literal></entry>
8352
       </row>
8353
       <row>
8354
        <entry> <literal>&lt;&gt;</literal> </entry>
8355
        <entry>is not equal</entry>
8356
        <entry><literal>inet '192.168.1.5' &lt;&gt; inet '192.168.1.4'</literal></entry>
8357
       </row>
8358
       <row>
8359
        <entry> <literal>&lt;&lt;</literal> </entry>
8360
        <entry>is contained within</entry>
8361
        <entry><literal>inet '192.168.1.5' &lt;&lt; inet '192.168.1/24'</literal></entry>
8362
       </row>
8363
       <row>
8364
        <entry> <literal>&lt;&lt;=</literal> </entry>
8365
        <entry>is contained within or equals</entry>
8366
        <entry><literal>inet '192.168.1/24' &lt;&lt;= inet '192.168.1/24'</literal></entry>
8367
       </row>
8368
       <row>
8369
        <entry> <literal>&gt;&gt;</literal> </entry>
8370
        <entry>contains</entry>
8371
        <entry><literal>inet '192.168.1/24' &gt;&gt; inet '192.168.1.5'</literal></entry>
8372
       </row>
8373
       <row>
8374
        <entry> <literal>&gt;&gt;=</literal> </entry>
8375
        <entry>contains or equals</entry>
8376
        <entry><literal>inet '192.168.1/24' &gt;&gt;= inet '192.168.1/24'</literal></entry>
8377
       </row>
8378
       <row>
8379
        <entry> <literal>~</literal> </entry>
8380
        <entry>bitwise NOT</entry>
8381
        <entry><literal>~ inet '192.168.1.6'</literal></entry>
8382
       </row>
8383
       <row>
8384
        <entry> <literal>&amp;</literal> </entry>
8385
        <entry>bitwise AND</entry>
8386
        <entry><literal>inet '192.168.1.6' &amp; inet '0.0.0.255'</literal></entry>
8387
       </row>
8388
       <row>
8389
        <entry> <literal>|</literal> </entry>
8390
        <entry>bitwise OR</entry>
8391
        <entry><literal>inet '192.168.1.6' | inet '0.0.0.255'</literal></entry>
8392
       </row>
8393
       <row>
8394
        <entry> <literal>+</literal> </entry>
8395
        <entry>addition</entry>
8396
        <entry><literal>inet '192.168.1.6' + 25</literal></entry>
8397
       </row>
8398
       <row>
8399
        <entry> <literal>-</literal> </entry>
8400
        <entry>subtraction</entry>
8401
        <entry><literal>inet '192.168.1.43' - 36</literal></entry>
8402
       </row>
8403
       <row>
8404
        <entry> <literal>-</literal> </entry>
8405
        <entry>subtraction</entry>
8406
        <entry><literal>inet '192.168.1.43' - inet '192.168.1.19'</literal></entry>
8407
       </row>
8408
      </tbody>
8409
     </tgroup>
8410
    </table>
8411
8412
  <para>
8413
   <xref linkend="cidr-inet-functions-table"> shows the functions
8414
   available for use with the <type>cidr</type> and <type>inet</type>
8415
   types.  The <function>abbrev</function>, <function>host</function>,
8416
   and <function>text</function>
8417
   functions are primarily intended to offer alternative display
8418
   formats.
8419
  </para>
8420
8421
    <table id="cidr-inet-functions-table">
8422
     <title><type>cidr</type> and <type>inet</type> Functions</title>
8423
     <tgroup cols="5">
8424
      <thead>
8425
       <row>
8426
        <entry>Function</entry>
8427
        <entry>Return Type</entry>
8428
        <entry>Description</entry>
8429
        <entry>Example</entry>
8430
        <entry>Result</entry>
8431
       </row>
8432
      </thead>
8433
      <tbody>
8434
       <row>
8435
        <entry>
8436
         <indexterm>
8437
          <primary>abbrev</primary>
8438
         </indexterm>
8439
         <literal><function>abbrev(<type>inet</type>)</function></literal>
8440
        </entry>
8441
        <entry><type>text</type></entry>
8442
        <entry>abbreviated display format as text</entry>
8443
        <entry><literal>abbrev(inet '10.1.0.0/16')</literal></entry>
8444
        <entry><literal>10.1.0.0/16</literal></entry>
8445
       </row>
8446
       <row>
8447
        <entry><literal><function>abbrev(<type>cidr</type>)</function></literal></entry>
8448
        <entry><type>text</type></entry>
8449
        <entry>abbreviated display format as text</entry>
8450
        <entry><literal>abbrev(cidr '10.1.0.0/16')</literal></entry>
8451
        <entry><literal>10.1/16</literal></entry>
8452
       </row>
8453
       <row>
8454
        <entry>
8455
         <indexterm>
8456
          <primary>broadcast</primary>
8457
         </indexterm>
8458
         <literal><function>broadcast(<type>inet</type>)</function></literal>
8459
        </entry>
8460
        <entry><type>inet</type></entry>
8461
        <entry>broadcast address for network</entry>
8462
        <entry><literal>broadcast('192.168.1.5/24')</literal></entry>
8463
        <entry><literal>192.168.1.255/24</literal></entry>
8464
       </row>
8465
       <row>
8466
        <entry>
8467
         <indexterm>
8468
          <primary>family</primary>
8469
         </indexterm>
8470
         <literal><function>family(<type>inet</type>)</function></literal>
8471
        </entry>
8472
        <entry><type>int</type></entry>
8473
        <entry>extract family of address; <literal>4</literal> for IPv4,
8474
         <literal>6</literal> for IPv6</entry>
8475
        <entry><literal>family('::1')</literal></entry>
8476
        <entry><literal>6</literal></entry>
8477
       </row>
8478
       <row>
8479
        <entry>
8480
         <indexterm>
8481
          <primary>host</primary>
8482
         </indexterm>
8483
         <literal><function>host(<type>inet</type>)</function></literal>
8484
        </entry>
8485
        <entry><type>text</type></entry>
8486
        <entry>extract IP address as text</entry>
8487
        <entry><literal>host('192.168.1.5/24')</literal></entry>
8488
        <entry><literal>192.168.1.5</literal></entry>
8489
       </row>
8490
       <row>
8491
        <entry>
8492
         <indexterm>
8493
          <primary>hostmask</primary>
8494
         </indexterm>
8495
         <literal><function>hostmask(<type>inet</type>)</function></literal>
8496
        </entry>
8497
        <entry><type>inet</type></entry>
8498
        <entry>construct host mask for network</entry>
8499
        <entry><literal>hostmask('192.168.23.20/30')</literal></entry>
8500
        <entry><literal>0.0.0.3</literal></entry>
8501
       </row>
8502
       <row>
8503
        <entry>
8504
         <indexterm>
8505
          <primary>masklen</primary>
8506
         </indexterm>
8507
         <literal><function>masklen(<type>inet</type>)</function></literal>
8508
        </entry>
8509
        <entry><type>int</type></entry>
8510
        <entry>extract netmask length</entry>
8511
        <entry><literal>masklen('192.168.1.5/24')</literal></entry>
8512
        <entry><literal>24</literal></entry>
8513
       </row>
8514
       <row>
8515
        <entry>
8516
         <indexterm>
8517
          <primary>netmask</primary>
8518
         </indexterm>
8519
         <literal><function>netmask(<type>inet</type>)</function></literal>
8520
        </entry>
8521
        <entry><type>inet</type></entry>
8522
        <entry>construct netmask for network</entry>
8523
        <entry><literal>netmask('192.168.1.5/24')</literal></entry>
8524
        <entry><literal>255.255.255.0</literal></entry>
8525
       </row>
8526
       <row>
8527
        <entry>
8528
         <indexterm>
8529
          <primary>network</primary>
8530
         </indexterm>
8531
         <literal><function>network(<type>inet</type>)</function></literal>
8532
        </entry>
8533
        <entry><type>cidr</type></entry>
8534
        <entry>extract network part of address</entry>
8535
        <entry><literal>network('192.168.1.5/24')</literal></entry>
8536
        <entry><literal>192.168.1.0/24</literal></entry>
8537
       </row>
8538
       <row>
8539
        <entry>
8540
         <indexterm>
8541
          <primary>set_masklen</primary>
8542
         </indexterm>
8543
         <literal><function>set_masklen(<type>inet</type>, <type>int</type>)</function></literal>
8544
        </entry>
8545
        <entry><type>inet</type></entry>
8546
        <entry>set netmask length for <type>inet</type> value</entry>
8547
        <entry><literal>set_masklen('192.168.1.5/24', 16)</literal></entry>
8548
        <entry><literal>192.168.1.5/16</literal></entry>
8549
       </row>
8550
       <row>
8551
        <entry><literal><function>set_masklen(<type>cidr</type>, <type>int</type>)</function></literal></entry>
8552
        <entry><type>cidr</type></entry>
8553
        <entry>set netmask length for <type>cidr</type> value</entry>
8554
        <entry><literal>set_masklen('192.168.1.0/24'::cidr, 16)</literal></entry>
8555
        <entry><literal>192.168.0.0/16</literal></entry>
8556
       </row>
8557
       <row>
8558
        <entry>
8559
         <indexterm>
8560
          <primary>text</primary>
8561
         </indexterm>
8562
         <literal><function>text(<type>inet</type>)</function></literal>
8563
        </entry>
8564
        <entry><type>text</type></entry>
8565
        <entry>extract IP address and netmask length as text</entry>
8566
        <entry><literal>text(inet '192.168.1.5')</literal></entry>
8567
        <entry><literal>192.168.1.5/32</literal></entry>
8568
       </row>
8569
      </tbody>
8570
     </tgroup>
8571
    </table>
8572
8573
  <para>
8574
   Any <type>cidr</> value can be cast to <type>inet</> implicitly
8575
   or explicitly; therefore, the functions shown above as operating on
8576
   <type>inet</> also work on <type>cidr</> values.  (Where there are
8577
   separate functions for <type>inet</> and <type>cidr</>, it is because
8578
   the behavior should be different for the two cases.)
8579
   Also, it is permitted to cast an <type>inet</> value to <type>cidr</>.
8580
   When this is done, any bits to the right of the netmask are silently zeroed
8581
   to create a valid <type>cidr</> value.
8582
   In addition,
8583
   you can cast a text value to <type>inet</> or <type>cidr</>
8584
   using normal casting syntax: for example,
8585
   <literal>inet(<replaceable>expression</>)</literal> or
8586
   <literal><replaceable>colname</>::cidr</literal>.
8587
  </para>
8588
8589
  <para>
8590
   <xref linkend="macaddr-functions-table"> shows the functions
8591
   available for use with the <type>macaddr</type> type.  The function
8592
   <literal><function>trunc(<type>macaddr</type>)</function></literal> returns a MAC
8593
   address with the last 3 bytes set to zero.  This can be used to
8594
   associate the remaining prefix with a manufacturer.
8595
  </para>
8596
8597
    <table id="macaddr-functions-table">
8598
     <title><type>macaddr</type> Functions</title>
8599
     <tgroup cols="5">
8600
      <thead>
8601
       <row>
8602
        <entry>Function</entry>
8603
        <entry>Return Type</entry>
8604
        <entry>Description</entry>
8605
        <entry>Example</entry>
8606
        <entry>Result</entry>
8607
       </row>
8608
      </thead>
8609
      <tbody>
8610
       <row>
8611
        <entry>
8612
         <indexterm>
8613
          <primary>trunc</primary>
8614
         </indexterm>
8615
         <literal><function>trunc(<type>macaddr</type>)</function></literal>
8616
        </entry>
8617
        <entry><type>macaddr</type></entry>
8618
        <entry>set last 3 bytes to zero</entry>
8619
        <entry><literal>trunc(macaddr '12:34:56:78:90:ab')</literal></entry>
8620
        <entry><literal>12:34:56:00:00:00</literal></entry>
8621
       </row>
8622
      </tbody>
8623
     </tgroup>
8624
    </table>
8625
8626
   <para>
8627
    The <type>macaddr</type> type also supports the standard relational
8628
    operators (<literal>&gt;</literal>, <literal>&lt;=</literal>, etc.) for
8629
    lexicographical ordering, and the bitwise arithmetic operators
8630
    (<literal>~</literal>, <literal>&amp;</literal> and <literal>|</literal>)
8631
    for NOT, AND and OR.
8632
   </para>
8633
8634
  </sect1>
8635
8636
8637
 <sect1 id="functions-textsearch">
8638
  <title>Text Search Functions and Operators</title>
8639
8640
   <indexterm zone="datatype-textsearch">
8641
    <primary>full text search</primary>
8642
    <secondary>functions and operators</secondary>
8643
   </indexterm>
8644
8645
   <indexterm zone="datatype-textsearch">
8646
    <primary>text search</primary>
8647
    <secondary>functions and operators</secondary>
8648
   </indexterm>
8649
8650
  <para>
8651
   <xref linkend="textsearch-operators-table">,
8652
   <xref linkend="textsearch-functions-table"> and
8653
   <xref linkend="textsearch-functions-debug-table">
8654
   summarize the functions and operators that are provided
8655
   for full text searching.  See <xref linkend="textsearch"> for a detailed
8656
   explanation of <productname>PostgreSQL</productname>'s text search
8657
   facility.
8658
  </para>
8659
8660
    <table id="textsearch-operators-table">
8661
     <title>Text Search Operators</title>
8662
     <tgroup cols="4">
8663
      <thead>
8664
       <row>
8665
        <entry>Operator</entry>
8666
        <entry>Description</entry>
8667
        <entry>Example</entry>
8668
        <entry>Result</entry>
8669
       </row>
8670
      </thead>
8671
      <tbody>
8672
       <row>
8673
        <entry> <literal>@@</literal> </entry>
8674
        <entry><type>tsvector</> matches <type>tsquery</> ?</entry>
8675
        <entry><literal>to_tsvector('fat cats ate rats') @@ to_tsquery('cat &amp; rat')</literal></entry>
8676
        <entry><literal>t</literal></entry>
8677
       </row>
8678
       <row>
8679
        <entry> <literal>@@@</literal> </entry>
8680
        <entry>deprecated synonym for <literal>@@</></entry>
8681
        <entry><literal>to_tsvector('fat cats ate rats') @@@ to_tsquery('cat &amp; rat')</literal></entry>
8682
        <entry><literal>t</literal></entry>
8683
       </row>
8684
       <row>
8685
        <entry> <literal>||</literal> </entry>
8686
        <entry>concatenate <type>tsvector</>s</entry>
8687
        <entry><literal>'a:1 b:2'::tsvector || 'c:1 d:2 b:3'::tsvector</literal></entry>
8688
        <entry><literal>'a':1 'b':2,5 'c':3 'd':4</literal></entry>
8689
       </row>
8690
       <row>
8691
        <entry> <literal>&amp;&amp;</literal> </entry>
8692
        <entry>AND <type>tsquery</>s together</entry>
8693
        <entry><literal>'fat | rat'::tsquery &amp;&amp; 'cat'::tsquery</literal></entry>
8694
        <entry><literal>( 'fat' | 'rat' ) &amp; 'cat'</literal></entry>
8695
       </row>
8696
       <row>
8697
        <entry> <literal>||</literal> </entry>
8698
        <entry>OR <type>tsquery</>s together</entry>
8699
        <entry><literal>'fat | rat'::tsquery || 'cat'::tsquery</literal></entry>
8700
        <entry><literal>( 'fat' | 'rat' ) | 'cat'</literal></entry>
8701
       </row>
8702
       <row>
8703
        <entry> <literal>!!</literal> </entry>
8704
        <entry>negate a <type>tsquery</></entry>
8705
        <entry><literal>!! 'cat'::tsquery</literal></entry>
8706
        <entry><literal>!'cat'</literal></entry>
8707
       </row>
8708
       <row>
8709
        <entry> <literal>@&gt;</literal> </entry>
8710
        <entry><type>tsquery</> contains another ?</entry>
8711
        <entry><literal>'cat'::tsquery @&gt; 'cat &amp; rat'::tsquery</literal></entry>
8712
        <entry><literal>f</literal></entry>
8713
       </row>
8714
       <row>
8715
        <entry> <literal>&lt;@</literal> </entry>
8716
        <entry><type>tsquery</> is contained in ?</entry>
8717
        <entry><literal>'cat'::tsquery &lt;@ 'cat &amp; rat'::tsquery</literal></entry>
8718
        <entry><literal>t</literal></entry>
8719
       </row>
8720
      </tbody>
8721
     </tgroup>
8722
    </table>
8723
8724
    <note>
8725
     <para>
8726
      The <type>tsquery</> containment operators consider only the lexemes
8727
      listed in the two queries, ignoring the combining operators.
8728
     </para>
8729
    </note>
8730
8731
    <para>
8732
     In addition to the operators shown in the table, the ordinary B-tree
8733
     comparison operators (<literal>=</>, <literal>&lt;</>, etc) are defined
8734
     for types <type>tsvector</> and <type>tsquery</>.  These are not very
8735
     useful for text searching but allow, for example, unique indexes to be
8736
     built on columns of these types.
8737
    </para>
8738
8739
    <table id="textsearch-functions-table">
8740
     <title>Text Search Functions</title>
8741
     <tgroup cols="5">
8742
      <thead>
8743
       <row>
8744
        <entry>Function</entry>
8745
        <entry>Return Type</entry>
8746
        <entry>Description</entry>
8747
        <entry>Example</entry>
8748
        <entry>Result</entry>
8749
       </row>
8750
      </thead>
8751
      <tbody>
8752
       <row>
8753
        <entry>
8754
         <indexterm>
8755
          <primary>get_current_ts_config</primary>
8756
         </indexterm>
8757
         <literal><function>get_current_ts_config()</function></literal>
8758
        </entry>
8759
        <entry><type>regconfig</type></entry>
8760
        <entry>get default text search configuration</entry>
8761
        <entry><literal>get_current_ts_config()</literal></entry>
8762
        <entry><literal>english</literal></entry>
8763
       </row>
8764
       <row>
8765
        <entry>
8766
         <indexterm>
8767
          <primary>length</primary>
8768
         </indexterm>
8769
         <literal><function>length(<type>tsvector</>)</function></literal>
8770
        </entry>
8771
        <entry><type>integer</type></entry>
8772
        <entry>number of lexemes in <type>tsvector</></entry>
8773
        <entry><literal>length('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
8774
        <entry><literal>3</literal></entry>
8775
       </row>
8776
       <row>
8777
        <entry>
8778
         <indexterm>
8779
          <primary>numnode</primary>
8780
         </indexterm>
8781
         <literal><function>numnode(<type>tsquery</>)</function></literal>
8782
        </entry>
8783
        <entry><type>integer</type></entry>
8784
        <entry>number of lexemes plus operators in <type>tsquery</></entry>
8785
        <entry><literal> numnode('(fat &amp; rat) | cat'::tsquery)</literal></entry>
8786
        <entry><literal>5</literal></entry>
8787
       </row>
8788
       <row>
8789
        <entry>
8790
         <indexterm>
8791
          <primary>plainto_tsquery</primary>
8792
         </indexterm>
8793
         <literal><function>plainto_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
8794
        </entry>
8795
        <entry><type>tsquery</type></entry>
8796
        <entry>produce <type>tsquery</> ignoring punctuation</entry>
8797
        <entry><literal>plainto_tsquery('english', 'The Fat Rats')</literal></entry>
8798
        <entry><literal>'fat' &amp; 'rat'</literal></entry>
8799
       </row>
8800
       <row>
8801
        <entry>
8802
         <indexterm>
8803
          <primary>querytree</primary>
8804
         </indexterm>
8805
         <literal><function>querytree(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>)</function></literal>
8806
        </entry>
8807
        <entry><type>text</type></entry>
8808
        <entry>get indexable part of a <type>tsquery</></entry>
8809
        <entry><literal>querytree('foo &amp; ! bar'::tsquery)</literal></entry>
8810
        <entry><literal>'foo'</literal></entry>
8811
       </row>
8812
       <row>
8813
        <entry>
8814
         <indexterm>
8815
          <primary>setweight</primary>
8816
         </indexterm>
8817
         <literal><function>setweight(<type>tsvector</>, <type>"char"</>)</function></literal>
8818
        </entry>
8819
        <entry><type>tsvector</type></entry>
8820
        <entry>assign weight to each element of <type>tsvector</></entry>
8821
        <entry><literal>setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A')</literal></entry>
8822
        <entry><literal>'cat':3A 'fat':2A,4A 'rat':5A</literal></entry>
8823
       </row>
8824
       <row>
8825
        <entry>
8826
         <indexterm>
8827
          <primary>strip</primary>
8828
         </indexterm>
8829
         <literal><function>strip(<type>tsvector</>)</function></literal>
8830
        </entry>
8831
        <entry><type>tsvector</type></entry>
8832
        <entry>remove positions and weights from <type>tsvector</></entry>
8833
        <entry><literal>strip('fat:2,4 cat:3 rat:5A'::tsvector)</literal></entry>
8834
        <entry><literal>'cat' 'fat' 'rat'</literal></entry>
8835
       </row>
8836
       <row>
8837
        <entry>
8838
         <indexterm>
8839
          <primary>to_tsquery</primary>
8840
         </indexterm>
8841
         <literal><function>to_tsquery(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">query</> <type>text</type>)</function></literal>
8842
        </entry>
8843
        <entry><type>tsquery</type></entry>
8844
        <entry>normalize words and convert to <type>tsquery</></entry>
8845
        <entry><literal>to_tsquery('english', 'The &amp; Fat &amp; Rats')</literal></entry>
8846
        <entry><literal>'fat' &amp; 'rat'</literal></entry>
8847
       </row>
8848
       <row>
8849
        <entry>
8850
         <indexterm>
8851
          <primary>to_tsvector</primary>
8852
         </indexterm>
8853
         <literal><function>to_tsvector(<optional> <replaceable class="PARAMETER">config</> <type>regconfig</> , </optional> <replaceable class="PARAMETER">document</> <type>text</type>)</function></literal>
8854
        </entry>
8855
        <entry><type>tsvector</type></entry>
8856
        <entry>reduce document text to <type>tsvector</></entry>
8857
        <entry><literal>to_tsvector('english', 'The Fat Rats')</literal></entry>
8858
        <entry><literal>'fat':2 'rat':3</literal></entry>
8859
       </row>
8860
       <row>
8861
        <entry>
8862
         <indexterm>
8863
          <primary>ts_headline</primary>
8864
         </indexterm>
8865
         <literal><function>ts_headline(<optional> <replaceable class="PARAMETER">config</replaceable> <type>regconfig</>, </optional> <replaceable class="PARAMETER">document</replaceable> <type>text</>, <replaceable class="PARAMETER">query</replaceable> <type>tsquery</> <optional>, <replaceable class="PARAMETER">options</replaceable> <type>text</> </optional>)</function></literal>
8866
        </entry>
8867
        <entry><type>text</type></entry>
8868
        <entry>display a query match</entry>
8869
        <entry><literal>ts_headline('x y z', 'z'::tsquery)</literal></entry>
8870
        <entry><literal>x y &lt;b&gt;z&lt;/b&gt;</literal></entry>
8871
       </row>
8872
       <row>
8873
        <entry>
8874
         <indexterm>
8875
          <primary>ts_rank</primary>
8876
         </indexterm>
8877
         <literal><function>ts_rank(<optional> <replaceable class="PARAMETER">weights</replaceable> <type>float4[]</>, </optional> <replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">query</replaceable> <type>tsquery</> <optional>, <replaceable class="PARAMETER">normalization</replaceable> <type>integer</> </optional>)</function></literal>
8878
        </entry>
8879
        <entry><type>float4</type></entry>
8880
        <entry>rank document for query</entry>
8881
        <entry><literal>ts_rank(textsearch, query)</literal></entry>
8882
        <entry><literal>0.818</literal></entry>
8883
       </row>
8884
       <row>
8885
        <entry>
8886
         <indexterm>
8887
          <primary>ts_rank_cd</primary>
8888
         </indexterm>
8889
         <literal><function>ts_rank_cd(<optional> <replaceable class="PARAMETER">weights</replaceable> <type>float4[]</>, </optional> <replaceable class="PARAMETER">vector</replaceable> <type>tsvector</>, <replaceable class="PARAMETER">query</replaceable> <type>tsquery</> <optional>, <replaceable class="PARAMETER">normalization</replaceable> <type>integer</> </optional>)</function></literal>
8890
        </entry>
8891
        <entry><type>float4</type></entry>
8892
        <entry>rank document for query using cover density</entry>
8893
        <entry><literal>ts_rank_cd('{0.1, 0.2, 0.4, 1.0}', textsearch, query)</literal></entry>
8894
        <entry><literal>2.01317</literal></entry>
8895
       </row>
8896
       <row>
8897
        <entry>
8898
         <indexterm>
8899
          <primary>ts_rewrite</primary>
8900
         </indexterm>
8901
         <literal><function>ts_rewrite(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">target</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">substitute</replaceable> <type>tsquery</>)</function></literal>
8902
        </entry>
8903
        <entry><type>tsquery</type></entry>
8904
        <entry>replace target with substitute within query</entry>
8905
        <entry><literal>ts_rewrite('a &amp; b'::tsquery, 'a'::tsquery, 'foo|bar'::tsquery)</literal></entry>
8906
        <entry><literal>'b' &amp; ( 'foo' | 'bar' )</literal></entry>
8907
       </row>
8908
       <row>
8909
        <entry><literal><function>ts_rewrite(<replaceable class="PARAMETER">query</replaceable> <type>tsquery</>, <replaceable class="PARAMETER">select</replaceable> <type>text</>)</function></literal></entry>
8910
        <entry><type>tsquery</type></entry>
8911
        <entry>replace using targets and substitutes from a <command>SELECT</> command</entry>
8912
        <entry><literal>SELECT ts_rewrite('a &amp; b'::tsquery, 'SELECT t,s FROM aliases')</literal></entry>
8913
        <entry><literal>'b' &amp; ( 'foo' | 'bar' )</literal></entry>
8914
       </row>
8915
       <row>
8916
        <entry>
8917
         <indexterm>
8918
          <primary>tsvector_update_trigger</primary>
8919
         </indexterm>
8920
         <literal><function>tsvector_update_trigger()</function></literal>
8921
        </entry>
8922
        <entry><type>trigger</type></entry>
8923
        <entry>trigger function for automatic <type>tsvector</> column update</entry>
8924
        <entry><literal>CREATE TRIGGER ... tsvector_update_trigger(tsvcol, 'pg_catalog.swedish', title, body)</literal></entry>
8925
        <entry><literal></literal></entry>
8926
       </row>
8927
       <row>
8928
        <entry>
8929
         <indexterm>
8930
          <primary>tsvector_update_trigger_column</primary>
8931
         </indexterm>
8932
         <literal><function>tsvector_update_trigger_column()</function></literal>
8933
        </entry>
8934
        <entry><type>trigger</type></entry>
8935
        <entry>trigger function for automatic <type>tsvector</> column update</entry>
8936
        <entry><literal>CREATE TRIGGER ... tsvector_update_trigger_column(tsvcol, configcol, title, body)</literal></entry>
8937
        <entry><literal></literal></entry>
8938
       </row>
8939
      </tbody>
8940
     </tgroup>
8941
    </table>
8942
8943
  <note>
8944
   <para>
8945
    All the text search functions that accept an optional <type>regconfig</>
8946
    argument will use the configuration specified by
8947
    <xref linkend="guc-default-text-search-config">
8948
    when that argument is omitted.
8949
   </para>
8950
  </note>
8951
8952
  <para>
8953
   The functions in
8954
   <xref linkend="textsearch-functions-debug-table">
8955
   are listed separately because they are not usually used in everyday text
8956
   searching operations.  They are helpful for development and debugging
8957
   of new text search configurations.
8958
  </para>
8959
8960
    <table id="textsearch-functions-debug-table">
8961
     <title>Text Search Debugging Functions</title>
8962
     <tgroup cols="5">
8963
      <thead>
8964
       <row>
8965
        <entry>Function</entry>
8966
        <entry>Return Type</entry>
8967
        <entry>Description</entry>
8968
        <entry>Example</entry>
8969
        <entry>Result</entry>
8970
       </row>
8971
      </thead>
8972
      <tbody>
8973
       <row>
8974
        <entry>
8975
         <indexterm>
8976
          <primary>ts_debug</primary>
8977
         </indexterm>
8978
         <literal><function>ts_debug(<optional> <replaceable class="PARAMETER">config</replaceable> <type>regconfig</>, </optional> <replaceable class="PARAMETER">document</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">alias</> <type>text</>, OUT <replaceable class="PARAMETER">description</> <type>text</>, OUT <replaceable class="PARAMETER">token</> <type>text</>, OUT <replaceable class="PARAMETER">dictionaries</> <type>regdictionary[]</>, OUT <replaceable class="PARAMETER">dictionary</> <type>regdictionary</>, OUT <replaceable class="PARAMETER">lexemes</> <type>text[]</>)</function></literal>
8979
        </entry>
8980
        <entry><type>setof record</type></entry>
8981
        <entry>test a configuration</entry>
8982
        <entry><literal>ts_debug('english', 'The Brightest supernovaes')</literal></entry>
8983
        <entry><literal>(asciiword,"Word, all ASCII",The,{english_stem},english_stem,{}) ...</literal></entry>
8984
       </row>
8985
       <row>
8986
        <entry>
8987
         <indexterm>
8988
          <primary>ts_lexize</primary>
8989
         </indexterm>
8990
         <literal><function>ts_lexize(<replaceable class="PARAMETER">dict</replaceable> <type>regdictionary</>, <replaceable class="PARAMETER">token</replaceable> <type>text</>)</function></literal>
8991
        </entry>
8992
        <entry><type>text[]</type></entry>
8993
        <entry>test a dictionary</entry>
8994
        <entry><literal>ts_lexize('english_stem', 'stars')</literal></entry>
8995
        <entry><literal>{star}</literal></entry>
8996
       </row>
8997
       <row>
8998
        <entry>
8999
         <indexterm>
9000
          <primary>ts_parse</primary>
9001
         </indexterm>
9002
         <literal><function>ts_parse(<replaceable class="PARAMETER">parser_name</replaceable> <type>text</>, <replaceable class="PARAMETER">document</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">token</> <type>text</>)</function></literal>
9003
        </entry>
9004
        <entry><type>setof record</type></entry>
9005
        <entry>test a parser</entry>
9006
        <entry><literal>ts_parse('default', 'foo - bar')</literal></entry>
9007
        <entry><literal>(1,foo) ...</literal></entry>
9008
       </row>
9009
       <row>
9010
        <entry><literal><function>ts_parse(<replaceable class="PARAMETER">parser_oid</replaceable> <type>oid</>, <replaceable class="PARAMETER">document</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">token</> <type>text</>)</function></literal></entry>
9011
        <entry><type>setof record</type></entry>
9012
        <entry>test a parser</entry>
9013
        <entry><literal>ts_parse(3722, 'foo - bar')</literal></entry>
9014
        <entry><literal>(1,foo) ...</literal></entry>
9015
       </row>
9016
       <row>
9017
        <entry>
9018
         <indexterm>
9019
          <primary>ts_token_type</primary>
9020
         </indexterm>
9021
         <literal><function>ts_token_type(<replaceable class="PARAMETER">parser_name</> <type>text</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">alias</> <type>text</>, OUT <replaceable class="PARAMETER">description</> <type>text</>)</function></literal>
9022
        </entry>
9023
        <entry><type>setof record</type></entry>
9024
        <entry>get token types defined by parser</entry>
9025
        <entry><literal>ts_token_type('default')</literal></entry>
9026
        <entry><literal>(1,asciiword,"Word, all ASCII") ...</literal></entry>
9027
       </row>
9028
       <row>
9029
        <entry><literal><function>ts_token_type(<replaceable class="PARAMETER">parser_oid</> <type>oid</>, OUT <replaceable class="PARAMETER">tokid</> <type>integer</>, OUT <replaceable class="PARAMETER">alias</> <type>text</>, OUT <replaceable class="PARAMETER">description</> <type>text</>)</function></literal></entry>
9030
        <entry><type>setof record</type></entry>
9031
        <entry>get token types defined by parser</entry>
9032
        <entry><literal>ts_token_type(3722)</literal></entry>
9033
        <entry><literal>(1,asciiword,"Word, all ASCII") ...</literal></entry>
9034
       </row>
9035
       <row>
9036
        <entry>
9037
         <indexterm>
9038
          <primary>ts_stat</primary>
9039
         </indexterm>
9040
         <literal><function>ts_stat(<replaceable class="PARAMETER">sqlquery</replaceable> <type>text</>, <optional> <replaceable class="PARAMETER">weights</replaceable> <type>text</>, </optional> OUT <replaceable class="PARAMETER">word</replaceable> <type>text</>, OUT <replaceable class="PARAMETER">ndoc</replaceable> <type>integer</>, OUT <replaceable class="PARAMETER">nentry</replaceable> <type>integer</>)</function></literal>
9041
        </entry>
9042
        <entry><type>setof record</type></entry>
9043
        <entry>get statistics of a <type>tsvector</> column</entry>
9044
        <entry><literal>ts_stat('SELECT vector from apod')</literal></entry>
9045
        <entry><literal>(foo,10,15) ...</literal></entry>
9046
       </row>
9047
      </tbody>
9048
     </tgroup>
9049
    </table>
9050
9051
 </sect1>
9052
9053
9054
 <sect1 id="functions-xml">
9055
  <title>XML Functions</title>
9056
9057
  <para>
9058
   The functions and function-like expressions described in this
9059
   section operate on values of type <type>xml</type>.  Check <xref
9060
   linkend="datatype-xml"> for information about the <type>xml</type>
9061
   type.  The function-like expressions <function>xmlparse</function>
9062
   and <function>xmlserialize</function> for converting to and from
9063
   type <type>xml</type> are not repeated here.  Use of most of these
9064
   functions requires the installation to have been built
9065
   with <command>configure --with-libxml</>.
9066
  </para>
9067
9068
  <sect2 id="functions-producing-xml">
9069
   <title>Producing XML Content</title>
9070
9071
   <para>
9072
    A set of functions and function-like expressions are available for
9073
    producing XML content from SQL data.  As such, they are
9074
    particularly suitable for formatting query results into XML
9075
    documents for processing in client applications.
9076
   </para>
9077
9078
   <sect3>
9079
    <title><literal>xmlcomment</literal></title>
9080
9081
    <indexterm>
9082
     <primary>xmlcomment</primary>
9083
    </indexterm>
9084
9085
<synopsis>
9086
<function>xmlcomment</function>(<replaceable>text</replaceable>)
9087
</synopsis>
9088
9089
    <para>
9090
     The function <function>xmlcomment</function> creates an XML value
9091
     containing an XML comment with the specified text as content.
9092
     The text cannot contain <quote><literal>--</literal></quote> or end with a
9093
     <quote><literal>-</literal></quote> so that the resulting construct is a valid
9094
     XML comment.  If the argument is null, the result is null.
9095
    </para>
9096
9097
    <para>
9098
     Example:
9099
<screen><![CDATA[
9100
SELECT xmlcomment('hello');
9101
9102
  xmlcomment
9103
--------------
9104
 <!--hello-->
9105
]]></screen>
9106
    </para>
9107
   </sect3>
9108
9109
   <sect3>
9110
    <title><literal>xmlconcat</literal></title>
9111
9112
    <indexterm>
9113
     <primary>xmlconcat</primary>
9114
    </indexterm>
9115
9116
<synopsis>
9117
<function>xmlconcat</function>(<replaceable>xml</replaceable><optional>, ...</optional>)
9118
</synopsis>
9119
9120
    <para>
9121
     The function <function>xmlconcat</function> concatenates a list
9122
     of individual XML values to create a single value containing an
9123
     XML content fragment.  Null values are omitted; the result is
9124
     only null if there are no nonnull arguments.
9125
    </para>
9126
9127
    <para>
9128
     Example:
9129
<screen><![CDATA[
9130
SELECT xmlconcat('<abc/>', '<bar>foo</bar>');
9131
9132
      xmlconcat
9133
----------------------
9134
 <abc/><bar>foo</bar>
9135
]]></screen>
9136
    </para>
9137
9138
    <para>
9139
     XML declarations, if present, are combined as follows.  If all
9140
     argument values have the same XML version declaration, that
9141
     version is used in the result, else no version is used.  If all
9142
     argument values have the standalone declaration value
9143
     <quote>yes</quote>, then that value is used in the result.  If
9144
     all argument values have a standalone declaration value and at
9145
     least one is <quote>no</quote>, then that is used in the result.
9146
     Else the result will have no standalone declaration.  If the
9147
     result is determined to require a standalone declaration but no
9148
     version declaration, a version declaration with version 1.0 will
9149
     be used because XML requires an XML declaration to contain a
9150
     version declaration.  Encoding declarations are ignored and
9151
     removed in all cases.
9152
    </para>
9153
9154
    <para>
9155
     Example:
9156
<screen><![CDATA[
9157
SELECT xmlconcat('<?xml version="1.1"?><foo/>', '<?xml version="1.1" standalone="no"?><bar/>');
9158
9159
             xmlconcat
9160
-----------------------------------
9161
 <?xml version="1.1"?><foo/><bar/>
9162
]]></screen>
9163
    </para>
9164
   </sect3>
9165
9166
   <sect3>
9167
    <title><literal>xmlelement</literal></title>
9168
9169
   <indexterm>
9170
    <primary>xmlelement</primary>
9171
   </indexterm>
9172
9173
<synopsis>
9174
<function>xmlelement</function>(name <replaceable>name</replaceable> <optional>, xmlattributes(<replaceable>value</replaceable> <optional>AS <replaceable>attname</replaceable></optional> <optional>, ... </optional>)</optional> <optional><replaceable>, content, ...</replaceable></optional>)
9175
</synopsis>
9176
9177
    <para>
9178
     The <function>xmlelement</function> expression produces an XML
9179
     element with the given name, attributes, and content.
9180
    </para>
9181
9182
    <para>
9183
     Examples:
9184
<screen><![CDATA[
9185
SELECT xmlelement(name foo);
9186
9187
 xmlelement
9188
------------
9189
 <foo/>
9190
9191
SELECT xmlelement(name foo, xmlattributes('xyz' as bar));
9192
9193
    xmlelement
9194
------------------
9195
 <foo bar="xyz"/>
9196
9197
SELECT xmlelement(name foo, xmlattributes(current_date as bar), 'cont', 'ent');
9198
9199
             xmlelement
9200
-------------------------------------
9201
 <foo bar="2007-01-26">content</foo>
9202
]]></screen>
9203
    </para>
9204
9205
    <para>
9206
     Element and attribute names that are not valid XML names are
9207
     escaped by replacing the offending characters by the sequence
9208
     <literal>_x<replaceable>HHHH</replaceable>_</literal>, where
9209
     <replaceable>HHHH</replaceable> is the character's Unicode
9210
     codepoint in hexadecimal notation.  For example:
9211
<screen><![CDATA[
9212
SELECT xmlelement(name "foo$bar", xmlattributes('xyz' as "a&b"));
9213
9214
            xmlelement
9215
----------------------------------
9216
 <foo_x0024_bar a_x0026_b="xyz"/>
9217
]]></screen>
9218
    </para>
9219
9220
    <para>
9221
     An explicit attribute name need not be specified if the attribute
9222
     value is a column reference, in which case the column's name will
9223
     be used as the attribute name by default.  In other cases, the
9224
     attribute must be given an explicit name.  So this example is
9225
     valid:
9226
<screen>
9227
CREATE TABLE test (a xml, b xml);
9228
SELECT xmlelement(name test, xmlattributes(a, b)) FROM test;
9229
</screen>
9230
     But these are not:
9231
<screen>
9232
SELECT xmlelement(name test, xmlattributes('constant'), a, b) FROM test;
9233
SELECT xmlelement(name test, xmlattributes(func(a, b))) FROM test;
9234
</screen>
9235
    </para>
9236
9237
    <para>
9238
     Element content, if specified, will be formatted according to
9239
     its data type.  If the content is itself of type <type>xml</type>,
9240
     complex XML documents can be constructed.  For example:
9241
<screen><![CDATA[
9242
SELECT xmlelement(name foo, xmlattributes('xyz' as bar),
9243
                            xmlelement(name abc),
9244
                            xmlcomment('test'),
9245
                            xmlelement(name xyz));
9246
9247
                  xmlelement
9248
----------------------------------------------
9249
 <foo bar="xyz"><abc/><!--test--><xyz/></foo>
9250
]]></screen>
9251
9252
     Content of other types will be formatted into valid XML character
9253
     data.  This means in particular that the characters &lt;, &gt;,
9254
     and &amp; will be converted to entities.  Binary data (data type
9255
     <type>bytea</type>) will be represented in base64 or hex
9256
     encoding, depending on the setting of the configuration parameter
9257
     <xref linkend="guc-xmlbinary">.  The particular behavior for
9258
     individual data types is expected to evolve in order to align the
9259
     SQL and PostgreSQL data types with the XML Schema specification,
9260
     at which point a more precise description will appear.
9261
    </para>
9262
   </sect3>
9263
9264
   <sect3>
9265
    <title><literal>xmlforest</literal></title>
9266
9267
   <indexterm>
9268
    <primary>xmlforest</primary>
9269
   </indexterm>
9270
9271
<synopsis>
9272
<function>xmlforest</function>(<replaceable>content</replaceable> <optional>AS <replaceable>name</replaceable></optional> <optional>, ...</optional>)
9273
</synopsis>
9274
9275
    <para>
9276
     The <function>xmlforest</function> expression produces an XML
9277
     forest (sequence) of elements using the given names and content.
9278
    </para>
9279
9280
    <para>
9281
     Examples:
9282
<screen><![CDATA[
9283
SELECT xmlforest('abc' AS foo, 123 AS bar);
9284
9285
          xmlforest
9286
------------------------------
9287
 <foo>abc</foo><bar>123</bar>
9288
9289
9290
SELECT xmlforest(table_name, column_name)
9291
FROM information_schema.columns
9292
WHERE table_schema = 'pg_catalog';
9293
9294
                                         xmlforest
9295
-------------------------------------------------------------------------------------------
9296
 <table_name>pg_authid</table_name><column_name>rolname</column_name>
9297
 <table_name>pg_authid</table_name><column_name>rolsuper</column_name>
9298
 ...
9299
]]></screen>
9300
9301
     As seen in the second example, the element name can be omitted if
9302
     the content value is a column reference, in which case the column
9303
     name is used by default.  Otherwise, a name must be specified.
9304
    </para>
9305
9306
    <para>
9307
     Element names that are not valid XML names are escaped as shown
9308
     for <function>xmlelement</function> above.  Similarly, content
9309
     data is escaped to make valid XML content, unless it is already
9310
     of type <type>xml</type>.
9311
    </para>
9312
9313
    <para>
9314
     Note that XML forests are not valid XML documents if they consist
9315
     of more than one element, so it might be useful to wrap
9316
     <function>xmlforest</function> expressions in
9317
     <function>xmlelement</function>.
9318
    </para>
9319
   </sect3>
9320
9321
   <sect3>
9322
    <title><literal>xmlpi</literal></title>
9323
9324
   <indexterm>
9325
    <primary>xmlpi</primary>
9326
   </indexterm>
9327
9328
<synopsis>
9329
<function>xmlpi</function>(name <replaceable>target</replaceable> <optional>, <replaceable>content</replaceable></optional>)
9330
</synopsis>
9331
9332
    <para>
9333
     The <function>xmlpi</function> expression creates an XML
9334
     processing instruction.  The content, if present, must not
9335
     contain the character sequence <literal>?&gt;</literal>.
9336
    </para>
9337
9338
    <para>
9339
     Example:
9340
<screen><![CDATA[
9341
SELECT xmlpi(name php, 'echo "hello world";');
9342
9343
            xmlpi
9344
-----------------------------
9345
 <?php echo "hello world";?>
9346
]]></screen>
9347
    </para>
9348
   </sect3>
9349
9350
   <sect3>
9351
    <title><literal>xmlroot</literal></title>
9352
9353
   <indexterm>
9354
    <primary>xmlroot</primary>
9355
   </indexterm>
9356
9357
<synopsis>
9358
<function>xmlroot</function>(<replaceable>xml</replaceable>, version <replaceable>text</replaceable> | no value <optional>, standalone yes|no|no value</optional>)
9359
</synopsis>
9360
9361
    <para>
9362
     The <function>xmlroot</function> expression alters the properties
9363
     of the root node of an XML value.  If a version is specified,
9364
     it replaces the value in the root node's version declaration; if a
9365
     standalone setting is specified, it replaces the value in the
9366
     root node's standalone declaration.
9367
    </para>
9368
9369
    <para>
9370
<screen><![CDATA[
9371
SELECT xmlroot(xmlparse(document '<?xml version="1.1"?><content>abc</content>'),
9372
               version '1.0', standalone yes);
9373
9374
                xmlroot
9375
----------------------------------------
9376
 <?xml version="1.0" standalone="yes"?>
9377
 <content>abc</content>
9378
]]></screen>
9379
    </para>
9380
   </sect3>
9381
9382
   <sect3 id="functions-xml-xmlagg">
9383
    <title><literal>xmlagg</literal></title>
9384
9385
    <indexterm>
9386
     <primary>xmlagg</primary>
9387
    </indexterm>
9388
9389
<synopsis>
9390
<function>xmlagg</function>(<replaceable>xml</replaceable>)
9391
</synopsis>
9392
9393
    <para>
9394
     The function <function>xmlagg</function> is, unlike the other
9395
     functions described here, an aggregate function.  It concatenates the
9396
     input values to the aggregate function call,
9397
     much like <function>xmlconcat</function> does, except that concatenation
9398
     occurs across rows rather than across expressions in a single row.
9399
     See <xref linkend="functions-aggregate"> for additional information
9400
     about aggregate functions.
9401
    </para>
9402
9403
    <para>
9404
     Example:
9405
<screen><![CDATA[
9406
CREATE TABLE test (y int, x xml);
9407
INSERT INTO test VALUES (1, '<foo>abc</foo>');
9408
INSERT INTO test VALUES (2, '<bar/>');
9409
SELECT xmlagg(x) FROM test;
9410
        xmlagg
9411
----------------------
9412
 <foo>abc</foo><bar/>
9413
]]></screen>
9414
    </para>
9415
9416
    <para>
9417
     To determine the order of the concatenation, an <literal>ORDER BY</>
9418
     clause may be added to the aggregate call as described in
9419
     <xref linkend="syntax-aggregates">. For example:
9420
9421
<screen><![CDATA[
9422
SELECT xmlagg(x ORDER BY y DESC) FROM test;
9423
        xmlagg
9424
----------------------
9425
 <bar/><foo>abc</foo>
9426
]]></screen>
9427
    </para>
9428
9429
    <para>
9430
     The following non-standard approach used to be recommended
9431
     in previous versions, and may still be useful in specific
9432
     cases:
9433
9434
<screen><![CDATA[
9435
SELECT xmlagg(x) FROM (SELECT * FROM test ORDER BY y DESC) AS tab;
9436
        xmlagg
9437
----------------------
9438
 <bar/><foo>abc</foo>
9439
]]></screen>
9440
    </para>
9441
   </sect3>
9442
   </sect2>
9443
9444
   <sect2 id="functions-xml-predicates">
9445
    <title>XML Predicates</title>
9446
9447
    <para>
9448
     The expressions described in this section check properties
9449
     of <type>xml</type> values.
9450
    </para>
9451
9452
   <sect3>
9453
    <title><literal>IS DOCUMENT</literal></title>
9454
9455
    <indexterm>
9456
     <primary>IS DOCUMENT</primary>
9457
    </indexterm>
9458
9459
<synopsis>
9460
<replaceable>xml</replaceable> IS DOCUMENT
9461
</synopsis>
9462
9463
    <para>
9464
     The expression <literal>IS DOCUMENT</literal> returns true if the
9465
     argument XML value is a proper XML document, false if it is not
9466
     (that is, it is a content fragment), or null if the argument is
9467
     null.  See <xref linkend="datatype-xml"> about the difference
9468
     between documents and content fragments.
9469
    </para>
9470
   </sect3>
9471
9472
   <sect3 id="xml-exists">
9473
    <title><literal>XMLEXISTS</literal></title>
9474
9475
    <indexterm>
9476
     <primary>XMLEXISTS</primary>
9477
    </indexterm>
9478
9479
<synopsis>
9480
<function>XMLEXISTS</function>(<replaceable>text</replaceable> PASSING <optional>BY REF</optional> <replaceable>xml</replaceable> <optional>BY REF</optional>)
9481
</synopsis>
9482
9483
    <para>
9484
     The function <function>xmlexists</function> returns true if the
9485
     XPath expression in the first argument returns any nodes, and
9486
     false otherwise.  (If either argument is null, the result is
9487
     null.)
9488
    </para>
9489
9490
    <para>
9491
     Example:
9492
     <screen><![CDATA[
9493
SELECT xmlexists('//town[text() = ''Toronto'']' PASSING BY REF '<towns><town>Toronto</town><town>Ottawa</town></towns>');
9494
9495
 xmlexists
9496
------------
9497
 t
9498
(1 row)
9499
]]></screen>
9500
    </para>
9501
9502
    <para>
9503
     The <literal>BY REF</literal> clauses have no effect in
9504
     PostgreSQL, but are allowed for SQL conformance and compatibility
9505
     with other implementations.  Per SQL standard, the
9506
     first <literal>BY REF</literal> is required, the second is
9507
     optional.  Also note that the SQL standard specifies
9508
     the <function>xmlexists</function> construct to take an XQuery
9509
     expression as first argument, but PostgreSQL currently only
9510
     supports XPath, which is a subset of XQuery.
9511
    </para>
9512
   </sect3>
9513
9514
   <sect3 id="xml-is-well-formed">
9515
    <title><literal>xml_is_well_formed</literal></title>
9516
9517
    <indexterm>
9518
     <primary>xml_is_well_formed</primary>
9519
    </indexterm>
9520
9521
    <indexterm>
9522
     <primary>xml_is_well_formed_document</primary>
9523
    </indexterm>
9524
9525
    <indexterm>
9526
     <primary>xml_is_well_formed_content</primary>
9527
    </indexterm>
9528
9529
<synopsis>
9530
<function>xml_is_well_formed</function>(<replaceable>text</replaceable>)
9531
<function>xml_is_well_formed_document</function>(<replaceable>text</replaceable>)
9532
<function>xml_is_well_formed_content</function>(<replaceable>text</replaceable>)
9533
</synopsis>
9534
9535
    <para>
9536
     These functions check whether a <type>text</> string is well-formed XML,
9537
     returning a Boolean result.
9538
     <function>xml_is_well_formed_document</function> checks for a well-formed
9539
     document, while <function>xml_is_well_formed_content</function> checks
9540
     for well-formed content.  <function>xml_is_well_formed</function> does
9541
     the former if the <xref linkend="guc-xmloption"> configuration
9542
     parameter is set to <literal>DOCUMENT</>, or the latter if it is set to
9543
     <literal>CONTENT</>.  This means that
9544
     <function>xml_is_well_formed</function> is useful for seeing whether
9545
     a simple cast to type <type>xml</> will succeed, whereas the other two
9546
     functions are useful for seeing whether the corresponding variants of
9547
     <function>XMLPARSE</> will succeed.
9548
    </para>
9549
9550
    <para>
9551
     Examples:
9552
9553
<screen><![CDATA[
9554
SET xmloption TO DOCUMENT;
9555
SELECT xml_is_well_formed('<>');
9556
 xml_is_well_formed 
9557
--------------------
9558
 f
9559
(1 row)
9560
9561
SELECT xml_is_well_formed('<abc/>');
9562
 xml_is_well_formed 
9563
--------------------
9564
 t
9565
(1 row)
9566
9567
SET xmloption TO CONTENT;
9568
SELECT xml_is_well_formed('abc');
9569
 xml_is_well_formed 
9570
--------------------
9571
 t
9572
(1 row)
9573
9574
SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</pg:foo>');
9575
 xml_is_well_formed_document 
9576
-----------------------------
9577
 t
9578
(1 row)
9579
9580
SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</my:foo>');
9581
 xml_is_well_formed_document 
9582
-----------------------------
9583
 f
9584
(1 row)
9585
]]></screen>
9586
9587
     The last example shows that the checks include whether
9588
     namespaces are correctly matched.
9589
    </para>
9590
   </sect3>
9591
  </sect2>
9592
9593
  <sect2 id="functions-xml-processing">
9594
   <title>Processing XML</title>
9595
9596
   <indexterm>
9597
    <primary>XPath</primary>
9598
   </indexterm>
9599
9600
   <para>
9601
    To process values of data type <type>xml</type>, PostgreSQL offers
9602
    the functions <function>xpath</function> and
9603
    <function>xpath_exists</function>, which evaluate XPath 1.0
9604
    expressions.
9605
   </para>
9606
9607
<synopsis>
9608
<function>xpath</function>(<replaceable>xpath</replaceable>, <replaceable>xml</replaceable> <optional>, <replaceable>nsarray</replaceable></optional>)
9609
</synopsis>
9610
9611
   <para>
9612
    The function <function>xpath</function> evaluates the XPath
9613
    expression <replaceable>xpath</replaceable> (a <type>text</> value)
9614
    against the XML value
9615
    <replaceable>xml</replaceable>.  It returns an array of XML values
9616
    corresponding to the node set produced by the XPath expression.
9617
    If the XPath expression returns a scalar value rather than a node set,
9618
    a single-element array is returned.
9619
   </para>
9620
9621
  <para>
9622
    The second argument must be a well formed XML document. In particular,
9623
    it must have a single root node element.
9624
  </para>
9625
9626
   <para>
9627
    The optional third argument of the function is an array of namespace
9628
    mappings.  This array should be a two-dimensional <type>text</> array with
9629
    the length of the second axis being equal to 2 (i.e., it should be an
9630
    array of arrays, each of which consists of exactly 2 elements).
9631
    The first element of each array entry is the namespace name (alias), the
9632
    second the namespace URI. It is not required that aliases provided in
9633
    this array be the same as those being used in the XML document itself (in
9634
    other words, both in the XML document and in the <function>xpath</function>
9635
    function context, aliases are <emphasis>local</>).
9636
   </para>
9637
9638
   <para>
9639
    Example:
9640
<screen><![CDATA[
9641
SELECT xpath('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
9642
             ARRAY[ARRAY['my', 'http://example.com']]);
9643
9644
 xpath  
9645
--------
9646
 {test}
9647
(1 row)
9648
]]></screen>
9649
   </para>
9650
9651
   <para>
9652
    To deal with default (anonymous) namespaces, do something like this:
9653
<screen><![CDATA[
9654
SELECT xpath('//mydefns:b/text()', '<a xmlns="http://example.com"><b>test</b></a>',
9655
             ARRAY[ARRAY['mydefns', 'http://example.com']]);
9656
9657
 xpath
9658
--------
9659
 {test}
9660
(1 row)
9661
]]></screen>
9662
   </para>
9663
9664
   <indexterm>
9665
    <primary>xpath_exists</primary>
9666
   </indexterm>
9667
9668
<synopsis>
9669
<function>xpath_exists</function>(<replaceable>xpath</replaceable>, <replaceable>xml</replaceable> <optional>, <replaceable>nsarray</replaceable></optional>)
9670
</synopsis>
9671
9672
   <para>
9673
    The function <function>xpath_exists</function> is a specialized form
9674
    of the <function>xpath</function> function.  Instead of returning the
9675
    individual XML values that satisfy the XPath, this function returns a
9676
    Boolean indicating whether the query was satisfied or not.  This
9677
    function is equivalent to the standard <literal>XMLEXISTS</> predicate,
9678
    except that it also offers support for a namespace mapping argument.
9679
   </para>
9680
9681
   <para>
9682
    Example:
9683
<screen><![CDATA[
9684
SELECT xpath_exists('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
9685
                     ARRAY[ARRAY['my', 'http://example.com']]);
9686
9687
 xpath_exists  
9688
--------------
9689
 t
9690
(1 row)
9691
]]></screen>
9692
   </para>
9693
  </sect2>
9694
9695
  <sect2 id="functions-xml-mapping">
9696
   <title>Mapping Tables to XML</title>
9697
9698
   <indexterm zone="functions-xml-mapping">
9699
    <primary>XML export</primary>
9700
   </indexterm>
9701
9702
   <para>
9703
    The following functions map the contents of relational tables to
9704
    XML values.  They can be thought of as XML export functionality:
9705
<synopsis>
9706
table_to_xml(tbl regclass, nulls boolean, tableforest boolean, targetns text)
9707
query_to_xml(query text, nulls boolean, tableforest boolean, targetns text)
9708
cursor_to_xml(cursor refcursor, count int, nulls boolean,
9709
              tableforest boolean, targetns text)
9710
</synopsis>
9711
    The return type of each function is <type>xml</type>.
9712
   </para>
9713
9714
   <para>
9715
    <function>table_to_xml</function> maps the content of the named
9716
    table, passed as parameter <parameter>tbl</parameter>.  The
9717
    <type>regclass</type> type accepts strings identifying tables using the
9718
    usual notation, including optional schema qualifications and
9719
    double quotes.  <function>query_to_xml</function> executes the
9720
    query whose text is passed as parameter
9721
    <parameter>query</parameter> and maps the result set.
9722
    <function>cursor_to_xml</function> fetches the indicated number of
9723
    rows from the cursor specified by the parameter
9724
    <parameter>cursor</parameter>.  This variant is recommended if
9725
    large tables have to be mapped, because the result value is built
9726
    up in memory by each function.
9727
   </para>
9728
9729
   <para>
9730
    If <parameter>tableforest</parameter> is false, then the resulting
9731
    XML document looks like this:
9732
<screen><![CDATA[
9733
<tablename>
9734
  <row>
9735
    <columnname1>data</columnname1>
9736
    <columnname2>data</columnname2>
9737
  </row>
9738
9739
  <row>
9740
    ...
9741
  </row>
9742
9743
  ...
9744
</tablename>
9745
]]></screen>
9746
9747
    If <parameter>tableforest</parameter> is true, the result is an
9748
    XML content fragment that looks like this:
9749
<screen><![CDATA[
9750
<tablename>
9751
  <columnname1>data</columnname1>
9752
  <columnname2>data</columnname2>
9753
</tablename>
9754
9755
<tablename>
9756
  ...
9757
</tablename>
9758
9759
...
9760
]]></screen>
9761
9762
    If no table name is available, that is, when mapping a query or a
9763
    cursor, the string <literal>table</literal> is used in the first
9764
    format, <literal>row</literal> in the second format.
9765
   </para>
9766
9767
   <para>
9768
    The choice between these formats is up to the user.  The first
9769
    format is a proper XML document, which will be important in many
9770
    applications.  The second format tends to be more useful in the
9771
    <function>cursor_to_xml</function> function if the result values are to be
9772
    reassembled into one document later on.  The functions for
9773
    producing XML content discussed above, in particular
9774
    <function>xmlelement</function>, can be used to alter the results
9775
    to taste.
9776
   </para>
9777
9778
   <para>
9779
    The data values are mapped in the same way as described for the
9780
    function <function>xmlelement</function> above.
9781
   </para>
9782
9783
   <para>
9784
    The parameter <parameter>nulls</parameter> determines whether null
9785
    values should be included in the output.  If true, null values in
9786
    columns are represented as:
9787
<screen><![CDATA[
9788
<columnname xsi:nil="true"/>
9789
]]></screen>
9790
    where <literal>xsi</literal> is the XML namespace prefix for XML
9791
    Schema Instance.  An appropriate namespace declaration will be
9792
    added to the result value.  If false, columns containing null
9793
    values are simply omitted from the output.
9794
   </para>
9795
9796
   <para>
9797
    The parameter <parameter>targetns</parameter> specifies the
9798
    desired XML namespace of the result.  If no particular namespace
9799
    is wanted, an empty string should be passed.
9800
   </para>
9801
9802
   <para>
9803
    The following functions return XML Schema documents describing the
9804
    mappings performed by the corresponding functions above:
9805
<synopsis>
9806
table_to_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text)
9807
query_to_xmlschema(query text, nulls boolean, tableforest boolean, targetns text)
9808
cursor_to_xmlschema(cursor refcursor, nulls boolean, tableforest boolean, targetns text)
9809
</synopsis>
9810
    It is essential that the same parameters are passed in order to
9811
    obtain matching XML data mappings and XML Schema documents.
9812
   </para>
9813
9814
   <para>
9815
    The following functions produce XML data mappings and the
9816
    corresponding XML Schema in one document (or forest), linked
9817
    together.  They can be useful where self-contained and
9818
    self-describing results are wanted:
9819
<synopsis>
9820
table_to_xml_and_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text)
9821
query_to_xml_and_xmlschema(query text, nulls boolean, tableforest boolean, targetns text)
9822
</synopsis>
9823
   </para>
9824
9825
   <para>
9826
    In addition, the following functions are available to produce
9827
    analogous mappings of entire schemas or the entire current
9828
    database:
9829
<synopsis>
9830
schema_to_xml(schema name, nulls boolean, tableforest boolean, targetns text)
9831
schema_to_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text)
9832
schema_to_xml_and_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text)
9833
9834
database_to_xml(nulls boolean, tableforest boolean, targetns text)
9835
database_to_xmlschema(nulls boolean, tableforest boolean, targetns text)
9836
database_to_xml_and_xmlschema(nulls boolean, tableforest boolean, targetns text)
9837
</synopsis>
9838
9839
    Note that these potentially produce a lot of data, which needs to
9840
    be built up in memory.  When requesting content mappings of large
9841
    schemas or databases, it might be worthwhile to consider mapping the
9842
    tables separately instead, possibly even through a cursor.
9843
   </para>
9844
9845
   <para>
9846
    The result of a schema content mapping looks like this:
9847
9848
<screen><![CDATA[
9849
<schemaname>
9850
9851
table1-mapping
9852
9853
table2-mapping
9854
9855
...
9856
9857
</schemaname>]]></screen>
9858
9859
    where the format of a table mapping depends on the
9860
    <parameter>tableforest</parameter> parameter as explained above.
9861
   </para>
9862
9863
   <para>
9864
    The result of a database content mapping looks like this:
9865
9866
<screen><![CDATA[
9867
<dbname>
9868
9869
<schema1name>
9870
  ...
9871
</schema1name>
9872
9873
<schema2name>
9874
  ...
9875
</schema2name>
9876
9877
...
9878
9879
</dbname>]]></screen>
9880
9881
    where the schema mapping is as above.
9882
   </para>
9883
9884
   <para>
9885
    As an example of using the output produced by these functions,
9886
    <xref linkend="xslt-xml-html"> shows an XSLT stylesheet that
9887
    converts the output of
9888
    <function>table_to_xml_and_xmlschema</function> to an HTML
9889
    document containing a tabular rendition of the table data.  In a
9890
    similar manner, the results from these functions can be
9891
    converted into other XML-based formats.
9892
   </para>
9893
9894
   <figure id="xslt-xml-html">
9895
    <title>XSLT Stylesheet for Converting SQL/XML Output to HTML</title>
9896
<programlisting><![CDATA[
9897
<?xml version="1.0"?>
9898
<xsl:stylesheet version="1.0"
9899
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
9900
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
9901
    xmlns="http://www.w3.org/1999/xhtml"
9902
>
9903
9904
  <xsl:output method="xml"
9905
      doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
9906
      doctype-public="-//W3C/DTD XHTML 1.0 Strict//EN"
9907
      indent="yes"/>
9908
9909
  <xsl:template match="/*">
9910
    <xsl:variable name="schema" select="//xsd:schema"/>
9911
    <xsl:variable name="tabletypename"
9912
                  select="$schema/xsd:element[@name=name(current())]/@type"/>
9913
    <xsl:variable name="rowtypename"
9914
                  select="$schema/xsd:complexType[@name=$tabletypename]/xsd:sequence/xsd:element[@name='row']/@type"/>
9915
9916
    <html>
9917
      <head>
9918
        <title><xsl:value-of select="name(current())"/></title>
9919
      </head>
9920
      <body>
9921
        <table>
9922
          <tr>
9923
            <xsl:for-each select="$schema/xsd:complexType[@name=$rowtypename]/xsd:sequence/xsd:element/@name">
9924
              <th><xsl:value-of select="."/></th>
9925
            </xsl:for-each>
9926
          </tr>
9927
9928
          <xsl:for-each select="row">
9929
            <tr>
9930
              <xsl:for-each select="*">
9931
                <td><xsl:value-of select="."/></td>
9932
              </xsl:for-each>
9933
            </tr>
9934
          </xsl:for-each>
9935
        </table>
9936
      </body>
9937
    </html>
9938
  </xsl:template>
9939
9940
</xsl:stylesheet>
9941
]]></programlisting>
9942
   </figure>
9943
  </sect2>
9944
 </sect1>
9945
9946
 <sect1 id="functions-json">
9947
  <title>JSON Functions and Operators</title>
9948
9949
  <indexterm zone="functions-json">
9950
    <primary>JSON</primary>
9951
    <secondary>Functions and operators</secondary>
9952
  </indexterm>
9953
9954
   <para>
9955
   <xref linkend="functions-json-op-table"> shows the operators that are
9956
   available for use with JSON (see <xref linkend="datatype-json">) data.
9957
  </para>
9958
9959
  <table id="functions-json-op-table">
9960
     <title>JSON Operators</title>
9961
     <tgroup cols="4">
9962
      <thead>
9963
       <row>
9964
        <entry>Operator</entry>
9965
        <entry>Right Operand Type</entry>
9966
        <entry>Description</entry>
9967
        <entry>Example</entry>
9968
       </row>
9969
      </thead>
9970
      <tbody>
9971
       <row>
9972
        <entry><literal>-&gt;</literal></entry>
9973
        <entry>int</entry>
9974
        <entry>Get JSON array element</entry>
9975
        <entry><literal>'[1,2,3]'::json-&gt;2</literal></entry>
9976
       </row>
9977
       <row>
9978
        <entry><literal>-&gt;</literal></entry>
9979
        <entry>text</entry>
9980
        <entry>Get JSON object field</entry>
9981
        <entry><literal>'{"a":1,"b":2}'::json-&gt;'b'</literal></entry>
9982
       </row>
9983
        <row>
9984
        <entry><literal>-&gt;&gt;</literal></entry>
9985
        <entry>int</entry>
9986
        <entry>Get JSON array element as text</entry>
9987
        <entry><literal>'[1,2,3]'::json-&gt;&gt;2</literal></entry>
9988
       </row>
9989
       <row>
9990
        <entry><literal>-&gt;&gt;</literal></entry>
9991
        <entry>text</entry>
9992
        <entry>Get JSON object field as text</entry>
9993
        <entry><literal>'{"a":1,"b":2}'::json-&gt;&gt;'b'</literal></entry>
9994
       </row>
9995
       <row>
9996
        <entry><literal>#&gt;</literal></entry>
9997
        <entry>array of text</entry>
9998
        <entry>Get JSON object at specified path</entry>
9999
        <entry><literal>'{"a":[1,2,3],"b":[4,5,6]}'::json#&gt;'{a,2}'</literal></entry>
10000
       </row>
10001
       <row>
10002
        <entry><literal>#&gt;&gt;</literal></entry>
10003
        <entry>array of text</entry>
10004
        <entry>Get JSON object at specified path as text</entry>
10005
        <entry><literal>'{"a":[1,2,3],"b":[4,5,6]}'::json#&gt;&gt;'{a,2}'</literal></entry>
10006
       </row>
10007
      </tbody>
10008
     </tgroup>
10009
   </table>
10010
10011
  <para>
10012
   <xref linkend="functions-json-table"> shows the functions that are available
10013
   for creating and manipulating JSON (see <xref linkend="datatype-json">) data.
10014
  </para>
10015
10016
  <table id="functions-json-table">
10017
    <title>JSON Support Functions</title>
10018
    <tgroup cols="5">
10019
     <thead>
10020
      <row>
10021
       <entry>Function</entry>
10022
       <entry>Return Type</entry>
10023
       <entry>Description</entry>
10024
       <entry>Example</entry>
10025
       <entry>Example Result</entry>
10026
      </row>
10027
     </thead>
10028
     <tbody>
10029
      <row>
10030
       <entry>
10031
         <indexterm>
10032
          <primary>array_to_json</primary>
10033
         </indexterm>
10034
         <literal>array_to_json(anyarray [, pretty_bool])</literal>
10035
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10036
       <entry><type>json</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10037
       <entry>
10038
         Returns the array as JSON. A PostgreSQL multidimensional array
10039
         becomes a JSON array of arrays. Line feeds will be added between
10040
         dimension 1 elements if <parameter>pretty_bool</parameter> is true.
10041
       </entry>
10042
       <entry><literal>array_to_json('{{1,5},{99,100}}'::int[])</literal></entry>
10043
       <entry><literal>[[1,5],[99,100]]</literal></entry>
10044
      </row>
10045
      <row>
10046
       <entry>
10047
         <indexterm>
10048
          <primary>row_to_json</primary>
10049
         </indexterm>
10050
         <literal>row_to_json(record [, pretty_bool])</literal>
10051
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10052
       <entry><type>json</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10053
       <entry>
10054
         Returns the row as JSON. Line feeds will be added between level
10055
         1 elements if <parameter>pretty_bool</parameter> is true.
10056
       </entry>
10057
       <entry><literal>row_to_json(row(1,'foo'))</literal></entry>
10058
       <entry><literal>{"f1":1,"f2":"foo"}</literal></entry>
10059
      </row>
10060
      <row>
10061
       <entry>
10062
         <indexterm>
10063
          <primary>to_json</primary>
10064
         </indexterm>
10065
         <literal>to_json(anyelement)</literal>
10066
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10067
       <entry><type>json</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10068
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10069
         Returns the value as JSON. If the data type is not built in, and there
10070
         is a cast from the type to <type>json</type>, the cast function will be used to
1 by Martin Pitt
Import upstream version 9.3~beta1
10071
         perform the conversion. Otherwise, for any value other than a number,
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10072
         a Boolean, or a null value, the text representation will be used, escaped and
1 by Martin Pitt
Import upstream version 9.3~beta1
10073
         quoted so that it is legal JSON.
10074
       </entry>
10075
       <entry><literal>to_json('Fred said "Hi."'::text)</literal></entry>
10076
       <entry><literal>"Fred said \"Hi.\""</literal></entry>
10077
      </row>
10078
      <row>
10079
       <entry>
10080
         <indexterm>
10081
          <primary>json_array_length</primary>
10082
         </indexterm>
10083
         <literal>json_array_length(json)</literal>
10084
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10085
       <entry><type>int</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10086
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10087
         Returns the number of elements in the outermost JSON array.
1 by Martin Pitt
Import upstream version 9.3~beta1
10088
       </entry>
10089
       <entry><literal>json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]')</literal></entry>
10090
       <entry><literal>5</literal></entry>
10091
      </row>
10092
      <row>
10093
       <entry>
10094
         <indexterm>
10095
          <primary>json_each</primary>
10096
         </indexterm>
10097
         <literal>json_each(json)</literal>
10098
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10099
       <entry><type>SETOF key text, value json</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10100
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10101
         Expands the outermost JSON object into a set of key/value pairs.
1 by Martin Pitt
Import upstream version 9.3~beta1
10102
       </entry>
10103
       <entry><literal>select * from json_each('{"a":"foo", "b":"bar"}')</literal></entry>
10104
       <entry>
10105
<programlisting>
10106
 key | value
10107
-----+-------
10108
 a   | "foo"
10109
 b   | "bar"
10110
 </programlisting>
10111
       </entry>
10112
      </row>
10113
      <row>
10114
       <entry>
10115
         <indexterm>
10116
          <primary>json_each_text</primary>
10117
         </indexterm>
10118
         <literal>json_each_text(from_json json)</literal>
10119
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10120
       <entry><type>SETOF key text, value text</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10121
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10122
         Expands the outermost JSON object into a set of key/value pairs. The
1 by Martin Pitt
Import upstream version 9.3~beta1
10123
         returned value will be of type text.
10124
       </entry>
10125
       <entry><literal>select * from json_each_text('{"a":"foo", "b":"bar"}')</literal></entry>
10126
       <entry>
10127
<programlisting>
10128
 key | value
10129
-----+-------
10130
 a   | foo
10131
 b   | bar
10132
 </programlisting>
10133
       </entry>
10134
      </row>
10135
      <row>
10136
       <entry>
10137
         <indexterm>
10138
          <primary>json_extract_path</primary>
10139
         </indexterm>
10140
         <literal>json_extract_path(from_json json, VARIADIC path_elems text[])</literal>
10141
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10142
       <entry><type>json</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10143
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10144
         Returns JSON object pointed to by <parameter>path_elems</parameter>.
1 by Martin Pitt
Import upstream version 9.3~beta1
10145
       </entry>
10146
       <entry><literal>json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4')</literal></entry>
10147
       <entry><literal>{"f5":99,"f6":"foo"}</literal></entry>
10148
      </row>
10149
      <row>
10150
       <entry>
10151
         <indexterm>
10152
          <primary>json_extract_path_text</primary>
10153
         </indexterm>
10154
         <literal>json_extract_path_text(from_json json, VARIADIC path_elems text[])</literal>
10155
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10156
       <entry><type>text</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10157
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10158
         Returns JSON object pointed to by <parameter>path_elems</parameter>.
1 by Martin Pitt
Import upstream version 9.3~beta1
10159
       </entry>
10160
       <entry><literal>json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4', 'f6')</literal></entry>
10161
       <entry><literal>foo</literal></entry>
10162
      </row>
10163
      <row>
10164
       <entry>
10165
         <indexterm>
10166
          <primary>json_object_keys</primary>
10167
         </indexterm>
10168
         <literal>json_object_keys(json)</literal>
10169
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10170
       <entry><type>SETOF text</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10171
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10172
          Returns set of keys in the JSON object.  Only the <quote>outer</quote> object will be displayed.
1 by Martin Pitt
Import upstream version 9.3~beta1
10173
       </entry>
10174
       <entry><literal>json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')</literal></entry>
10175
       <entry>
10176
<programlisting>
10177
 json_object_keys
10178
------------------
10179
 f1
10180
 f2
10181
</programlisting>
10182
       </entry>
10183
      </row>
10184
      <row>
10185
       <entry>
10186
         <indexterm>
10187
          <primary>json_populate_record</primary>
10188
         </indexterm>
10189
         <literal>json_populate_record(base anyelement, from_json json, [, use_json_as_text bool=false]</literal>
10190
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10191
       <entry><type>anyelement</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10192
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10193
         Expands the object in <replaceable>from_json</replaceable> to a row whose columns match
1 by Martin Pitt
Import upstream version 9.3~beta1
10194
         the record type defined by base. Conversion will be best
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10195
         effort; columns in base with no corresponding key in <replaceable>from_json</replaceable>
1.1.4 by Martin Pitt
Import upstream version 9.3.1
10196
         will be left null. If a column is specified more than once, the last value is used.
1 by Martin Pitt
Import upstream version 9.3~beta1
10197
       </entry>
10198
       <entry><literal>select * from json_populate_record(null::x, '{"a":1,"b":2}')</literal></entry>
10199
       <entry>
10200
<programlisting>
10201
 a | b
10202
---+---
10203
 1 | 2
10204
</programlisting>
10205
       </entry>
10206
      </row>
10207
      <row>
10208
       <entry>
10209
         <indexterm>
10210
          <primary>json_populate_recordset</primary>
10211
         </indexterm>
10212
         <literal>json_populate_recordset(base anyelement, from_json json, [, use_json_as_text bool=false]</literal>
10213
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10214
       <entry><type>SETOF anyelement</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10215
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10216
         Expands the outermost set of objects in <replaceable>from_json</replaceable> to a set
1 by Martin Pitt
Import upstream version 9.3~beta1
10217
         whose columns match the record type defined by base.
10218
         Conversion will be best effort; columns in base with no
1.1.4 by Martin Pitt
Import upstream version 9.3.1
10219
         corresponding key in <replaceable>from_json</replaceable> will be left null.
10220
         If a column is specified more than once, the last value is used.
1 by Martin Pitt
Import upstream version 9.3~beta1
10221
       </entry>
10222
       <entry><literal>select * from json_populate_recordset(null::x, '[{"a":1,"b":2},{"a":3,"b":4}]')</literal></entry>
10223
       <entry>
10224
<programlisting>
10225
 a | b
10226
---+---
10227
 1 | 2
10228
 3 | 4
10229
 </programlisting>
10230
       </entry>
10231
      </row>
10232
      <row>
10233
       <entry>
10234
         <indexterm>
10235
          <primary>json_array_elements</primary>
10236
         </indexterm>
10237
         <literal>json_array_elements(json)</literal>
10238
       </entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10239
       <entry><type>SETOF json</type></entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
10240
       <entry>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10241
         Expands a JSON array to a set of JSON elements.
1 by Martin Pitt
Import upstream version 9.3~beta1
10242
       </entry>
10243
       <entry><literal>json_array_elements('[1,true, [2,false]]')</literal></entry>
10244
       <entry>
10245
<programlisting>
10246
   value
10247
-----------
10248
 1
10249
 true
10250
 [2,false]
10251
</programlisting>
10252
       </entry>
10253
      </row>
10254
     </tbody>
10255
    </tgroup>
10256
   </table>
10257
10258
  <note>
10259
    <para>
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10260
      The <type>json</type> functions and operators can impose stricter validity requirements
10261
      than the type's input functions. In particular, they check much more closely that any use
10262
      of Unicode surrogate pairs to designate characters outside the Unicode Basic Multilingual
10263
      Plane is correct.
10264
    </para>
10265
  </note>
10266
10267
  <note>
10268
    <para>
10269
      Many of these functions and operators will convert Unicode escapes
10270
      in the JSON text to the appropriate UTF8 character when the database encoding is UTF8. In
10271
      other encodings the escape sequence must be for an ASCII character, and any other code point
10272
      in a Unicode escape sequence will result in an error.
10273
      In general, it is best to avoid mixing Unicode escapes in JSON with a non-UTF8 database
10274
      encoding, if possible.
10275
    </para>
10276
  </note>
10277
10278
  <note>
10279
    <para>
10280
      The <xref linkend="hstore"> extension has a cast from <type>hstore</type> to
10281
      <type>json</type>, so that converted <type>hstore</type> values are represented as JSON objects,
1 by Martin Pitt
Import upstream version 9.3~beta1
10282
      not as string values.
10283
    </para>
10284
  </note>
10285
10286
  <para>
10287
    See also <xref linkend="functions-aggregate"> about the aggregate
10288
    function <function>json_agg</function> which aggregates record
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
10289
    values as JSON efficiently.
1 by Martin Pitt
Import upstream version 9.3~beta1
10290
  </para>
10291
 </sect1>
10292
10293
 <sect1 id="functions-sequence">
10294
  <title>Sequence Manipulation Functions</title>
10295
10296
  <indexterm>
10297
   <primary>sequence</primary>
10298
  </indexterm>
10299
  <indexterm>
10300
   <primary>nextval</primary>
10301
  </indexterm>
10302
  <indexterm>
10303
   <primary>currval</primary>
10304
  </indexterm>
10305
  <indexterm>
10306
   <primary>lastval</primary>
10307
  </indexterm>
10308
  <indexterm>
10309
   <primary>setval</primary>
10310
  </indexterm>
10311
10312
  <para>
1.1.2 by Martin Pitt
Import upstream version 9.3~rc1
10313
   This section describes functions for operating on <firstterm>sequence
10314
   objects</firstterm>, also called sequence generators or just sequences.
10315
   Sequence objects are special single-row tables created with <xref
1 by Martin Pitt
Import upstream version 9.3~beta1
10316
   linkend="sql-createsequence">.
1.1.2 by Martin Pitt
Import upstream version 9.3~rc1
10317
   Sequence objects are commonly used to generate unique identifiers
1 by Martin Pitt
Import upstream version 9.3~beta1
10318
   for rows of a table.  The sequence functions, listed in <xref
10319
   linkend="functions-sequence-table">, provide simple, multiuser-safe
10320
   methods for obtaining successive sequence values from sequence
10321
   objects.
10322
  </para>
10323
10324
   <table id="functions-sequence-table">
10325
    <title>Sequence Functions</title>
10326
    <tgroup cols="3">
10327
     <thead>
10328
      <row><entry>Function</entry> <entry>Return Type</entry> <entry>Description</entry></row>
10329
     </thead>
10330
10331
     <tbody>
10332
      <row>
10333
        <entry><literal><function>currval(<type>regclass</type>)</function></literal></entry>
10334
        <entry><type>bigint</type></entry>
10335
        <entry>Return value most recently obtained with
10336
        <function>nextval</function> for specified sequence</entry>
10337
      </row>
10338
      <row>
10339
        <entry><literal><function>lastval()</function></literal></entry>
10340
        <entry><type>bigint</type></entry>
10341
        <entry>Return value most recently obtained with
10342
        <function>nextval</function> for any sequence</entry>
10343
      </row>
10344
      <row>
10345
        <entry><literal><function>nextval(<type>regclass</type>)</function></literal></entry>
10346
        <entry><type>bigint</type></entry>
10347
        <entry>Advance sequence and return new value</entry>
10348
      </row>
10349
      <row>
10350
        <entry><literal><function>setval(<type>regclass</type>, <type>bigint</type>)</function></literal></entry>
10351
        <entry><type>bigint</type></entry>
10352
        <entry>Set sequence's current value</entry>
10353
      </row>
10354
      <row>
10355
        <entry><literal><function>setval(<type>regclass</type>, <type>bigint</type>, <type>boolean</type>)</function></literal></entry>
10356
        <entry><type>bigint</type></entry>
10357
        <entry>Set sequence's current value and <literal>is_called</literal> flag</entry>
10358
      </row>
10359
     </tbody>
10360
    </tgroup>
10361
   </table>
10362
10363
  <para>
10364
   The sequence to be operated on by a sequence function is specified by
10365
   a <type>regclass</> argument, which is simply the OID of the sequence in the
10366
   <structname>pg_class</> system catalog.  You do not have to look up the
10367
   OID by hand, however, since the <type>regclass</> data type's input
10368
   converter will do the work for you.  Just write the sequence name enclosed
10369
   in single quotes so that it looks like a literal constant.  For
10370
   compatibility with the handling of ordinary
10371
   <acronym>SQL</acronym> names, the string will be converted to lower case
10372
   unless it contains double quotes around the sequence name.  Thus:
10373
<programlisting>
10374
nextval('foo')      <lineannotation>operates on sequence <literal>foo</literal></>
10375
nextval('FOO')      <lineannotation>operates on sequence <literal>foo</literal></>
10376
nextval('"Foo"')    <lineannotation>operates on sequence <literal>Foo</literal></>
10377
</programlisting>
10378
   The sequence name can be schema-qualified if necessary:
10379
<programlisting>
10380
nextval('myschema.foo')     <lineannotation>operates on <literal>myschema.foo</literal></>
10381
nextval('"myschema".foo')   <lineannotation>same as above</lineannotation>
10382
nextval('foo')              <lineannotation>searches search path for <literal>foo</literal></>
10383
</programlisting>
10384
   See <xref linkend="datatype-oid"> for more information about
10385
   <type>regclass</>.
10386
  </para>
10387
10388
  <note>
10389
   <para>
10390
    Before <productname>PostgreSQL</productname> 8.1, the arguments of the
10391
    sequence functions were of type <type>text</>, not <type>regclass</>, and
10392
    the above-described conversion from a text string to an OID value would
10393
    happen at run time during each call.  For backward compatibility, this
10394
    facility still exists, but internally it is now handled as an implicit
10395
    coercion from <type>text</> to <type>regclass</> before the function is
10396
    invoked.
10397
   </para>
10398
10399
   <para>
10400
    When you write the argument of a sequence function as an unadorned
10401
    literal string, it becomes a constant of type <type>regclass</>.
10402
    Since this is really just an OID, it will track the originally
10403
    identified sequence despite later renaming, schema reassignment,
10404
    etc.  This <quote>early binding</> behavior is usually desirable for
10405
    sequence references in column defaults and views.  But sometimes you might
10406
    want <quote>late binding</> where the sequence reference is resolved
10407
    at run time.  To get late-binding behavior, force the constant to be
10408
    stored as a <type>text</> constant instead of <type>regclass</>:
10409
<programlisting>
10410
nextval('foo'::text)      <lineannotation><literal>foo</literal> is looked up at runtime</>
10411
</programlisting>
10412
    Note that late binding was the only behavior supported in
10413
    <productname>PostgreSQL</productname> releases before 8.1, so you
10414
    might need to do this to preserve the semantics of old applications.
10415
   </para>
10416
10417
   <para>
10418
    Of course, the argument of a sequence function can be an expression
10419
    as well as a constant.  If it is a text expression then the implicit
10420
    coercion will result in a run-time lookup.
10421
   </para>
10422
  </note>
10423
10424
  <para>
10425
   The available sequence functions are:
10426
10427
    <variablelist>
10428
     <varlistentry>
10429
      <term><function>nextval</function></term>
10430
      <listitem>
10431
       <para>
10432
        Advance the sequence object to its next value and return that
10433
        value.  This is done atomically: even if multiple sessions
10434
        execute <function>nextval</function> concurrently, each will safely receive
10435
        a distinct sequence value.
10436
       </para>
10437
10438
       <para>
10439
        If a sequence object has been created with default parameters,
10440
        successive <function>nextval</function> calls will return successive
10441
        values beginning with 1.  Other behaviors can be obtained by using
10442
        special parameters in the <xref linkend="sql-createsequence"> command;
10443
        see its command reference page for more information.
10444
       </para>
10445
10446
       <important>
10447
        <para>
10448
         To avoid blocking concurrent transactions that obtain numbers from the
10449
         same sequence, a <function>nextval</function> operation is never
10450
         rolled back; that is, once a value has been fetched it is considered
10451
         used, even if the transaction that did the
10452
         <function>nextval</function> later aborts.  This means that aborted
10453
         transactions might leave unused <quote>holes</quote> in the sequence
10454
         of assigned values.
10455
        </para>
10456
       </important>
10457
10458
      </listitem>
10459
     </varlistentry>
10460
10461
     <varlistentry>
10462
      <term><function>currval</function></term>
10463
      <listitem>
10464
       <para>
10465
        Return the value most recently obtained by <function>nextval</function>
10466
        for this sequence in the current session.  (An error is
10467
        reported if <function>nextval</function> has never been called for this
10468
        sequence in this session.)  Because this is returning
10469
        a session-local value, it gives a predictable answer whether or not
10470
        other sessions have executed <function>nextval</function> since the
10471
        current session did.
10472
       </para>
10473
      </listitem>
10474
     </varlistentry>
10475
10476
     <varlistentry>
10477
      <term><function>lastval</function></term>
10478
      <listitem>
10479
       <para>
10480
        Return the value most recently returned by
10481
        <function>nextval</> in the current session. This function is
10482
        identical to <function>currval</function>, except that instead
10483
        of taking the sequence name as an argument it fetches the
10484
        value of the last sequence used by <function>nextval</function>
10485
        in the current session. It is an error to call
10486
        <function>lastval</function> if <function>nextval</function>
10487
        has not yet been called in the current session.
10488
       </para>
10489
      </listitem>
10490
     </varlistentry>
10491
10492
     <varlistentry>
10493
      <term><function>setval</function></term>
10494
      <listitem>
10495
       <para>
10496
        Reset the sequence object's counter value.  The two-parameter
10497
        form sets the sequence's <literal>last_value</literal> field to the
10498
        specified value and sets its <literal>is_called</literal> field to
10499
        <literal>true</literal>, meaning that the next
10500
        <function>nextval</function> will advance the sequence before
10501
        returning a value.  The value reported by <function>currval</> is
10502
        also set to the specified value.  In the three-parameter form,
10503
        <literal>is_called</literal> can be set to either <literal>true</literal>
10504
        or <literal>false</literal>.  <literal>true</> has the same effect as
10505
        the two-parameter form. If it is set to <literal>false</literal>, the
10506
        next <function>nextval</function> will return exactly the specified
10507
        value, and sequence advancement commences with the following
10508
        <function>nextval</function>.  Furthermore, the value reported by
10509
        <function>currval</> is not changed in this case (this is a change
10510
        from pre-8.3 behavior).  For example,
10511
10512
<screen>
10513
SELECT setval('foo', 42);           <lineannotation>Next <function>nextval</> will return 43</lineannotation>
10514
SELECT setval('foo', 42, true);     <lineannotation>Same as above</lineannotation>
10515
SELECT setval('foo', 42, false);    <lineannotation>Next <function>nextval</> will return 42</lineannotation>
10516
</screen>
10517
10518
        The result returned by <function>setval</function> is just the value of its
10519
        second argument.
10520
       </para>
10521
       <important>
10522
        <para>
10523
         Because sequences are non-transactional, changes made by
10524
         <function>setval</function> are not undone if the transaction rolls
10525
         back.
10526
        </para>
10527
       </important>
10528
      </listitem>
10529
     </varlistentry>
10530
    </variablelist>
10531
  </para>
10532
10533
 </sect1>
10534
10535
10536
 <sect1 id="functions-conditional">
10537
  <title>Conditional Expressions</title>
10538
10539
  <indexterm>
10540
   <primary>CASE</primary>
10541
  </indexterm>
10542
10543
  <indexterm>
10544
   <primary>conditional expression</primary>
10545
  </indexterm>
10546
10547
  <para>
10548
   This section describes the <acronym>SQL</acronym>-compliant conditional expressions
10549
   available in <productname>PostgreSQL</productname>.
10550
  </para>
10551
10552
  <tip>
10553
   <para>
10554
    If your needs go beyond the capabilities of these conditional
10555
    expressions, you might want to consider writing a stored procedure
10556
    in a more expressive programming language.
10557
   </para>
10558
  </tip>
10559
10560
  <sect2 id="functions-case">
10561
   <title><literal>CASE</></title>
10562
10563
  <para>
10564
   The <acronym>SQL</acronym> <token>CASE</token> expression is a
10565
   generic conditional expression, similar to if/else statements in
10566
   other programming languages:
10567
10568
<synopsis>
10569
CASE WHEN <replaceable>condition</replaceable> THEN <replaceable>result</replaceable>
10570
     <optional>WHEN ...</optional>
10571
     <optional>ELSE <replaceable>result</replaceable></optional>
10572
END
10573
</synopsis>
10574
10575
   <token>CASE</token> clauses can be used wherever
10576
   an expression is valid.  Each <replaceable>condition</replaceable> is an
10577
   expression that returns a <type>boolean</type> result.  If the condition's
10578
   result is true, the value of the <token>CASE</token> expression is the
10579
   <replaceable>result</replaceable> that follows the condition, and the
10580
   remainder of the <token>CASE</token> expression is not processed.  If the
10581
   condition's result is not true, any subsequent <token>WHEN</token> clauses
10582
   are examined in the same manner.  If no <token>WHEN</token>
10583
   <replaceable>condition</replaceable> yields true, the value of the
10584
   <token>CASE</> expression is the <replaceable>result</replaceable> of the
10585
   <token>ELSE</token> clause.  If the <token>ELSE</token> clause is
10586
   omitted and no condition is true, the result is null.
10587
  </para>
10588
10589
   <para>
10590
    An example:
10591
<screen>
10592
SELECT * FROM test;
10593
10594
 a
10595
---
10596
 1
10597
 2
10598
 3
10599
10600
10601
SELECT a,
10602
       CASE WHEN a=1 THEN 'one'
10603
            WHEN a=2 THEN 'two'
10604
            ELSE 'other'
10605
       END
10606
    FROM test;
10607
10608
 a | case
10609
---+-------
10610
 1 | one
10611
 2 | two
10612
 3 | other
10613
</screen>
10614
   </para>
10615
10616
  <para>
10617
   The data types of all the <replaceable>result</replaceable>
10618
   expressions must be convertible to a single output type.
10619
   See <xref linkend="typeconv-union-case"> for more details.
10620
  </para>
10621
10622
  <para>
10623
   There is a <quote>simple</> form of <token>CASE</token> expression
10624
   that is a variant of the general form above:
10625
10626
<synopsis>
10627
CASE <replaceable>expression</replaceable>
10628
    WHEN <replaceable>value</replaceable> THEN <replaceable>result</replaceable>
10629
    <optional>WHEN ...</optional>
10630
    <optional>ELSE <replaceable>result</replaceable></optional>
10631
END
10632
</synopsis>
10633
10634
   The first
10635
   <replaceable>expression</replaceable> is computed, then compared to
10636
   each of the <replaceable>value</replaceable> expressions in the
10637
   <token>WHEN</token> clauses until one is found that is equal to it.  If
10638
   no match is found, the <replaceable>result</replaceable> of the
10639
   <token>ELSE</token> clause (or a null value) is returned.  This is similar
10640
   to the <function>switch</function> statement in C.
10641
  </para>
10642
10643
   <para>
10644
    The example above can be written using the simple
10645
    <token>CASE</token> syntax:
10646
<screen>
10647
SELECT a,
10648
       CASE a WHEN 1 THEN 'one'
10649
              WHEN 2 THEN 'two'
10650
              ELSE 'other'
10651
       END
10652
    FROM test;
10653
10654
 a | case
10655
---+-------
10656
 1 | one
10657
 2 | two
10658
 3 | other
10659
</screen>
10660
   </para>
10661
10662
   <para>
10663
    A <token>CASE</token> expression does not evaluate any subexpressions
10664
    that are not needed to determine the result.  For example, this is a
10665
    possible way of avoiding a division-by-zero failure:
10666
<programlisting>
10667
SELECT ... WHERE CASE WHEN x &lt;&gt; 0 THEN y/x &gt; 1.5 ELSE false END;
10668
</programlisting>
10669
   </para>
1.1.2 by Martin Pitt
Import upstream version 9.3~rc1
10670
10671
   <note>
10672
    <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
10673
     As described in <xref linkend="syntax-express-eval">, there are various
10674
     situations in which subexpressions of an expression are evaluated at
10675
     different times, so that the principle that <quote><token>CASE</token>
10676
     evaluates only necessary subexpressions</quote> is not ironclad.  For
10677
     example a constant <literal>1/0</> subexpression will usually result in
10678
     a division-by-zero failure at planning time, even if it's within
10679
     a <token>CASE</token> arm that would never be entered at run time.
1.1.2 by Martin Pitt
Import upstream version 9.3~rc1
10680
    </para>
10681
   </note>
1 by Martin Pitt
Import upstream version 9.3~beta1
10682
  </sect2>
10683
10684
  <sect2 id="functions-coalesce-nvl-ifnull">
10685
   <title><literal>COALESCE</></title>
10686
10687
  <indexterm>
10688
   <primary>COALESCE</primary>
10689
  </indexterm>
10690
10691
  <indexterm>
10692
   <primary>NVL</primary>
10693
  </indexterm>
10694
10695
  <indexterm>
10696
   <primary>IFNULL</primary>
10697
  </indexterm>
10698
10699
<synopsis>
10700
<function>COALESCE</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
10701
</synopsis>
10702
10703
  <para>
10704
   The <function>COALESCE</function> function returns the first of its
10705
   arguments that is not null.  Null is returned only if all arguments
10706
   are null.  It is often used to substitute a default value for
10707
   null values when data is retrieved for display, for example:
10708
<programlisting>
10709
SELECT COALESCE(description, short_description, '(none)') ...
10710
</programlisting>
10711
   This returns <varname>description</> if it is not null, otherwise
10712
   <varname>short_description</> if it is not null, otherwise <literal>(none)</>.
10713
  </para>
10714
10715
   <para>
10716
    Like a <token>CASE</token> expression, <function>COALESCE</function> only
10717
    evaluates the arguments that are needed to determine the result;
10718
    that is, arguments to the right of the first non-null argument are
10719
    not evaluated.  This SQL-standard function provides capabilities similar
10720
    to <function>NVL</> and <function>IFNULL</>, which are used in some other
10721
    database systems.
10722
   </para>
10723
  </sect2>
10724
10725
  <sect2 id="functions-nullif">
10726
   <title><literal>NULLIF</></title>
10727
10728
  <indexterm>
10729
   <primary>NULLIF</primary>
10730
  </indexterm>
10731
10732
<synopsis>
10733
<function>NULLIF</function>(<replaceable>value1</replaceable>, <replaceable>value2</replaceable>)
10734
</synopsis>
10735
10736
  <para>
10737
   The <function>NULLIF</function> function returns a null value if
10738
   <replaceable>value1</replaceable> equals <replaceable>value2</replaceable>;
10739
   otherwise it returns <replaceable>value1</replaceable>.
10740
   This can be used to perform the inverse operation of the
10741
   <function>COALESCE</function> example given above:
10742
<programlisting>
10743
SELECT NULLIF(value, '(none)') ...
10744
</programlisting>
10745
  </para>
10746
  <para>
10747
   In this example, if <literal>value</literal> is <literal>(none)</>,
10748
   null is returned, otherwise the value of <literal>value</literal>
10749
   is returned.
10750
  </para>
10751
10752
  </sect2>
10753
10754
  <sect2 id="functions-greatest-least">
10755
   <title><literal>GREATEST</literal> and <literal>LEAST</literal></title>
10756
10757
  <indexterm>
10758
   <primary>GREATEST</primary>
10759
  </indexterm>
10760
  <indexterm>
10761
   <primary>LEAST</primary>
10762
  </indexterm>
10763
10764
<synopsis>
10765
<function>GREATEST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
10766
</synopsis>
10767
<synopsis>
10768
<function>LEAST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
10769
</synopsis>
10770
10771
   <para>
10772
    The <function>GREATEST</> and <function>LEAST</> functions select the
10773
    largest or smallest value from a list of any number of expressions.
10774
    The expressions must all be convertible to a common data type, which
10775
    will be the type of the result
10776
    (see <xref linkend="typeconv-union-case"> for details).  NULL values
10777
    in the list are ignored.  The result will be NULL only if all the
10778
    expressions evaluate to NULL.
10779
   </para>
10780
10781
   <para>
10782
    Note that <function>GREATEST</> and <function>LEAST</> are not in
10783
    the SQL standard, but are a common extension.  Some other databases
10784
    make them return NULL if any argument is NULL, rather than only when
10785
    all are NULL.
10786
   </para>
10787
  </sect2>
10788
 </sect1>
10789
10790
 <sect1 id="functions-array">
10791
  <title>Array Functions and Operators</title>
10792
10793
  <para>
10794
   <xref linkend="array-operators-table"> shows the operators
10795
   available for array types.
10796
  </para>
10797
10798
    <table id="array-operators-table">
10799
     <title>Array Operators</title>
10800
     <tgroup cols="4">
10801
      <thead>
10802
       <row>
10803
        <entry>Operator</entry>
10804
        <entry>Description</entry>
10805
        <entry>Example</entry>
10806
        <entry>Result</entry>
10807
       </row>
10808
      </thead>
10809
      <tbody>
10810
       <row>
10811
        <entry> <literal>=</literal> </entry>
10812
        <entry>equal</entry>
10813
        <entry><literal>ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3]</literal></entry>
10814
        <entry><literal>t</literal></entry>
10815
       </row>
10816
10817
       <row>
10818
        <entry> <literal>&lt;&gt;</literal> </entry>
10819
        <entry>not equal</entry>
10820
        <entry><literal>ARRAY[1,2,3] &lt;&gt; ARRAY[1,2,4]</literal></entry>
10821
        <entry><literal>t</literal></entry>
10822
       </row>
10823
10824
       <row>
10825
        <entry> <literal>&lt;</literal> </entry>
10826
        <entry>less than</entry>
10827
        <entry><literal>ARRAY[1,2,3] &lt; ARRAY[1,2,4]</literal></entry>
10828
        <entry><literal>t</literal></entry>
10829
       </row>
10830
10831
       <row>
10832
        <entry> <literal>&gt;</literal> </entry>
10833
        <entry>greater than</entry>
10834
        <entry><literal>ARRAY[1,4,3] &gt; ARRAY[1,2,4]</literal></entry>
10835
        <entry><literal>t</literal></entry>
10836
       </row>
10837
10838
       <row>
10839
        <entry> <literal>&lt;=</literal> </entry>
10840
        <entry>less than or equal</entry>
10841
        <entry><literal>ARRAY[1,2,3] &lt;= ARRAY[1,2,3]</literal></entry>
10842
        <entry><literal>t</literal></entry>
10843
       </row>
10844
10845
       <row>
10846
        <entry> <literal>&gt;=</literal> </entry>
10847
        <entry>greater than or equal</entry>
10848
        <entry><literal>ARRAY[1,4,3] &gt;= ARRAY[1,4,3]</literal></entry>
10849
        <entry><literal>t</literal></entry>
10850
       </row>
10851
10852
       <row>
10853
        <entry> <literal>@&gt;</literal> </entry>
10854
        <entry>contains</entry>
10855
        <entry><literal>ARRAY[1,4,3] @&gt; ARRAY[3,1]</literal></entry>
10856
        <entry><literal>t</literal></entry>
10857
       </row>
10858
10859
       <row>
10860
        <entry> <literal>&lt;@</literal> </entry>
10861
        <entry>is contained by</entry>
10862
        <entry><literal>ARRAY[2,7] &lt;@ ARRAY[1,7,4,2,6]</literal></entry>
10863
        <entry><literal>t</literal></entry>
10864
       </row>
10865
10866
       <row>
10867
        <entry> <literal>&amp;&amp;</literal> </entry>
10868
        <entry>overlap (have elements in common)</entry>
10869
        <entry><literal>ARRAY[1,4,3] &amp;&amp; ARRAY[2,1]</literal></entry>
10870
        <entry><literal>t</literal></entry>
10871
       </row>
10872
10873
       <row>
10874
        <entry> <literal>||</literal> </entry>
10875
        <entry>array-to-array concatenation</entry>
10876
        <entry><literal>ARRAY[1,2,3] || ARRAY[4,5,6]</literal></entry>
10877
        <entry><literal>{1,2,3,4,5,6}</literal></entry>
10878
       </row>
10879
10880
       <row>
10881
        <entry> <literal>||</literal> </entry>
10882
        <entry>array-to-array concatenation</entry>
10883
        <entry><literal>ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9]]</literal></entry>
10884
        <entry><literal>{{1,2,3},{4,5,6},{7,8,9}}</literal></entry>
10885
       </row>
10886
10887
       <row>
10888
        <entry> <literal>||</literal> </entry>
10889
        <entry>element-to-array concatenation</entry>
10890
        <entry><literal>3 || ARRAY[4,5,6]</literal></entry>
10891
        <entry><literal>{3,4,5,6}</literal></entry>
10892
       </row>
10893
10894
       <row>
10895
        <entry> <literal>||</literal> </entry>
10896
        <entry>array-to-element concatenation</entry>
10897
        <entry><literal>ARRAY[4,5,6] || 7</literal></entry>
10898
        <entry><literal>{4,5,6,7}</literal></entry>
10899
       </row>
10900
      </tbody>
10901
     </tgroup>
10902
    </table>
10903
10904
  <para>
10905
   Array comparisons compare the array contents element-by-element,
10906
   using the default B-tree comparison function for the element data type.
10907
   In multidimensional arrays the elements are visited in row-major order
10908
   (last subscript varies most rapidly).
10909
   If the contents of two arrays are equal but the dimensionality is
10910
   different, the first difference in the dimensionality information
10911
   determines the sort order.  (This is a change from versions of
10912
   <productname>PostgreSQL</> prior to 8.2: older versions would claim
10913
   that two arrays with the same contents were equal, even if the
10914
   number of dimensions or subscript ranges were different.)
10915
  </para>
10916
10917
  <para>
10918
   See <xref linkend="arrays"> for more details about array operator
10919
   behavior.  See <xref linkend="indexes-types"> for more details about
10920
   which operators support indexed operations.
10921
  </para>
10922
10923
  <para>
10924
   <xref linkend="array-functions-table"> shows the functions
10925
   available for use with array types. See <xref linkend="arrays">
10926
   for more information  and examples of the use of these functions.
10927
  </para>
10928
10929
  <indexterm>
10930
    <primary>array_append</primary>
10931
  </indexterm>
10932
  <indexterm>
10933
    <primary>array_cat</primary>
10934
  </indexterm>
10935
  <indexterm>
10936
    <primary>array_ndims</primary>
10937
  </indexterm>
10938
  <indexterm>
10939
    <primary>array_dims</primary>
10940
  </indexterm>
10941
  <indexterm>
10942
    <primary>array_fill</primary>
10943
  </indexterm>
10944
  <indexterm>
10945
    <primary>array_length</primary>
10946
  </indexterm>
10947
  <indexterm>
10948
    <primary>array_lower</primary>
10949
  </indexterm>
10950
  <indexterm>
10951
    <primary>array_prepend</primary>
10952
  </indexterm>
10953
  <indexterm>
10954
    <primary>array_remove</primary>
10955
  </indexterm>
10956
  <indexterm>
10957
    <primary>array_replace</primary>
10958
  </indexterm>
10959
  <indexterm>
10960
    <primary>array_to_string</primary>
10961
  </indexterm>
10962
 <indexterm>
10963
    <primary>array_upper</primary>
10964
  </indexterm>
10965
  <indexterm>
10966
    <primary>string_to_array</primary>
10967
  </indexterm>
10968
  <indexterm>
10969
    <primary>unnest</primary>
10970
  </indexterm>
10971
10972
    <table id="array-functions-table">
10973
     <title>Array Functions</title>
10974
     <tgroup cols="5">
10975
      <thead>
10976
       <row>
10977
        <entry>Function</entry>
10978
        <entry>Return Type</entry>
10979
        <entry>Description</entry>
10980
        <entry>Example</entry>
10981
        <entry>Result</entry>
10982
       </row>
10983
      </thead>
10984
      <tbody>
10985
       <row>
10986
        <entry>
10987
         <literal>
10988
          <function>array_append</function>(<type>anyarray</type>, <type>anyelement</type>)
10989
         </literal>
10990
        </entry>
10991
        <entry><type>anyarray</type></entry>
10992
        <entry>append an element to the end of an array</entry>
10993
        <entry><literal>array_append(ARRAY[1,2], 3)</literal></entry>
10994
        <entry><literal>{1,2,3}</literal></entry>
10995
       </row>
10996
       <row>
10997
        <entry>
10998
         <literal>
10999
          <function>array_cat</function>(<type>anyarray</type>, <type>anyarray</type>)
11000
         </literal>
11001
        </entry>
11002
        <entry><type>anyarray</type></entry>
11003
        <entry>concatenate two arrays</entry>
11004
        <entry><literal>array_cat(ARRAY[1,2,3], ARRAY[4,5])</literal></entry>
11005
        <entry><literal>{1,2,3,4,5}</literal></entry>
11006
       </row>
11007
       <row>
11008
        <entry>
11009
         <literal>
11010
          <function>array_ndims</function>(<type>anyarray</type>)
11011
         </literal>
11012
        </entry>
11013
        <entry><type>int</type></entry>
11014
        <entry>returns the number of dimensions of the array</entry>
11015
        <entry><literal>array_ndims(ARRAY[[1,2,3], [4,5,6]])</literal></entry>
11016
        <entry><literal>2</literal></entry>
11017
       </row>
11018
       <row>
11019
        <entry>
11020
         <literal>
11021
          <function>array_dims</function>(<type>anyarray</type>)
11022
         </literal>
11023
        </entry>
11024
        <entry><type>text</type></entry>
11025
        <entry>returns a text representation of array's dimensions</entry>
11026
        <entry><literal>array_dims(ARRAY[[1,2,3], [4,5,6]])</literal></entry>
11027
        <entry><literal>[1:2][1:3]</literal></entry>
11028
       </row>
11029
       <row>
11030
        <entry>
11031
         <literal>
11032
          <function>array_fill</function>(<type>anyelement</type>, <type>int[]</type>,
11033
          <optional>, <type>int[]</type></optional>)
11034
         </literal>
11035
        </entry>
11036
        <entry><type>anyarray</type></entry>
11037
        <entry>returns an array initialized with supplied value and
11038
         dimensions, optionally with lower bounds other than 1</entry>
11039
        <entry><literal>array_fill(7, ARRAY[3], ARRAY[2])</literal></entry>
11040
        <entry><literal>[2:4]={7,7,7}</literal></entry>
11041
       </row>
11042
       <row>
11043
        <entry>
11044
         <literal>
11045
          <function>array_length</function>(<type>anyarray</type>, <type>int</type>)
11046
         </literal>
11047
        </entry>
11048
        <entry><type>int</type></entry>
11049
        <entry>returns the length of the requested array dimension</entry>
11050
        <entry><literal>array_length(array[1,2,3], 1)</literal></entry>
11051
        <entry><literal>3</literal></entry>
11052
       </row>
11053
       <row>
11054
        <entry>
11055
         <literal>
11056
          <function>array_lower</function>(<type>anyarray</type>, <type>int</type>)
11057
         </literal>
11058
        </entry>
11059
        <entry><type>int</type></entry>
11060
        <entry>returns lower bound of the requested array dimension</entry>
11061
        <entry><literal>array_lower('[0:2]={1,2,3}'::int[], 1)</literal></entry>
11062
        <entry><literal>0</literal></entry>
11063
       </row>
11064
       <row>
11065
        <entry>
11066
         <literal>
11067
          <function>array_prepend</function>(<type>anyelement</type>, <type>anyarray</type>)
11068
         </literal>
11069
        </entry>
11070
        <entry><type>anyarray</type></entry>
11071
        <entry>append an element to the beginning of an array</entry>
11072
        <entry><literal>array_prepend(1, ARRAY[2,3])</literal></entry>
11073
        <entry><literal>{1,2,3}</literal></entry>
11074
       </row>
11075
       <row>
11076
        <entry>
11077
         <literal>
11078
          <function>array_remove</function>(<type>anyarray</type>, <type>anyelement</type>)
11079
         </literal>
11080
        </entry>
11081
        <entry><type>anyarray</type></entry>
11082
        <entry>remove all elements equal to the given value from the array
11083
         (array must be one-dimensional)</entry>
11084
        <entry><literal>array_remove(ARRAY[1,2,3,2], 2)</literal></entry>
11085
        <entry><literal>{1,3}</literal></entry>
11086
       </row>
11087
       <row>
11088
        <entry>
11089
         <literal>
11090
          <function>array_replace</function>(<type>anyarray</type>, <type>anyelement</type>, <type>anyelement</type>)
11091
         </literal>
11092
        </entry>
11093
        <entry><type>anyarray</type></entry>
11094
        <entry>replace each array element equal to the given value with a new value</entry>
11095
        <entry><literal>array_replace(ARRAY[1,2,5,4], 5, 3)</literal></entry>
11096
        <entry><literal>{1,2,3,4}</literal></entry>
11097
       </row>
11098
       <row>
11099
        <entry>
11100
         <literal>
11101
          <function>array_to_string</function>(<type>anyarray</type>, <type>text</type> <optional>, <type>text</type></optional>)
11102
         </literal>
11103
        </entry>
11104
        <entry><type>text</type></entry>
11105
        <entry>concatenates array elements using supplied delimiter and
11106
         optional null string</entry>
11107
        <entry><literal>array_to_string(ARRAY[1, 2, 3, NULL, 5], ',', '*')</literal></entry>
11108
        <entry><literal>1,2,3,*,5</literal></entry>
11109
       </row>
11110
       <row>
11111
        <entry>
11112
         <literal>
11113
          <function>array_upper</function>(<type>anyarray</type>, <type>int</type>)
11114
         </literal>
11115
        </entry>
11116
        <entry><type>int</type></entry>
11117
        <entry>returns upper bound of the requested array dimension</entry>
11118
        <entry><literal>array_upper(ARRAY[1,8,3,7], 1)</literal></entry>
11119
        <entry><literal>4</literal></entry>
11120
       </row>
11121
       <row>
11122
        <entry>
11123
         <literal>
11124
          <function>string_to_array</function>(<type>text</type>, <type>text</type> <optional>, <type>text</type></optional>)
11125
         </literal>
11126
        </entry>
11127
        <entry><type>text[]</type></entry>
11128
        <entry>splits string into array elements using supplied delimiter and
11129
         optional null string</entry>
11130
        <entry><literal>string_to_array('xx~^~yy~^~zz', '~^~', 'yy')</literal></entry>
11131
        <entry><literal>{xx,NULL,zz}</literal></entry>
11132
       </row>
11133
       <row>
11134
        <entry>
11135
         <literal>
11136
          <function>unnest</function>(<type>anyarray</type>)
11137
         </literal>
11138
        </entry>
11139
        <entry><type>setof anyelement</type></entry>
11140
        <entry>expand an array to a set of rows</entry>
11141
        <entry><literal>unnest(ARRAY[1,2])</literal></entry>
11142
        <entry><literallayout class="monospaced">1
11143
2</literallayout>(2 rows)</entry>
11144
       </row>
11145
      </tbody>
11146
     </tgroup>
11147
    </table>
11148
11149
   <para>
11150
    In <function>string_to_array</function>, if the delimiter parameter is
11151
    NULL, each character in the input string will become a separate element in
11152
    the resulting array.  If the delimiter is an empty string, then the entire
11153
    input string is returned as a one-element array.  Otherwise the input
11154
    string is split at each occurrence of the delimiter string.
11155
   </para>
11156
11157
   <para>
11158
    In <function>string_to_array</function>, if the null-string parameter
11159
    is omitted or NULL, none of the substrings of the input will be replaced
11160
    by NULL.
11161
    In <function>array_to_string</function>, if the null-string parameter
11162
    is omitted or NULL, any null elements in the array are simply skipped
11163
    and not represented in the output string.
11164
   </para>
11165
11166
   <note>
11167
    <para>
11168
     There are two differences in the behavior of <function>string_to_array</>
11169
     from pre-9.1 versions of <productname>PostgreSQL</>.
11170
     First, it will return an empty (zero-element) array rather than NULL when
11171
     the input string is of zero length.  Second, if the delimiter string is
11172
     NULL, the function splits the input into individual characters, rather
11173
     than returning NULL as before.
11174
    </para>
11175
   </note>
11176
11177
   <para>
11178
    See also <xref linkend="functions-aggregate"> about the aggregate
11179
    function <function>array_agg</function> for use with arrays.
11180
   </para>
11181
  </sect1>
11182
11183
 <sect1 id="functions-range">
11184
  <title>Range Functions and Operators</title>
11185
11186
  <para>
11187
   See <xref linkend="rangetypes"> for an overview of range types.
11188
  </para>
11189
11190
  <para>
11191
   <xref linkend="range-operators-table"> shows the operators
11192
   available for range types.
11193
  </para>
11194
11195
    <table id="range-operators-table">
11196
     <title>Range Operators</title>
11197
     <tgroup cols="4">
11198
      <thead>
11199
       <row>
11200
        <entry>Operator</entry>
11201
        <entry>Description</entry>
11202
        <entry>Example</entry>
11203
        <entry>Result</entry>
11204
       </row>
11205
      </thead>
11206
      <tbody>
11207
       <row>
11208
        <entry> <literal>=</literal> </entry>
11209
        <entry>equal</entry>
11210
        <entry><literal>int4range(1,5) = '[1,4]'::int4range</literal></entry>
11211
        <entry><literal>t</literal></entry>
11212
       </row>
11213
11214
       <row>
11215
        <entry> <literal>&lt;&gt;</literal> </entry>
11216
        <entry>not equal</entry>
11217
        <entry><literal>numrange(1.1,2.2) &lt;&gt; numrange(1.1,2.3)</literal></entry>
11218
        <entry><literal>t</literal></entry>
11219
       </row>
11220
11221
       <row>
11222
        <entry> <literal>&lt;</literal> </entry>
11223
        <entry>less than</entry>
11224
        <entry><literal>int4range(1,10) &lt; int4range(2,3)</literal></entry>
11225
        <entry><literal>t</literal></entry>
11226
       </row>
11227
11228
       <row>
11229
        <entry> <literal>&gt;</literal> </entry>
11230
        <entry>greater than</entry>
11231
        <entry><literal>int4range(1,10) &gt; int4range(1,5)</literal></entry>
11232
        <entry><literal>t</literal></entry>
11233
       </row>
11234
11235
       <row>
11236
        <entry> <literal>&lt;=</literal> </entry>
11237
        <entry>less than or equal</entry>
11238
        <entry><literal>numrange(1.1,2.2) &lt;= numrange(1.1,2.2)</literal></entry>
11239
        <entry><literal>t</literal></entry>
11240
       </row>
11241
11242
       <row>
11243
        <entry> <literal>&gt;=</literal> </entry>
11244
        <entry>greater than or equal</entry>
11245
        <entry><literal>numrange(1.1,2.2) &gt;= numrange(1.1,2.0)</literal></entry>
11246
        <entry><literal>t</literal></entry>
11247
       </row>
11248
11249
       <row>
11250
        <entry> <literal>@&gt;</literal> </entry>
11251
        <entry>contains range</entry>
11252
        <entry><literal>int4range(2,4) @&gt; int4range(2,3)</literal></entry>
11253
        <entry><literal>t</literal></entry>
11254
       </row>
11255
11256
       <row>
11257
        <entry> <literal>@&gt;</literal> </entry>
11258
        <entry>contains element</entry>
11259
        <entry><literal>'[2011-01-01,2011-03-01)'::tsrange @&gt; '2011-01-10'::timestamp</literal></entry>
11260
        <entry><literal>t</literal></entry>
11261
       </row>
11262
11263
       <row>
11264
        <entry> <literal>&lt;@</literal> </entry>
11265
        <entry>range is contained by</entry>
11266
        <entry><literal>int4range(2,4) &lt;@ int4range(1,7)</literal></entry>
11267
        <entry><literal>t</literal></entry>
11268
       </row>
11269
11270
       <row>
11271
        <entry> <literal>&lt;@</literal> </entry>
11272
        <entry>element is contained by</entry>
11273
        <entry><literal>42 &lt;@ int4range(1,7)</literal></entry>
11274
        <entry><literal>f</literal></entry>
11275
       </row>
11276
11277
       <row>
11278
        <entry> <literal>&amp;&amp;</literal> </entry>
11279
        <entry>overlap (have points in common)</entry>
11280
        <entry><literal>int8range(3,7) &amp;&amp; int8range(4,12)</literal></entry>
11281
        <entry><literal>t</literal></entry>
11282
       </row>
11283
11284
       <row>
11285
        <entry> <literal>&lt;&lt;</literal> </entry>
11286
        <entry>strictly left of</entry>
11287
        <entry><literal>int8range(1,10) &lt;&lt; int8range(100,110)</literal></entry>
11288
        <entry><literal>t</literal></entry>
11289
       </row>
11290
11291
       <row>
11292
        <entry> <literal>&gt;&gt;</literal> </entry>
11293
        <entry>strictly right of</entry>
11294
        <entry><literal>int8range(50,60) &gt;&gt; int8range(20,30)</literal></entry>
11295
        <entry><literal>t</literal></entry>
11296
       </row>
11297
11298
       <row>
11299
        <entry> <literal>&amp;&lt;</literal> </entry>
11300
        <entry>does not extend to the right of</entry>
11301
        <entry><literal>int8range(1,20) &amp;&lt; int8range(18,20)</literal></entry>
11302
        <entry><literal>t</literal></entry>
11303
       </row>
11304
11305
       <row>
11306
        <entry> <literal>&amp;&gt;</literal> </entry>
11307
        <entry>does not extend to the left of</entry>
11308
        <entry><literal>int8range(7,20) &amp;&gt; int8range(5,10)</literal></entry>
11309
        <entry><literal>t</literal></entry>
11310
       </row>
11311
11312
       <row>
11313
        <entry> <literal>-|-</literal> </entry>
11314
        <entry>is adjacent to</entry>
11315
        <entry><literal>numrange(1.1,2.2) -|- numrange(2.2,3.3)</literal></entry>
11316
        <entry><literal>t</literal></entry>
11317
       </row>
11318
11319
       <row>
11320
        <entry> <literal>+</literal> </entry>
11321
        <entry>union</entry>
11322
        <entry><literal>numrange(5,15) + numrange(10,20)</literal></entry>
11323
        <entry><literal>[5,20)</literal></entry>
11324
       </row>
11325
11326
       <row>
11327
        <entry> <literal>*</literal> </entry>
11328
        <entry>intersection</entry>
11329
        <entry><literal>int8range(5,15) * int8range(10,20)</literal></entry>
11330
        <entry><literal>[10,15)</literal></entry>
11331
       </row>
11332
11333
       <row>
11334
        <entry> <literal>-</literal> </entry>
11335
        <entry>difference</entry>
11336
        <entry><literal>int8range(5,15) - int8range(10,20)</literal></entry>
11337
        <entry><literal>[5,10)</literal></entry>
11338
       </row>
11339
11340
      </tbody>
11341
     </tgroup>
11342
    </table>
11343
11344
  <para>
11345
   The simple comparison operators <literal>&lt;</literal>,
11346
   <literal>&gt;</literal>, <literal>&lt;=</literal>, and
11347
   <literal>&gt;=</literal> compare the lower bounds first, and only if those
11348
   are equal, compare the upper bounds.  These comparisons are not usually
11349
   very useful for ranges, but are provided to allow B-tree indexes to be
11350
   constructed on ranges.
11351
  </para>
11352
11353
  <para>
11354
   The left-of/right-of/adjacent operators always return false when an empty
11355
   range is involved; that is, an empty range is not considered to be either
11356
   before or after any other range.
11357
  </para>
11358
11359
  <para>
11360
   The union and difference operators will fail if the resulting range would
11361
   need to contain two disjoint sub-ranges, as such a range cannot be
11362
   represented.
11363
  </para>
11364
11365
  <para>
11366
   <xref linkend="range-functions-table"> shows the functions
11367
   available for use with range types.
11368
  </para>
11369
11370
  <indexterm>
11371
    <primary>lower</primary>
11372
  </indexterm>
11373
  <indexterm>
11374
    <primary>upper</primary>
11375
  </indexterm>
11376
  <indexterm>
11377
    <primary>isempty</primary>
11378
  </indexterm>
11379
  <indexterm>
11380
    <primary>lower_inc</primary>
11381
  </indexterm>
11382
  <indexterm>
11383
    <primary>upper_inc</primary>
11384
  </indexterm>
11385
  <indexterm>
11386
    <primary>lower_inf</primary>
11387
  </indexterm>
11388
  <indexterm>
11389
    <primary>upper_inf</primary>
11390
  </indexterm>
11391
11392
    <table id="range-functions-table">
11393
     <title>Range Functions</title>
11394
     <tgroup cols="5">
11395
      <thead>
11396
       <row>
11397
        <entry>Function</entry>
11398
        <entry>Return Type</entry>
11399
        <entry>Description</entry>
11400
        <entry>Example</entry>
11401
        <entry>Result</entry>
11402
       </row>
11403
      </thead>
11404
      <tbody>
11405
       <row>
11406
        <entry>
11407
         <literal>
11408
          <function>lower</function>(<type>anyrange</type>)
11409
         </literal>
11410
        </entry>
11411
        <entry>range's element type</entry>
11412
        <entry>lower bound of range</entry>
11413
        <entry><literal>lower(numrange(1.1,2.2))</literal></entry>
11414
        <entry><literal>1.1</literal></entry>
11415
       </row>
11416
       <row>
11417
        <entry>
11418
         <literal>
11419
          <function>upper</function>(<type>anyrange</type>)
11420
         </literal>
11421
        </entry>
11422
        <entry>range's element type</entry>
11423
        <entry>upper bound of range</entry>
11424
        <entry><literal>upper(numrange(1.1,2.2))</literal></entry>
11425
        <entry><literal>2.2</literal></entry>
11426
       </row>
11427
       <row>
11428
        <entry>
11429
         <literal>
11430
          <function>isempty</function>(<type>anyrange</type>)
11431
         </literal>
11432
        </entry>
11433
        <entry><type>boolean</type></entry>
11434
        <entry>is the range empty?</entry>
11435
        <entry><literal>isempty(numrange(1.1,2.2))</literal></entry>
11436
        <entry><literal>false</literal></entry>
11437
       </row>
11438
       <row>
11439
        <entry>
11440
         <literal>
11441
          <function>lower_inc</function>(<type>anyrange</type>)
11442
         </literal>
11443
        </entry>
11444
        <entry><type>boolean</type></entry>
11445
        <entry>is the lower bound inclusive?</entry>
11446
        <entry><literal>lower_inc(numrange(1.1,2.2))</literal></entry>
11447
        <entry><literal>true</literal></entry>
11448
       </row>
11449
       <row>
11450
        <entry>
11451
         <literal>
11452
          <function>upper_inc</function>(<type>anyrange</type>)
11453
         </literal>
11454
        </entry>
11455
        <entry><type>boolean</type></entry>
11456
        <entry>is the upper bound inclusive?</entry>
11457
        <entry><literal>upper_inc(numrange(1.1,2.2))</literal></entry>
11458
        <entry><literal>false</literal></entry>
11459
       </row>
11460
       <row>
11461
        <entry>
11462
         <literal>
11463
          <function>lower_inf</function>(<type>anyrange</type>)
11464
         </literal>
11465
        </entry>
11466
        <entry><type>boolean</type></entry>
11467
        <entry>is the lower bound infinite?</entry>
11468
        <entry><literal>lower_inf('(,)'::daterange)</literal></entry>
11469
        <entry><literal>true</literal></entry>
11470
       </row>
11471
       <row>
11472
        <entry>
11473
         <literal>
11474
          <function>upper_inf</function>(<type>anyrange</type>)
11475
         </literal>
11476
        </entry>
11477
        <entry><type>boolean</type></entry>
11478
        <entry>is the upper bound infinite?</entry>
11479
        <entry><literal>upper_inf('(,)'::daterange)</literal></entry>
11480
        <entry><literal>true</literal></entry>
11481
       </row>
11482
      </tbody>
11483
     </tgroup>
11484
    </table>
11485
11486
  <para>
11487
   The <function>lower</> and  <function>upper</> functions return null
11488
   if the range is empty or the requested bound is infinite.
11489
   The <function>lower_inc</function>, <function>upper_inc</function>,
11490
   <function>lower_inf</function>, and <function>upper_inf</function>
11491
   functions all return false for an empty range.
11492
  </para>
11493
  </sect1>
11494
11495
 <sect1 id="functions-aggregate">
11496
  <title>Aggregate Functions</title>
11497
11498
  <indexterm zone="functions-aggregate">
11499
   <primary>aggregate function</primary>
11500
   <secondary>built-in</secondary>
11501
  </indexterm>
11502
11503
  <para>
11504
   <firstterm>Aggregate functions</firstterm> compute a single result
11505
   from a set of input values.  The built-in aggregate functions
11506
   are listed in
11507
   <xref linkend="functions-aggregate-table"> and
11508
   <xref linkend="functions-aggregate-statistics-table">.
11509
   The special syntax considerations for aggregate
11510
   functions are explained in <xref linkend="syntax-aggregates">.
11511
   Consult <xref linkend="tutorial-agg"> for additional introductory
11512
   information.
11513
  </para>
11514
11515
  <table id="functions-aggregate-table">
11516
   <title>General-Purpose Aggregate Functions</title>
11517
11518
   <tgroup cols="4">
11519
    <thead>
11520
     <row>
11521
      <entry>Function</entry>
11522
      <entry>Argument Type(s)</entry>
11523
      <entry>Return Type</entry>
11524
      <entry>Description</entry>
11525
     </row>
11526
    </thead>
11527
11528
    <tbody>
11529
     <row>
11530
      <entry>
11531
       <indexterm>
11532
        <primary>array_agg</primary>
11533
       </indexterm>
11534
       <function>array_agg(<replaceable class="parameter">expression</replaceable>)</function>
11535
      </entry>
11536
      <entry>
11537
       any
11538
      </entry>
11539
      <entry>
11540
       array of the argument type
11541
      </entry>
11542
      <entry>input values, including nulls, concatenated into an array</entry>
11543
     </row>
11544
11545
     <row>
11546
      <entry>
11547
       <indexterm>
11548
        <primary>average</primary>
11549
       </indexterm>
11550
       <indexterm>
11551
        <primary>avg</primary>
11552
       </indexterm>
11553
       <function>avg(<replaceable class="parameter">expression</replaceable>)</function>
11554
      </entry>
11555
      <entry>
11556
       <type>smallint</type>, <type>int</type>,
11557
       <type>bigint</type>, <type>real</type>, <type>double
11558
       precision</type>, <type>numeric</type>, or <type>interval</type>
11559
      </entry>
11560
      <entry>
11561
       <type>numeric</type> for any integer-type argument,
11562
       <type>double precision</type> for a floating-point argument,
11563
       otherwise the same as the argument data type
11564
      </entry>
11565
      <entry>the average (arithmetic mean) of all input values</entry>
11566
     </row>
11567
11568
     <row>
11569
      <entry>
11570
       <indexterm>
11571
        <primary>bit_and</primary>
11572
       </indexterm>
11573
       <function>bit_and(<replaceable class="parameter">expression</replaceable>)</function>
11574
      </entry>
11575
      <entry>
11576
       <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
11577
       <type>bit</type>
11578
      </entry>
11579
      <entry>
11580
        same as argument data type
11581
      </entry>
11582
      <entry>the bitwise AND of all non-null input values, or null if none</entry>
11583
     </row>
11584
11585
     <row>
11586
      <entry>
11587
       <indexterm>
11588
        <primary>bit_or</primary>
11589
       </indexterm>
11590
       <function>bit_or(<replaceable class="parameter">expression</replaceable>)</function>
11591
      </entry>
11592
      <entry>
11593
       <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
11594
       <type>bit</type>
11595
      </entry>
11596
      <entry>
11597
        same as argument data type
11598
      </entry>
11599
      <entry>the bitwise OR of all non-null input values, or null if none</entry>
11600
     </row>
11601
11602
     <row>
11603
      <entry>
11604
       <indexterm>
11605
        <primary>bool_and</primary>
11606
       </indexterm>
11607
       <function>bool_and(<replaceable class="parameter">expression</replaceable>)</function>
11608
      </entry>
11609
      <entry>
11610
       <type>bool</type>
11611
      </entry>
11612
      <entry>
11613
       <type>bool</type>
11614
      </entry>
11615
      <entry>true if all input values are true, otherwise false</entry>
11616
     </row>
11617
11618
     <row>
11619
      <entry>
11620
       <indexterm>
11621
        <primary>bool_or</primary>
11622
       </indexterm>
11623
       <function>bool_or(<replaceable class="parameter">expression</replaceable>)</function>
11624
      </entry>
11625
      <entry>
11626
       <type>bool</type>
11627
      </entry>
11628
      <entry>
11629
       <type>bool</type>
11630
      </entry>
11631
      <entry>true if at least one input value is true, otherwise false</entry>
11632
     </row>
11633
11634
     <row>
11635
      <entry>
11636
       <indexterm>
11637
        <primary>count</primary>
11638
       </indexterm>
11639
       <function>count(*)</function>
11640
      </entry>
11641
      <entry></entry>
11642
      <entry><type>bigint</type></entry>
11643
      <entry>number of input rows</entry>
11644
     </row>
11645
11646
     <row>
11647
      <entry><function>count(<replaceable class="parameter">expression</replaceable>)</function></entry>
11648
      <entry>any</entry>
11649
      <entry><type>bigint</type></entry>
11650
      <entry>
11651
       number of input rows for which the value of <replaceable
11652
       class="parameter">expression</replaceable> is not null
11653
      </entry>
11654
     </row>
11655
11656
     <row>
11657
      <entry>
11658
       <indexterm>
11659
        <primary>every</primary>
11660
       </indexterm>
11661
       <function>every(<replaceable class="parameter">expression</replaceable>)</function>
11662
      </entry>
11663
      <entry>
11664
       <type>bool</type>
11665
      </entry>
11666
      <entry>
11667
       <type>bool</type>
11668
      </entry>
11669
      <entry>equivalent to <function>bool_and</function></entry>
11670
     </row>
11671
11672
     <row>
11673
      <entry>
11674
       <indexterm>
11675
        <primary>json_agg</primary>
11676
       </indexterm>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
11677
       <function>json_agg(<replaceable class="parameter">expression</replaceable>)</function>
1 by Martin Pitt
Import upstream version 9.3~beta1
11678
      </entry>
11679
      <entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
11680
       <type>any</type>
1 by Martin Pitt
Import upstream version 9.3~beta1
11681
      </entry>
11682
      <entry>
11683
       <type>json</type>
11684
      </entry>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
11685
      <entry>aggregates values as a JSON array</entry>
1 by Martin Pitt
Import upstream version 9.3~beta1
11686
     </row>
11687
11688
     <row>
11689
      <entry>
11690
       <indexterm>
11691
        <primary>max</primary>
11692
       </indexterm>
11693
       <function>max(<replaceable class="parameter">expression</replaceable>)</function>
11694
      </entry>
11695
      <entry>any array, numeric, string, or date/time type</entry>
11696
      <entry>same as argument type</entry>
11697
      <entry>
11698
       maximum value of <replaceable
11699
       class="parameter">expression</replaceable> across all input
11700
       values
11701
      </entry>
11702
     </row>
11703
11704
     <row>
11705
      <entry>
11706
       <indexterm>
11707
        <primary>min</primary>
11708
       </indexterm>
11709
       <function>min(<replaceable class="parameter">expression</replaceable>)</function>
11710
      </entry>
11711
      <entry>any array, numeric, string, or date/time type</entry>
11712
      <entry>same as argument type</entry>
11713
      <entry>
11714
       minimum value of <replaceable
11715
       class="parameter">expression</replaceable> across all input
11716
       values
11717
      </entry>
11718
     </row>
11719
11720
     <row>
11721
      <entry>
11722
       <indexterm>
11723
        <primary>string_agg</primary>
11724
       </indexterm>
11725
       <function>
11726
         string_agg(<replaceable class="parameter">expression</replaceable>,
11727
                    <replaceable class="parameter">delimiter</replaceable>)
11728
       </function>
11729
      </entry>
11730
      <entry>
11731
       (<type>text</type>, <type>text</type>) or (<type>bytea</type>, <type>bytea</type>)
11732
      </entry>
11733
      <entry>
11734
       same as argument types
11735
      </entry>
11736
      <entry>input values concatenated into a string, separated by delimiter</entry>
11737
     </row>
11738
11739
     <row>
11740
      <entry>
11741
       <indexterm>
11742
        <primary>sum</primary>
11743
       </indexterm>
11744
       <function>sum(<replaceable class="parameter">expression</replaceable>)</function>
11745
      </entry>
11746
      <entry>
11747
       <type>smallint</type>, <type>int</type>,
11748
       <type>bigint</type>, <type>real</type>, <type>double
1.2.1 by Martin Pitt
Import upstream version 9.3.6
11749
       precision</type>, <type>numeric</type>,
11750
       <type>interval</type>, or <type>money</>
1 by Martin Pitt
Import upstream version 9.3~beta1
11751
      </entry>
11752
      <entry>
11753
       <type>bigint</type> for <type>smallint</type> or
11754
       <type>int</type> arguments, <type>numeric</type> for
1.2.1 by Martin Pitt
Import upstream version 9.3.6
11755
       <type>bigint</type> arguments, otherwise the same as the
1 by Martin Pitt
Import upstream version 9.3~beta1
11756
       argument data type
11757
      </entry>
11758
      <entry>sum of <replaceable class="parameter">expression</replaceable> across all input values</entry>
11759
     </row>
11760
11761
     <row>
11762
      <entry>
11763
       <indexterm>
11764
        <primary>xmlagg</primary>
11765
       </indexterm>
11766
       <function>xmlagg(<replaceable class="parameter">expression</replaceable>)</function>
11767
      </entry>
11768
      <entry>
11769
       <type>xml</type>
11770
      </entry>
11771
      <entry>
11772
       <type>xml</type>
11773
      </entry>
11774
      <entry>concatenation of XML values (see also <xref linkend="functions-xml-xmlagg">)</entry>
11775
     </row>
11776
    </tbody>
11777
   </tgroup>
11778
  </table>
11779
11780
  <para>
11781
   It should be noted that except for <function>count</function>,
11782
   these functions return a null value when no rows are selected.  In
11783
   particular, <function>sum</function> of no rows returns null, not
11784
   zero as one might expect, and <function>array_agg</function>
11785
   returns null rather than an empty array when there are no input
11786
   rows.  The <function>coalesce</function> function can be used to
11787
   substitute zero or an empty array for null when necessary.
11788
  </para>
11789
11790
  <note>
11791
    <indexterm>
11792
      <primary>ANY</primary>
11793
    </indexterm>
11794
    <indexterm>
11795
      <primary>SOME</primary>
11796
    </indexterm>
11797
    <para>
11798
      Boolean aggregates <function>bool_and</function> and
11799
      <function>bool_or</function> correspond to standard SQL aggregates
11800
      <function>every</function> and <function>any</function> or
11801
      <function>some</function>.
11802
      As for <function>any</function> and <function>some</function>,
11803
      it seems that there is an ambiguity built into the standard syntax:
11804
<programlisting>
11805
SELECT b1 = ANY((SELECT b2 FROM t2 ...)) FROM t1 ...;
11806
</programlisting>
11807
      Here <function>ANY</function> can be considered either as introducing
11808
      a subquery, or as being an aggregate function, if the subquery
11809
      returns one row with a Boolean value.
11810
      Thus the standard name cannot be given to these aggregates.
11811
    </para>
11812
  </note>
11813
11814
  <note>
11815
   <para>
11816
    Users accustomed to working with other SQL database management
11817
    systems might be disappointed by the performance of the
11818
    <function>count</function> aggregate when it is applied to the
11819
    entire table. A query like:
11820
<programlisting>
11821
SELECT count(*) FROM sometable;
11822
</programlisting>
11823
    will require effort proportional to the size of the table:
11824
    <productname>PostgreSQL</productname> will need to scan either the
11825
    entire table or the entirety of an index which includes all rows in
11826
    the table.
11827
   </para>
11828
  </note>
11829
11830
  <para>
11831
   The aggregate functions <function>array_agg</function>,
11832
   <function>json_agg</function>,
11833
   <function>string_agg</function>,
11834
   and <function>xmlagg</function>, as well as similar user-defined
11835
   aggregate functions, produce meaningfully different result values
11836
   depending on the order of the input values.  This ordering is
11837
   unspecified by default, but can be controlled by writing an
11838
   <literal>ORDER BY</> clause within the aggregate call, as shown in
11839
   <xref linkend="syntax-aggregates">.
11840
   Alternatively, supplying the input values from a sorted subquery
11841
   will usually work.  For example:
11842
11843
<screen><![CDATA[
11844
SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;
11845
]]></screen>
11846
11847
   But this syntax is not allowed in the SQL standard, and is
11848
   not portable to other database systems.
11849
  </para>
11850
11851
  <para>
11852
   <xref linkend="functions-aggregate-statistics-table"> shows
11853
   aggregate functions typically used in statistical analysis.
11854
   (These are separated out merely to avoid cluttering the listing
11855
   of more-commonly-used aggregates.)  Where the description mentions
11856
   <replaceable class="parameter">N</replaceable>, it means the
11857
   number of input rows for which all the input expressions are non-null.
11858
   In all cases, null is returned if the computation is meaningless,
11859
   for example when <replaceable class="parameter">N</replaceable> is zero.
11860
  </para>
11861
11862
  <indexterm>
11863
   <primary>statistics</primary>
11864
  </indexterm>
11865
  <indexterm>
11866
   <primary>linear regression</primary>
11867
  </indexterm>
11868
11869
  <table id="functions-aggregate-statistics-table">
11870
   <title>Aggregate Functions for Statistics</title>
11871
11872
   <tgroup cols="4">
11873
    <thead>
11874
     <row>
11875
      <entry>Function</entry>
11876
      <entry>Argument Type</entry>
11877
      <entry>Return Type</entry>
11878
      <entry>Description</entry>
11879
     </row>
11880
    </thead>
11881
11882
    <tbody>
11883
11884
     <row>
11885
      <entry>
11886
       <indexterm>
11887
        <primary>correlation</primary>
11888
       </indexterm>
11889
       <indexterm>
11890
        <primary>corr</primary>
11891
       </indexterm>
11892
       <function>corr(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
11893
      </entry>
11894
      <entry>
11895
       <type>double precision</type>
11896
      </entry>
11897
      <entry>
11898
       <type>double precision</type>
11899
      </entry>
11900
      <entry>correlation coefficient</entry>
11901
     </row>
11902
11903
     <row>
11904
      <entry>
11905
       <indexterm>
11906
        <primary>covariance</primary>
11907
        <secondary>population</secondary>
11908
       </indexterm>
11909
       <indexterm>
11910
        <primary>covar_pop</primary>
11911
       </indexterm>
11912
       <function>covar_pop(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
11913
      </entry>
11914
      <entry>
11915
       <type>double precision</type>
11916
      </entry>
11917
      <entry>
11918
       <type>double precision</type>
11919
      </entry>
11920
      <entry>population covariance</entry>
11921
     </row>
11922
11923
     <row>
11924
      <entry>
11925
       <indexterm>
11926
        <primary>covariance</primary>
11927
        <secondary>sample</secondary>
11928
       </indexterm>
11929
       <indexterm>
11930
        <primary>covar_samp</primary>
11931
       </indexterm>
11932
       <function>covar_samp(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
11933
      </entry>
11934
      <entry>
11935
       <type>double precision</type>
11936
      </entry>
11937
      <entry>
11938
       <type>double precision</type>
11939
      </entry>
11940
      <entry>sample covariance</entry>
11941
     </row>
11942
11943
     <row>
11944
      <entry>
11945
       <indexterm>
11946
        <primary>regr_avgx</primary>
11947
       </indexterm>
11948
       <function>regr_avgx(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
11949
      </entry>
11950
      <entry>
11951
       <type>double precision</type>
11952
      </entry>
11953
      <entry>
11954
       <type>double precision</type>
11955
      </entry>
11956
      <entry>average of the independent variable
11957
      (<literal>sum(<replaceable class="parameter">X</replaceable>)/<replaceable class="parameter">N</replaceable></literal>)</entry>
11958
     </row>
11959
11960
     <row>
11961
      <entry>
11962
       <indexterm>
11963
        <primary>regr_avgy</primary>
11964
       </indexterm>
11965
       <function>regr_avgy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
11966
      </entry>
11967
      <entry>
11968
       <type>double precision</type>
11969
      </entry>
11970
      <entry>
11971
       <type>double precision</type>
11972
      </entry>
11973
      <entry>average of the dependent variable
11974
      (<literal>sum(<replaceable class="parameter">Y</replaceable>)/<replaceable class="parameter">N</replaceable></literal>)</entry>
11975
     </row>
11976
11977
     <row>
11978
      <entry>
11979
       <indexterm>
11980
        <primary>regr_count</primary>
11981
       </indexterm>
11982
       <function>regr_count(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
11983
      </entry>
11984
      <entry>
11985
       <type>double precision</type>
11986
      </entry>
11987
      <entry>
11988
       <type>bigint</type>
11989
      </entry>
11990
      <entry>number of input rows in which both expressions are nonnull</entry>
11991
     </row>
11992
11993
     <row>
11994
      <entry>
11995
       <indexterm>
11996
        <primary>regression intercept</primary>
11997
       </indexterm>
11998
       <indexterm>
11999
        <primary>regr_intercept</primary>
12000
       </indexterm>
12001
       <function>regr_intercept(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
12002
      </entry>
12003
      <entry>
12004
       <type>double precision</type>
12005
      </entry>
12006
      <entry>
12007
       <type>double precision</type>
12008
      </entry>
12009
      <entry>y-intercept of the least-squares-fit linear equation
12010
      determined by the (<replaceable
12011
      class="parameter">X</replaceable>, <replaceable
12012
      class="parameter">Y</replaceable>) pairs</entry>
12013
     </row>
12014
12015
     <row>
12016
      <entry>
12017
       <indexterm>
12018
        <primary>regr_r2</primary>
12019
       </indexterm>
12020
       <function>regr_r2(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
12021
      </entry>
12022
      <entry>
12023
       <type>double precision</type>
12024
      </entry>
12025
      <entry>
12026
       <type>double precision</type>
12027
      </entry>
12028
      <entry>square of the correlation coefficient</entry>
12029
     </row>
12030
12031
     <row>
12032
      <entry>
12033
       <indexterm>
12034
        <primary>regression slope</primary>
12035
       </indexterm>
12036
       <indexterm>
12037
        <primary>regr_slope</primary>
12038
       </indexterm>
12039
       <function>regr_slope(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
12040
      </entry>
12041
      <entry>
12042
       <type>double precision</type>
12043
      </entry>
12044
      <entry>
12045
       <type>double precision</type>
12046
      </entry>
12047
      <entry>slope of the least-squares-fit linear equation determined
12048
      by the (<replaceable class="parameter">X</replaceable>,
12049
      <replaceable class="parameter">Y</replaceable>) pairs</entry>
12050
     </row>
12051
12052
     <row>
12053
      <entry>
12054
       <indexterm>
12055
        <primary>regr_sxx</primary>
12056
       </indexterm>
12057
       <function>regr_sxx(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
12058
      </entry>
12059
      <entry>
12060
       <type>double precision</type>
12061
      </entry>
12062
      <entry>
12063
       <type>double precision</type>
12064
      </entry>
12065
      <entry><literal>sum(<replaceable
12066
      class="parameter">X</replaceable>^2) - sum(<replaceable
12067
      class="parameter">X</replaceable>)^2/<replaceable
12068
      class="parameter">N</replaceable></literal> (<quote>sum of
12069
      squares</quote> of the independent variable)</entry>
12070
     </row>
12071
12072
     <row>
12073
      <entry>
12074
       <indexterm>
12075
        <primary>regr_sxy</primary>
12076
       </indexterm>
12077
       <function>regr_sxy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
12078
      </entry>
12079
      <entry>
12080
       <type>double precision</type>
12081
      </entry>
12082
      <entry>
12083
       <type>double precision</type>
12084
      </entry>
12085
      <entry><literal>sum(<replaceable
12086
      class="parameter">X</replaceable>*<replaceable
12087
      class="parameter">Y</replaceable>) - sum(<replaceable
12088
      class="parameter">X</replaceable>) * sum(<replaceable
12089
      class="parameter">Y</replaceable>)/<replaceable
12090
      class="parameter">N</replaceable></literal> (<quote>sum of
12091
      products</quote> of independent times dependent
12092
      variable)</entry>
12093
     </row>
12094
12095
     <row>
12096
      <entry>
12097
       <indexterm>
12098
        <primary>regr_syy</primary>
12099
       </indexterm>
12100
       <function>regr_syy(<replaceable class="parameter">Y</replaceable>, <replaceable class="parameter">X</replaceable>)</function>
12101
      </entry>
12102
      <entry>
12103
       <type>double precision</type>
12104
      </entry>
12105
      <entry>
12106
       <type>double precision</type>
12107
      </entry>
12108
      <entry><literal>sum(<replaceable
12109
      class="parameter">Y</replaceable>^2) - sum(<replaceable
12110
      class="parameter">Y</replaceable>)^2/<replaceable
12111
      class="parameter">N</replaceable></literal> (<quote>sum of
12112
      squares</quote> of the dependent variable)</entry>
12113
     </row>
12114
12115
     <row>
12116
      <entry>
12117
       <indexterm>
12118
        <primary>standard deviation</primary>
12119
       </indexterm>
12120
       <indexterm>
12121
        <primary>stddev</primary>
12122
       </indexterm>
12123
       <function>stddev(<replaceable class="parameter">expression</replaceable>)</function>
12124
      </entry>
12125
      <entry>
12126
       <type>smallint</type>, <type>int</type>,
12127
       <type>bigint</type>, <type>real</type>, <type>double
12128
       precision</type>, or <type>numeric</type>
12129
      </entry>
12130
      <entry>
12131
       <type>double precision</type> for floating-point arguments,
12132
       otherwise <type>numeric</type>
12133
      </entry>
12134
      <entry>historical alias for <function>stddev_samp</function></entry>
12135
     </row>
12136
12137
     <row>
12138
      <entry>
12139
       <indexterm>
12140
        <primary>standard deviation</primary>
12141
        <secondary>population</secondary>
12142
       </indexterm>
12143
       <indexterm>
12144
        <primary>stddev_pop</primary>
12145
       </indexterm>
12146
       <function>stddev_pop(<replaceable class="parameter">expression</replaceable>)</function>
12147
      </entry>
12148
      <entry>
12149
       <type>smallint</type>, <type>int</type>,
12150
       <type>bigint</type>, <type>real</type>, <type>double
12151
       precision</type>, or <type>numeric</type>
12152
      </entry>
12153
      <entry>
12154
       <type>double precision</type> for floating-point arguments,
12155
       otherwise <type>numeric</type>
12156
      </entry>
12157
      <entry>population standard deviation of the input values</entry>
12158
     </row>
12159
12160
     <row>
12161
      <entry>
12162
       <indexterm>
12163
        <primary>standard deviation</primary>
12164
        <secondary>sample</secondary>
12165
       </indexterm>
12166
       <indexterm>
12167
        <primary>stddev_samp</primary>
12168
       </indexterm>
12169
       <function>stddev_samp(<replaceable class="parameter">expression</replaceable>)</function>
12170
      </entry>
12171
      <entry>
12172
       <type>smallint</type>, <type>int</type>,
12173
       <type>bigint</type>, <type>real</type>, <type>double
12174
       precision</type>, or <type>numeric</type>
12175
      </entry>
12176
      <entry>
12177
       <type>double precision</type> for floating-point arguments,
12178
       otherwise <type>numeric</type>
12179
      </entry>
12180
      <entry>sample standard deviation of the input values</entry>
12181
     </row>
12182
12183
     <row>
12184
      <entry>
12185
       <indexterm>
12186
        <primary>variance</primary>
12187
       </indexterm>
12188
       <function>variance</function>(<replaceable class="parameter">expression</replaceable>)
12189
      </entry>
12190
      <entry>
12191
       <type>smallint</type>, <type>int</type>,
12192
       <type>bigint</type>, <type>real</type>, <type>double
12193
       precision</type>, or <type>numeric</type>
12194
      </entry>
12195
      <entry>
12196
       <type>double precision</type> for floating-point arguments,
12197
       otherwise <type>numeric</type>
12198
      </entry>
12199
      <entry>historical alias for <function>var_samp</function></entry>
12200
     </row>
12201
12202
     <row>
12203
      <entry>
12204
       <indexterm>
12205
        <primary>variance</primary>
12206
        <secondary>population</secondary>
12207
       </indexterm>
12208
       <indexterm>
12209
        <primary>var_pop</primary>
12210
       </indexterm>
12211
       <function>var_pop</function>(<replaceable class="parameter">expression</replaceable>)
12212
      </entry>
12213
      <entry>
12214
       <type>smallint</type>, <type>int</type>,
12215
       <type>bigint</type>, <type>real</type>, <type>double
12216
       precision</type>, or <type>numeric</type>
12217
      </entry>
12218
      <entry>
12219
       <type>double precision</type> for floating-point arguments,
12220
       otherwise <type>numeric</type>
12221
      </entry>
12222
      <entry>population variance of the input values (square of the population standard deviation)</entry>
12223
     </row>
12224
12225
     <row>
12226
      <entry>
12227
       <indexterm>
12228
        <primary>variance</primary>
12229
        <secondary>sample</secondary>
12230
       </indexterm>
12231
       <indexterm>
12232
        <primary>var_samp</primary>
12233
       </indexterm>
12234
       <function>var_samp</function>(<replaceable class="parameter">expression</replaceable>)
12235
      </entry>
12236
      <entry>
12237
       <type>smallint</type>, <type>int</type>,
12238
       <type>bigint</type>, <type>real</type>, <type>double
12239
       precision</type>, or <type>numeric</type>
12240
      </entry>
12241
      <entry>
12242
       <type>double precision</type> for floating-point arguments,
12243
       otherwise <type>numeric</type>
12244
      </entry>
12245
      <entry>sample variance of the input values (square of the sample standard deviation)</entry>
12246
     </row>
12247
    </tbody>
12248
   </tgroup>
12249
  </table>
12250
12251
 </sect1>
12252
12253
 <sect1 id="functions-window">
12254
  <title>Window Functions</title>
12255
12256
  <indexterm zone="functions-window">
12257
   <primary>window function</primary>
12258
   <secondary>built-in</secondary>
12259
  </indexterm>
12260
12261
  <para>
12262
   <firstterm>Window functions</firstterm> provide the ability to perform
12263
   calculations across sets of rows that are related to the current query
12264
   row.  See <xref linkend="tutorial-window"> for an introduction to this
12265
   feature.
12266
  </para>
12267
12268
  <para>
12269
   The built-in window functions are listed in
12270
   <xref linkend="functions-window-table">.  Note that these functions
12271
   <emphasis>must</> be invoked using window function syntax; that is an
12272
   <literal>OVER</> clause is required.
12273
  </para>
12274
12275
  <para>
12276
   In addition to these functions, any built-in or user-defined aggregate
12277
   function can be used as a window function (see
12278
   <xref linkend="functions-aggregate"> for a list of the built-in aggregates).
12279
   Aggregate functions act as window functions only when an <literal>OVER</>
12280
   clause follows the call; otherwise they act as regular aggregates.
12281
  </para>
12282
12283
  <table id="functions-window-table">
12284
   <title>General-Purpose Window Functions</title>
12285
12286
   <tgroup cols="3">
12287
    <thead>
12288
     <row>
12289
      <entry>Function</entry>
12290
      <entry>Return Type</entry>
12291
      <entry>Description</entry>
12292
     </row>
12293
    </thead>
12294
12295
    <tbody>
12296
     <row>
12297
      <entry>
12298
       <indexterm>
12299
        <primary>row_number</primary>
12300
       </indexterm>
12301
       <function>row_number()</function>
12302
      </entry>
12303
      <entry>
12304
       <type>bigint</type>
12305
      </entry>
12306
      <entry>number of the current row within its partition, counting from 1</entry>
12307
     </row>
12308
12309
     <row>
12310
      <entry>
12311
       <indexterm>
12312
        <primary>rank</primary>
12313
       </indexterm>
12314
       <function>rank()</function>
12315
      </entry>
12316
      <entry>
12317
       <type>bigint</type>
12318
      </entry>
12319
      <entry>rank of the current row with gaps; same as <function>row_number</> of its first peer</entry>
12320
     </row>
12321
12322
     <row>
12323
      <entry>
12324
       <indexterm>
12325
        <primary>dense_rank</primary>
12326
       </indexterm>
12327
       <function>dense_rank()</function>
12328
      </entry>
12329
      <entry>
12330
       <type>bigint</type>
12331
      </entry>
12332
      <entry>rank of the current row without gaps; this function counts peer groups</entry>
12333
     </row>
12334
12335
     <row>
12336
      <entry>
12337
       <indexterm>
12338
        <primary>percent_rank</primary>
12339
       </indexterm>
12340
       <function>percent_rank()</function>
12341
      </entry>
12342
      <entry>
12343
       <type>double precision</type>
12344
      </entry>
12345
      <entry>relative rank of the current row: (<function>rank</> - 1) / (total rows - 1)</entry>
12346
     </row>
12347
12348
     <row>
12349
      <entry>
12350
       <indexterm>
12351
        <primary>cume_dist</primary>
12352
       </indexterm>
12353
       <function>cume_dist()</function>
12354
      </entry>
12355
      <entry>
12356
       <type>double precision</type>
12357
      </entry>
12358
      <entry>relative rank of the current row: (number of rows preceding or peer with current row) / (total rows)</entry>
12359
     </row>
12360
12361
     <row>
12362
      <entry>
12363
       <indexterm>
12364
        <primary>ntile</primary>
12365
       </indexterm>
12366
       <function>ntile(<replaceable class="parameter">num_buckets</replaceable> <type>integer</>)</function>
12367
      </entry>
12368
      <entry>
12369
       <type>integer</type>
12370
      </entry>
12371
      <entry>integer ranging from 1 to the argument value, dividing the
12372
       partition as equally as possible</entry>
12373
     </row>
12374
12375
     <row>
12376
      <entry>
12377
       <indexterm>
12378
        <primary>lag</primary>
12379
       </indexterm>
12380
       <function>
1.2.3 by Martin Pitt
Import upstream version 9.3.10
12381
         lag(<replaceable class="parameter">value</replaceable> <type>anyelement</>
1 by Martin Pitt
Import upstream version 9.3~beta1
12382
             [, <replaceable class="parameter">offset</replaceable> <type>integer</>
1.2.3 by Martin Pitt
Import upstream version 9.3.10
12383
             [, <replaceable class="parameter">default</replaceable> <type>anyelement</> ]])
1 by Martin Pitt
Import upstream version 9.3~beta1
12384
       </function>
12385
      </entry>
12386
      <entry>
12387
       <type>same type as <replaceable class="parameter">value</replaceable></type>
12388
      </entry>
12389
      <entry>
12390
       returns <replaceable class="parameter">value</replaceable> evaluated at
12391
       the row that is <replaceable class="parameter">offset</replaceable>
12392
       rows before the current row within the partition; if there is no such
1.2.3 by Martin Pitt
Import upstream version 9.3.10
12393
       row, instead return <replaceable class="parameter">default</replaceable>
12394
       (which must be of the same type as
12395
       <replaceable class="parameter">value</replaceable>).
1 by Martin Pitt
Import upstream version 9.3~beta1
12396
       Both <replaceable class="parameter">offset</replaceable> and
12397
       <replaceable class="parameter">default</replaceable> are evaluated
12398
       with respect to the current row.  If omitted,
12399
       <replaceable class="parameter">offset</replaceable> defaults to 1 and
12400
       <replaceable class="parameter">default</replaceable> to null
12401
      </entry>
12402
     </row>
12403
12404
     <row>
12405
      <entry>
12406
       <indexterm>
12407
        <primary>lead</primary>
12408
       </indexterm>
12409
       <function>
1.2.3 by Martin Pitt
Import upstream version 9.3.10
12410
         lead(<replaceable class="parameter">value</replaceable> <type>anyelement</>
1 by Martin Pitt
Import upstream version 9.3~beta1
12411
              [, <replaceable class="parameter">offset</replaceable> <type>integer</>
1.2.3 by Martin Pitt
Import upstream version 9.3.10
12412
              [, <replaceable class="parameter">default</replaceable> <type>anyelement</> ]])
1 by Martin Pitt
Import upstream version 9.3~beta1
12413
       </function>
12414
      </entry>
12415
      <entry>
12416
       <type>same type as <replaceable class="parameter">value</replaceable></type>
12417
      </entry>
12418
      <entry>
12419
       returns <replaceable class="parameter">value</replaceable> evaluated at
12420
       the row that is <replaceable class="parameter">offset</replaceable>
12421
       rows after the current row within the partition; if there is no such
1.2.3 by Martin Pitt
Import upstream version 9.3.10
12422
       row, instead return <replaceable class="parameter">default</replaceable>
12423
       (which must be of the same type as
12424
       <replaceable class="parameter">value</replaceable>).
1 by Martin Pitt
Import upstream version 9.3~beta1
12425
       Both <replaceable class="parameter">offset</replaceable> and
12426
       <replaceable class="parameter">default</replaceable> are evaluated
12427
       with respect to the current row.  If omitted,
12428
       <replaceable class="parameter">offset</replaceable> defaults to 1 and
12429
       <replaceable class="parameter">default</replaceable> to null
12430
      </entry>
12431
     </row>
12432
12433
     <row>
12434
      <entry>
12435
       <indexterm>
12436
        <primary>first_value</primary>
12437
       </indexterm>
12438
       <function>first_value(<replaceable class="parameter">value</replaceable> <type>any</>)</function>
12439
      </entry>
12440
      <entry>
12441
       <type>same type as <replaceable class="parameter">value</replaceable></type>
12442
      </entry>
12443
      <entry>
12444
       returns <replaceable class="parameter">value</replaceable> evaluated
12445
       at the row that is the first row of the window frame
12446
      </entry>
12447
     </row>
12448
12449
     <row>
12450
      <entry>
12451
       <indexterm>
12452
        <primary>last_value</primary>
12453
       </indexterm>
12454
       <function>last_value(<replaceable class="parameter">value</replaceable> <type>any</>)</function>
12455
      </entry>
12456
      <entry>
12457
       <type>same type as <replaceable class="parameter">value</replaceable></type>
12458
      </entry>
12459
      <entry>
12460
       returns <replaceable class="parameter">value</replaceable> evaluated
12461
       at the row that is the last row of the window frame
12462
      </entry>
12463
     </row>
12464
12465
     <row>
12466
      <entry>
12467
       <indexterm>
12468
        <primary>nth_value</primary>
12469
       </indexterm>
12470
       <function>
12471
         nth_value(<replaceable class="parameter">value</replaceable> <type>any</>, <replaceable class="parameter">nth</replaceable> <type>integer</>)
12472
       </function>
12473
      </entry>
12474
      <entry>
12475
       <type>same type as <replaceable class="parameter">value</replaceable></type>
12476
      </entry>
12477
      <entry>
12478
       returns <replaceable class="parameter">value</replaceable> evaluated
12479
       at the row that is the <replaceable class="parameter">nth</replaceable>
12480
       row of the window frame (counting from 1); null if no such row
12481
      </entry>
12482
     </row>
12483
    </tbody>
12484
   </tgroup>
12485
  </table>
12486
12487
  <para>
12488
   All of the functions listed in
12489
   <xref linkend="functions-window-table"> depend on the sort ordering
12490
   specified by the <literal>ORDER BY</> clause of the associated window
12491
   definition.  Rows that are not distinct in the <literal>ORDER BY</>
12492
   ordering are said to be <firstterm>peers</>; the four ranking functions
12493
   are defined so that they give the same answer for any two peer rows.
12494
  </para>
12495
12496
  <para>
12497
   Note that <function>first_value</>, <function>last_value</>, and
12498
   <function>nth_value</> consider only the rows within the <quote>window
12499
   frame</>, which by default contains the rows from the start of the
12500
   partition through the last peer of the current row.  This is
12501
   likely to give unhelpful results for <function>last_value</> and
12502
   sometimes also <function>nth_value</>.  You can redefine the frame by
12503
   adding a suitable frame specification (<literal>RANGE</> or
12504
   <literal>ROWS</>) to the <literal>OVER</> clause.
12505
   See <xref linkend="syntax-window-functions"> for more information
12506
   about frame specifications.
12507
  </para>
12508
12509
  <para>
12510
   When an aggregate function is used as a window function, it aggregates
12511
   over the rows within the current row's window frame.
12512
   An aggregate used with <literal>ORDER BY</> and the default window frame
12513
   definition produces a <quote>running sum</> type of behavior, which may or
12514
   may not be what's wanted.  To obtain
12515
   aggregation over the whole partition, omit <literal>ORDER BY</> or use
12516
   <literal>ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING</>.
12517
   Other frame specifications can be used to obtain other effects.
12518
  </para>
12519
12520
  <note>
12521
   <para>
12522
    The SQL standard defines a <literal>RESPECT NULLS</> or
12523
    <literal>IGNORE NULLS</> option for <function>lead</>, <function>lag</>,
12524
    <function>first_value</>, <function>last_value</>, and
12525
    <function>nth_value</>.  This is not implemented in
12526
    <productname>PostgreSQL</productname>: the behavior is always the
12527
    same as the standard's default, namely <literal>RESPECT NULLS</>.
12528
    Likewise, the standard's <literal>FROM FIRST</> or <literal>FROM LAST</>
12529
    option for <function>nth_value</> is not implemented: only the
12530
    default <literal>FROM FIRST</> behavior is supported.  (You can achieve
12531
    the result of <literal>FROM LAST</> by reversing the <literal>ORDER BY</>
12532
    ordering.)
12533
   </para>
12534
  </note>
12535
12536
 </sect1>
12537
12538
 <sect1 id="functions-subquery">
12539
  <title>Subquery Expressions</title>
12540
12541
  <indexterm>
12542
   <primary>EXISTS</primary>
12543
  </indexterm>
12544
12545
  <indexterm>
12546
   <primary>IN</primary>
12547
  </indexterm>
12548
12549
  <indexterm>
12550
   <primary>NOT IN</primary>
12551
  </indexterm>
12552
12553
  <indexterm>
12554
   <primary>ANY</primary>
12555
  </indexterm>
12556
12557
  <indexterm>
12558
   <primary>ALL</primary>
12559
  </indexterm>
12560
12561
  <indexterm>
12562
   <primary>SOME</primary>
12563
  </indexterm>
12564
12565
  <indexterm>
12566
   <primary>subquery</primary>
12567
  </indexterm>
12568
12569
  <para>
12570
   This section describes the <acronym>SQL</acronym>-compliant subquery
12571
   expressions available in <productname>PostgreSQL</productname>.
12572
   All of the expression forms documented in this section return
12573
   Boolean (true/false) results.
12574
  </para>
12575
12576
  <sect2 id="functions-subquery-exists">
12577
   <title><literal>EXISTS</literal></title>
12578
12579
<synopsis>
12580
EXISTS (<replaceable>subquery</replaceable>)
12581
</synopsis>
12582
12583
  <para>
12584
   The argument of <token>EXISTS</token> is an arbitrary <command>SELECT</> statement,
12585
   or <firstterm>subquery</firstterm>.  The
12586
   subquery is evaluated to determine whether it returns any rows.
12587
   If it returns at least one row, the result of <token>EXISTS</token> is
12588
   <quote>true</>; if the subquery returns no rows, the result of <token>EXISTS</token>
12589
   is <quote>false</>.
12590
  </para>
12591
12592
  <para>
12593
   The subquery can refer to variables from the surrounding query,
12594
   which will act as constants during any one evaluation of the subquery.
12595
  </para>
12596
12597
  <para>
12598
   The subquery will generally only be executed long enough to determine
12599
   whether at least one row is returned, not all the way to completion.
12600
   It is unwise to write a subquery that has side effects (such as
12601
   calling sequence functions); whether the side effects occur
12602
   might be unpredictable.
12603
  </para>
12604
12605
  <para>
12606
   Since the result depends only on whether any rows are returned,
12607
   and not on the contents of those rows, the output list of the
12608
   subquery is normally unimportant.  A common coding convention is
12609
   to write all <literal>EXISTS</> tests in the form
12610
   <literal>EXISTS(SELECT 1 WHERE ...)</literal>.  There are exceptions to
12611
   this rule however, such as subqueries that use <token>INTERSECT</token>.
12612
  </para>
12613
12614
  <para>
12615
   This simple example is like an inner join on <literal>col2</>, but
12616
   it produces at most one output row for each <literal>tab1</> row,
12617
   even if there are several matching <literal>tab2</> rows:
12618
<screen>
12619
SELECT col1
12620
FROM tab1
12621
WHERE EXISTS (SELECT 1 FROM tab2 WHERE col2 = tab1.col2);
12622
</screen>
12623
  </para>
12624
  </sect2>
12625
12626
  <sect2 id="functions-subquery-in">
12627
   <title><literal>IN</literal></title>
12628
12629
<synopsis>
12630
<replaceable>expression</replaceable> IN (<replaceable>subquery</replaceable>)
12631
</synopsis>
12632
12633
  <para>
12634
   The right-hand side is a parenthesized
12635
   subquery, which must return exactly one column.  The left-hand expression
12636
   is evaluated and compared to each row of the subquery result.
12637
   The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
12638
   The result is <quote>false</> if no equal row is found (including the
12639
   case where the subquery returns no rows).
12640
  </para>
12641
12642
  <para>
12643
   Note that if the left-hand expression yields null, or if there are
12644
   no equal right-hand values and at least one right-hand row yields
12645
   null, the result of the <token>IN</token> construct will be null, not false.
12646
   This is in accordance with SQL's normal rules for Boolean combinations
12647
   of null values.
12648
  </para>
12649
12650
  <para>
12651
   As with <token>EXISTS</token>, it's unwise to assume that the subquery will
12652
   be evaluated completely.
12653
  </para>
12654
12655
<synopsis>
12656
<replaceable>row_constructor</replaceable> IN (<replaceable>subquery</replaceable>)
12657
</synopsis>
12658
12659
  <para>
12660
   The left-hand side of this form of <token>IN</token> is a row constructor,
12661
   as described in <xref linkend="sql-syntax-row-constructors">.
12662
   The right-hand side is a parenthesized
12663
   subquery, which must return exactly as many columns as there are
12664
   expressions in the left-hand row.  The left-hand expressions are
12665
   evaluated and compared row-wise to each row of the subquery result.
12666
   The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
12667
   The result is <quote>false</> if no equal row is found (including the
12668
   case where the subquery returns no rows).
12669
  </para>
12670
12671
  <para>
12672
   As usual, null values in the rows are combined per
12673
   the normal rules of SQL Boolean expressions.  Two rows are considered
12674
   equal if all their corresponding members are non-null and equal; the rows
12675
   are unequal if any corresponding members are non-null and unequal;
12676
   otherwise the result of that row comparison is unknown (null).
12677
   If all the per-row results are either unequal or null, with at least one
12678
   null, then the result of <token>IN</token> is null.
12679
  </para>
12680
  </sect2>
12681
12682
  <sect2 id="functions-subquery-notin">
12683
   <title><literal>NOT IN</literal></title>
12684
12685
<synopsis>
12686
<replaceable>expression</replaceable> NOT IN (<replaceable>subquery</replaceable>)
12687
</synopsis>
12688
12689
  <para>
12690
   The right-hand side is a parenthesized
12691
   subquery, which must return exactly one column.  The left-hand expression
12692
   is evaluated and compared to each row of the subquery result.
12693
   The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
12694
   are found (including the case where the subquery returns no rows).
12695
   The result is <quote>false</> if any equal row is found.
12696
  </para>
12697
12698
  <para>
12699
   Note that if the left-hand expression yields null, or if there are
12700
   no equal right-hand values and at least one right-hand row yields
12701
   null, the result of the <token>NOT IN</token> construct will be null, not true.
12702
   This is in accordance with SQL's normal rules for Boolean combinations
12703
   of null values.
12704
  </para>
12705
12706
  <para>
12707
   As with <token>EXISTS</token>, it's unwise to assume that the subquery will
12708
   be evaluated completely.
12709
  </para>
12710
12711
<synopsis>
12712
<replaceable>row_constructor</replaceable> NOT IN (<replaceable>subquery</replaceable>)
12713
</synopsis>
12714
12715
  <para>
12716
   The left-hand side of this form of <token>NOT IN</token> is a row constructor,
12717
   as described in <xref linkend="sql-syntax-row-constructors">.
12718
   The right-hand side is a parenthesized
12719
   subquery, which must return exactly as many columns as there are
12720
   expressions in the left-hand row.  The left-hand expressions are
12721
   evaluated and compared row-wise to each row of the subquery result.
12722
   The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
12723
   are found (including the case where the subquery returns no rows).
12724
   The result is <quote>false</> if any equal row is found.
12725
  </para>
12726
12727
  <para>
12728
   As usual, null values in the rows are combined per
12729
   the normal rules of SQL Boolean expressions.  Two rows are considered
12730
   equal if all their corresponding members are non-null and equal; the rows
12731
   are unequal if any corresponding members are non-null and unequal;
12732
   otherwise the result of that row comparison is unknown (null).
12733
   If all the per-row results are either unequal or null, with at least one
12734
   null, then the result of <token>NOT IN</token> is null.
12735
  </para>
12736
  </sect2>
12737
12738
  <sect2 id="functions-subquery-any-some">
12739
   <title><literal>ANY</literal>/<literal>SOME</literal></title>
12740
12741
<synopsis>
12742
<replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>subquery</replaceable>)
12743
<replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>subquery</replaceable>)
12744
</synopsis>
12745
12746
  <para>
12747
   The right-hand side is a parenthesized
12748
   subquery, which must return exactly one column.  The left-hand expression
12749
   is evaluated and compared to each row of the subquery result using the
12750
   given <replaceable>operator</replaceable>, which must yield a Boolean
12751
   result.
12752
   The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
12753
   The result is <quote>false</> if no true result is found (including the
12754
   case where the subquery returns no rows).
12755
  </para>
12756
12757
  <para>
12758
   <token>SOME</token> is a synonym for <token>ANY</token>.
12759
   <token>IN</token> is equivalent to <literal>= ANY</literal>.
12760
  </para>
12761
12762
  <para>
12763
   Note that if there are no successes and at least one right-hand row yields
12764
   null for the operator's result, the result of the <token>ANY</token> construct
12765
   will be null, not false.
12766
   This is in accordance with SQL's normal rules for Boolean combinations
12767
   of null values.
12768
  </para>
12769
12770
  <para>
12771
   As with <token>EXISTS</token>, it's unwise to assume that the subquery will
12772
   be evaluated completely.
12773
  </para>
12774
12775
<synopsis>
12776
<replaceable>row_constructor</replaceable> <replaceable>operator</> ANY (<replaceable>subquery</replaceable>)
12777
<replaceable>row_constructor</replaceable> <replaceable>operator</> SOME (<replaceable>subquery</replaceable>)
12778
</synopsis>
12779
12780
  <para>
12781
   The left-hand side of this form of <token>ANY</token> is a row constructor,
12782
   as described in <xref linkend="sql-syntax-row-constructors">.
12783
   The right-hand side is a parenthesized
12784
   subquery, which must return exactly as many columns as there are
12785
   expressions in the left-hand row.  The left-hand expressions are
12786
   evaluated and compared row-wise to each row of the subquery result,
12787
   using the given <replaceable>operator</replaceable>.
12788
   The result of <token>ANY</token> is <quote>true</> if the comparison
12789
   returns true for any subquery row.
12790
   The result is <quote>false</> if the comparison returns false for every
12791
   subquery row (including the case where the subquery returns no
12792
   rows).
12793
   The result is NULL if the comparison does not return true for any row,
12794
   and it returns NULL for at least one row.
12795
  </para>
12796
12797
  <para>
12798
   See <xref linkend="row-wise-comparison"> for details about the meaning
12799
   of a row-wise comparison.
12800
  </para>
12801
  </sect2>
12802
12803
  <sect2 id="functions-subquery-all">
12804
   <title><literal>ALL</literal></title>
12805
12806
<synopsis>
12807
<replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
12808
</synopsis>
12809
12810
  <para>
12811
   The right-hand side is a parenthesized
12812
   subquery, which must return exactly one column.  The left-hand expression
12813
   is evaluated and compared to each row of the subquery result using the
12814
   given <replaceable>operator</replaceable>, which must yield a Boolean
12815
   result.
12816
   The result of <token>ALL</token> is <quote>true</> if all rows yield true
12817
   (including the case where the subquery returns no rows).
12818
   The result is <quote>false</> if any false result is found.
12819
   The result is NULL if the comparison does not return false for any row,
12820
   and it returns NULL for at least one row.
12821
  </para>
12822
12823
  <para>
12824
   <token>NOT IN</token> is equivalent to <literal>&lt;&gt; ALL</literal>.
12825
  </para>
12826
12827
  <para>
12828
   As with <token>EXISTS</token>, it's unwise to assume that the subquery will
12829
   be evaluated completely.
12830
  </para>
12831
12832
<synopsis>
12833
<replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
12834
</synopsis>
12835
12836
  <para>
12837
   The left-hand side of this form of <token>ALL</token> is a row constructor,
12838
   as described in <xref linkend="sql-syntax-row-constructors">.
12839
   The right-hand side is a parenthesized
12840
   subquery, which must return exactly as many columns as there are
12841
   expressions in the left-hand row.  The left-hand expressions are
12842
   evaluated and compared row-wise to each row of the subquery result,
12843
   using the given <replaceable>operator</replaceable>.
12844
   The result of <token>ALL</token> is <quote>true</> if the comparison
12845
   returns true for all subquery rows (including the
12846
   case where the subquery returns no rows).
12847
   The result is <quote>false</> if the comparison returns false for any
12848
   subquery row.
12849
   The result is NULL if the comparison does not return false for any
12850
   subquery row, and it returns NULL for at least one row.
12851
  </para>
12852
12853
  <para>
12854
   See <xref linkend="row-wise-comparison"> for details about the meaning
12855
   of a row-wise comparison.
12856
  </para>
12857
  </sect2>
12858
12859
  <sect2>
12860
   <title>Row-wise Comparison</title>
12861
12862
   <indexterm zone="functions-subquery">
12863
    <primary>comparison</primary>
12864
    <secondary>subquery result row</secondary>
12865
   </indexterm>
12866
12867
<synopsis>
12868
<replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> (<replaceable>subquery</replaceable>)
12869
</synopsis>
12870
12871
  <para>
12872
   The left-hand side is a row constructor,
12873
   as described in <xref linkend="sql-syntax-row-constructors">.
12874
   The right-hand side is a parenthesized subquery, which must return exactly
12875
   as many columns as there are expressions in the left-hand row. Furthermore,
12876
   the subquery cannot return more than one row.  (If it returns zero rows,
12877
   the result is taken to be null.)  The left-hand side is evaluated and
12878
   compared row-wise to the single subquery result row.
12879
  </para>
12880
12881
  <para>
12882
   See <xref linkend="row-wise-comparison"> for details about the meaning
12883
   of a row-wise comparison.
12884
  </para>
12885
  </sect2>
12886
 </sect1>
12887
12888
12889
 <sect1 id="functions-comparisons">
12890
  <title>Row and Array Comparisons</title>
12891
12892
  <indexterm>
12893
   <primary>IN</primary>
12894
  </indexterm>
12895
12896
  <indexterm>
12897
   <primary>NOT IN</primary>
12898
  </indexterm>
12899
12900
  <indexterm>
12901
   <primary>ANY</primary>
12902
  </indexterm>
12903
12904
  <indexterm>
12905
   <primary>ALL</primary>
12906
  </indexterm>
12907
12908
  <indexterm>
12909
   <primary>SOME</primary>
12910
  </indexterm>
12911
12912
  <indexterm>
12913
   <primary>row-wise comparison</primary>
12914
  </indexterm>
12915
12916
  <indexterm>
12917
   <primary>comparison</primary>
12918
   <secondary>row-wise</secondary>
12919
  </indexterm>
12920
12921
  <indexterm>
12922
   <primary>IS DISTINCT FROM</primary>
12923
  </indexterm>
12924
12925
  <indexterm>
12926
   <primary>IS NOT DISTINCT FROM</primary>
12927
  </indexterm>
12928
12929
  <para>
12930
   This section describes several specialized constructs for making
12931
   multiple comparisons between groups of values.  These forms are
12932
   syntactically related to the subquery forms of the previous section,
12933
   but do not involve subqueries.
12934
   The forms involving array subexpressions are
12935
   <productname>PostgreSQL</productname> extensions; the rest are
12936
   <acronym>SQL</acronym>-compliant.
12937
   All of the expression forms documented in this section return
12938
   Boolean (true/false) results.
12939
  </para>
12940
12941
  <sect2>
12942
   <title><literal>IN</literal></title>
12943
12944
<synopsis>
12945
<replaceable>expression</replaceable> IN (<replaceable>value</replaceable> <optional>, ...</optional>)
12946
</synopsis>
12947
12948
  <para>
12949
   The right-hand side is a parenthesized list
12950
   of scalar expressions.  The result is <quote>true</> if the left-hand expression's
12951
   result is equal to any of the right-hand expressions.  This is a shorthand
12952
   notation for
12953
12954
<synopsis>
12955
<replaceable>expression</replaceable> = <replaceable>value1</replaceable>
12956
OR
12957
<replaceable>expression</replaceable> = <replaceable>value2</replaceable>
12958
OR
12959
...
12960
</synopsis>
12961
  </para>
12962
12963
  <para>
12964
   Note that if the left-hand expression yields null, or if there are
12965
   no equal right-hand values and at least one right-hand expression yields
12966
   null, the result of the <token>IN</token> construct will be null, not false.
12967
   This is in accordance with SQL's normal rules for Boolean combinations
12968
   of null values.
12969
  </para>
12970
  </sect2>
12971
12972
  <sect2>
12973
   <title><literal>NOT IN</literal></title>
12974
12975
<synopsis>
12976
<replaceable>expression</replaceable> NOT IN (<replaceable>value</replaceable> <optional>, ...</optional>)
12977
</synopsis>
12978
12979
  <para>
12980
   The right-hand side is a parenthesized list
12981
   of scalar expressions.  The result is <quote>true</quote> if the left-hand expression's
12982
   result is unequal to all of the right-hand expressions.  This is a shorthand
12983
   notation for
12984
12985
<synopsis>
12986
<replaceable>expression</replaceable> &lt;&gt; <replaceable>value1</replaceable>
12987
AND
12988
<replaceable>expression</replaceable> &lt;&gt; <replaceable>value2</replaceable>
12989
AND
12990
...
12991
</synopsis>
12992
  </para>
12993
12994
  <para>
12995
   Note that if the left-hand expression yields null, or if there are
12996
   no equal right-hand values and at least one right-hand expression yields
12997
   null, the result of the <token>NOT IN</token> construct will be null, not true
12998
   as one might naively expect.
12999
   This is in accordance with SQL's normal rules for Boolean combinations
13000
   of null values.
13001
  </para>
13002
13003
  <tip>
13004
  <para>
13005
   <literal>x NOT IN y</literal> is equivalent to <literal>NOT (x IN y)</literal> in all
13006
   cases.  However, null values are much more likely to trip up the novice when
13007
   working with <token>NOT IN</token> than when working with <token>IN</token>.
13008
   It is best to express your condition positively if possible.
13009
  </para>
13010
  </tip>
13011
  </sect2>
13012
13013
  <sect2>
13014
   <title><literal>ANY</literal>/<literal>SOME</literal> (array)</title>
13015
13016
<synopsis>
13017
<replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>array expression</replaceable>)
13018
<replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>array expression</replaceable>)
13019
</synopsis>
13020
13021
  <para>
13022
   The right-hand side is a parenthesized expression, which must yield an
13023
   array value.
13024
   The left-hand expression
13025
   is evaluated and compared to each element of the array using the
13026
   given <replaceable>operator</replaceable>, which must yield a Boolean
13027
   result.
13028
   The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
13029
   The result is <quote>false</> if no true result is found (including the
13030
   case where the array has zero elements).
13031
  </para>
13032
13033
  <para>
13034
   If the array expression yields a null array, the result of
13035
   <token>ANY</token> will be null.  If the left-hand expression yields null,
13036
   the result of <token>ANY</token> is ordinarily null (though a non-strict
13037
   comparison operator could possibly yield a different result).
13038
   Also, if the right-hand array contains any null elements and no true
13039
   comparison result is obtained, the result of <token>ANY</token>
13040
   will be null, not false (again, assuming a strict comparison operator).
13041
   This is in accordance with SQL's normal rules for Boolean combinations
13042
   of null values.
13043
  </para>
13044
13045
  <para>
13046
   <token>SOME</token> is a synonym for <token>ANY</token>.
13047
  </para>
13048
  </sect2>
13049
13050
  <sect2>
13051
   <title><literal>ALL</literal> (array)</title>
13052
13053
<synopsis>
13054
<replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>array expression</replaceable>)
13055
</synopsis>
13056
13057
  <para>
13058
   The right-hand side is a parenthesized expression, which must yield an
13059
   array value.
13060
   The left-hand expression
13061
   is evaluated and compared to each element of the array using the
13062
   given <replaceable>operator</replaceable>, which must yield a Boolean
13063
   result.
13064
   The result of <token>ALL</token> is <quote>true</> if all comparisons yield true
13065
   (including the case where the array has zero elements).
13066
   The result is <quote>false</> if any false result is found.
13067
  </para>
13068
13069
  <para>
13070
   If the array expression yields a null array, the result of
13071
   <token>ALL</token> will be null.  If the left-hand expression yields null,
13072
   the result of <token>ALL</token> is ordinarily null (though a non-strict
13073
   comparison operator could possibly yield a different result).
13074
   Also, if the right-hand array contains any null elements and no false
13075
   comparison result is obtained, the result of <token>ALL</token>
13076
   will be null, not true (again, assuming a strict comparison operator).
13077
   This is in accordance with SQL's normal rules for Boolean combinations
13078
   of null values.
13079
  </para>
13080
  </sect2>
13081
13082
  <sect2 id="row-wise-comparison">
13083
   <title>Row-wise Comparison</title>
13084
13085
<synopsis>
13086
<replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> <replaceable>row_constructor</replaceable>
13087
</synopsis>
13088
13089
  <para>
13090
   Each side is a row constructor,
13091
   as described in <xref linkend="sql-syntax-row-constructors">.
13092
   The two row values must have the same number of fields.
13093
   Each side is evaluated and they are compared row-wise.  Row comparisons
13094
   are allowed when the <replaceable>operator</replaceable> is
13095
   <literal>=</>,
13096
   <literal>&lt;&gt;</>,
13097
   <literal>&lt;</>,
13098
   <literal>&lt;=</>,
13099
   <literal>&gt;</> or
13100
   <literal>&gt;=</>,
13101
   or has semantics similar to one of these.  (To be specific, an operator
13102
   can be a row comparison operator if it is a member of a B-tree operator
13103
   class, or is the negator of the <literal>=</> member of a B-tree operator
13104
   class.)
13105
  </para>
13106
13107
  <para>
13108
   The <literal>=</> and <literal>&lt;&gt;</> cases work slightly differently
13109
   from the others.  Two rows are considered
13110
   equal if all their corresponding members are non-null and equal; the rows
13111
   are unequal if any corresponding members are non-null and unequal;
13112
   otherwise the result of the row comparison is unknown (null).
13113
  </para>
13114
13115
  <para>
13116
   For the <literal>&lt;</>, <literal>&lt;=</>, <literal>&gt;</> and
13117
   <literal>&gt;=</> cases, the row elements are compared left-to-right,
13118
   stopping as soon as an unequal or null pair of elements is found.
13119
   If either of this pair of elements is null, the result of the
13120
   row comparison is unknown (null); otherwise comparison of this pair
13121
   of elements determines the result.  For example,
13122
   <literal>ROW(1,2,NULL) &lt; ROW(1,3,0)</>
13123
   yields true, not null, because the third pair of elements are not
13124
   considered.
13125
  </para>
13126
13127
  <note>
13128
   <para>
13129
    Prior to <productname>PostgreSQL</productname> 8.2, the
13130
    <literal>&lt;</>, <literal>&lt;=</>, <literal>&gt;</> and <literal>&gt;=</>
13131
    cases were not handled per SQL specification.  A comparison like
13132
    <literal>ROW(a,b) &lt; ROW(c,d)</>
13133
    was implemented as
13134
    <literal>a &lt; c AND b &lt; d</>
13135
    whereas the correct behavior is equivalent to
13136
    <literal>a &lt; c OR (a = c AND b &lt; d)</>.
13137
   </para>
13138
  </note>
13139
13140
<synopsis>
13141
<replaceable>row_constructor</replaceable> IS DISTINCT FROM <replaceable>row_constructor</replaceable>
13142
</synopsis>
13143
13144
  <para>
13145
   This construct is similar to a <literal>&lt;&gt;</literal> row comparison,
13146
   but it does not yield null for null inputs.  Instead, any null value is
13147
   considered unequal to (distinct from) any non-null value, and any two
13148
   nulls are considered equal (not distinct).  Thus the result will
13149
   either be true or false, never null.
13150
  </para>
13151
13152
<synopsis>
13153
<replaceable>row_constructor</replaceable> IS NOT DISTINCT FROM <replaceable>row_constructor</replaceable>
13154
</synopsis>
13155
13156
  <para>
13157
   This construct is similar to a <literal>=</literal> row comparison,
13158
   but it does not yield null for null inputs.  Instead, any null value is
13159
   considered unequal to (distinct from) any non-null value, and any two
13160
   nulls are considered equal (not distinct).  Thus the result will always
13161
   be either true or false, never null.
13162
  </para>
13163
13164
  <note>
13165
   <para>
13166
    The SQL specification requires row-wise comparison to return NULL if the
13167
    result depends on comparing two NULL values or a NULL and a non-NULL.
13168
    <productname>PostgreSQL</productname> does this only when comparing the
13169
    results of two row constructors or comparing a row constructor to the
13170
    output of a subquery (as in <xref linkend="functions-subquery">).
13171
    In other contexts where two composite-type values are compared, two
13172
    NULL field values are considered equal, and a NULL is considered larger
13173
    than a non-NULL.  This is necessary in order to have consistent sorting
13174
    and indexing behavior for composite types.
13175
   </para>
13176
  </note>
13177
13178
  </sect2>
13179
 </sect1>
13180
13181
 <sect1 id="functions-srf">
13182
  <title>Set Returning Functions</title>
13183
13184
  <indexterm zone="functions-srf">
13185
   <primary>set returning functions</primary>
13186
   <secondary>functions</secondary>
13187
  </indexterm>
13188
13189
  <indexterm>
13190
   <primary>generate_series</primary>
13191
  </indexterm>
13192
13193
  <para>
13194
   This section describes functions that possibly return more than one row.
13195
   The most widely used functions in this class are series generating
13196
   functions, as detailed in <xref linkend="functions-srf-series"> and
13197
   <xref linkend="functions-srf-subscripts">.  Other, more specialized
13198
   set-returning functions are described elsewhere in this manual.
13199
  </para>
13200
13201
  <table id="functions-srf-series">
13202
   <title>Series Generating Functions</title>
13203
   <tgroup cols="4">
13204
    <thead>
13205
     <row>
13206
      <entry>Function</entry>
13207
      <entry>Argument Type</entry>
13208
      <entry>Return Type</entry>
13209
      <entry>Description</entry>
13210
     </row>
13211
    </thead>
13212
13213
    <tbody>
13214
     <row>
13215
      <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>)</function></literal></entry>
13216
      <entry><type>int</type> or <type>bigint</type></entry>
13217
      <entry><type>setof int</type> or <type>setof bigint</type> (same as argument type)</entry>
13218
      <entry>
13219
       Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
13220
       with a step size of one
13221
      </entry>
13222
     </row>
13223
13224
     <row>
13225
      <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>, <parameter>step</parameter>)</function></literal></entry>
13226
      <entry><type>int</type> or <type>bigint</type></entry>
13227
      <entry><type>setof int</type> or <type>setof bigint</type> (same as argument type)</entry>
13228
      <entry>
13229
       Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
13230
       with a step size of <parameter>step</parameter>
13231
      </entry>
13232
     </row>
13233
13234
     <row>
13235
      <entry><literal><function>generate_series(<parameter>start</parameter>, <parameter>stop</parameter>, <parameter>step</parameter> <type>interval</>)</function></literal></entry>
13236
      <entry><type>timestamp</type> or <type>timestamp with time zone</type></entry>
13237
      <entry><type>setof timestamp</type> or <type>setof timestamp with time zone</type> (same as argument type)</entry>
13238
      <entry>
13239
       Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
13240
       with a step size of <parameter>step</parameter>
13241
      </entry>
13242
     </row>
13243
13244
    </tbody>
13245
   </tgroup>
13246
  </table>
13247
13248
  <para>
13249
   When <parameter>step</parameter> is positive, zero rows are returned if
13250
   <parameter>start</parameter> is greater than <parameter>stop</parameter>.
13251
   Conversely, when <parameter>step</parameter> is negative, zero rows are
13252
   returned if <parameter>start</parameter> is less than <parameter>stop</parameter>.
13253
   Zero rows are also returned for <literal>NULL</literal> inputs. It is an error
13254
   for <parameter>step</parameter> to be zero. Some examples follow:
13255
<programlisting>
13256
SELECT * FROM generate_series(2,4);
13257
 generate_series
13258
-----------------
13259
               2
13260
               3
13261
               4
13262
(3 rows)
13263
13264
SELECT * FROM generate_series(5,1,-2);
13265
 generate_series
13266
-----------------
13267
               5
13268
               3
13269
               1
13270
(3 rows)
13271
13272
SELECT * FROM generate_series(4,3);
13273
 generate_series
13274
-----------------
13275
(0 rows)
13276
13277
-- this example relies on the date-plus-integer operator
13278
SELECT current_date + s.a AS dates FROM generate_series(0,14,7) AS s(a);
13279
   dates
13280
------------
13281
 2004-02-05
13282
 2004-02-12
13283
 2004-02-19
13284
(3 rows)
13285
13286
SELECT * FROM generate_series('2008-03-01 00:00'::timestamp,
13287
                              '2008-03-04 12:00', '10 hours');
13288
   generate_series   
13289
---------------------
13290
 2008-03-01 00:00:00
13291
 2008-03-01 10:00:00
13292
 2008-03-01 20:00:00
13293
 2008-03-02 06:00:00
13294
 2008-03-02 16:00:00
13295
 2008-03-03 02:00:00
13296
 2008-03-03 12:00:00
13297
 2008-03-03 22:00:00
13298
 2008-03-04 08:00:00
13299
(9 rows)
13300
</programlisting>
13301
  </para>
13302
13303
  <table id="functions-srf-subscripts">
13304
   <title>Subscript Generating Functions</title>
13305
   <tgroup cols="3">
13306
    <thead>
13307
     <row>
13308
      <entry>Function</entry>
13309
      <entry>Return Type</entry>
13310
      <entry>Description</entry>
13311
     </row>
13312
    </thead>
13313
13314
    <tbody>
13315
     <row>
13316
      <entry><literal><function>generate_subscripts(<parameter>array anyarray</parameter>, <parameter>dim int</parameter>)</function></literal></entry>
13317
      <entry><type>setof int</type></entry>
13318
      <entry>
13319
       Generate a series comprising the given array's subscripts.
13320
      </entry>
13321
     </row>
13322
13323
     <row>
13324
      <entry><literal><function>generate_subscripts(<parameter>array anyarray</parameter>, <parameter>dim int</parameter>, <parameter>reverse boolean</parameter>)</function></literal></entry>
13325
      <entry><type>setof int</type></entry>
13326
      <entry>
13327
       Generate a series comprising the given array's subscripts. When
13328
       <parameter>reverse</parameter> is true, the series is returned in
13329
       reverse order.
13330
      </entry>
13331
     </row>
13332
13333
    </tbody>
13334
   </tgroup>
13335
  </table>
13336
13337
  <indexterm>
13338
   <primary>generate_subscripts</primary>
13339
  </indexterm>
13340
13341
  <para>
13342
   <function>generate_subscripts</> is a convenience function that generates
13343
   the set of valid subscripts for the specified dimension of the given
13344
   array.
13345
   Zero rows are returned for arrays that do not have the requested dimension,
13346
   or for NULL arrays (but valid subscripts are returned for NULL array
13347
   elements).  Some examples follow:
13348
<programlisting>
13349
-- basic usage
13350
SELECT generate_subscripts('{NULL,1,NULL,2}'::int[], 1) AS s;
13351
 s 
13352
---
13353
 1
13354
 2
13355
 3
13356
 4
13357
(4 rows)
13358
13359
-- presenting an array, the subscript and the subscripted
13360
-- value requires a subquery
13361
SELECT * FROM arrays;
13362
         a          
13363
--------------------
13364
 {-1,-2}
13365
 {100,200,300}
13366
(2 rows)
13367
13368
SELECT a AS array, s AS subscript, a[s] AS value
13369
FROM (SELECT generate_subscripts(a, 1) AS s, a FROM arrays) foo;
13370
     array     | subscript | value
13371
---------------+-----------+-------
13372
 {-1,-2}       |         1 |    -1
13373
 {-1,-2}       |         2 |    -2
13374
 {100,200,300} |         1 |   100
13375
 {100,200,300} |         2 |   200
13376
 {100,200,300} |         3 |   300
13377
(5 rows)
13378
13379
-- unnest a 2D array
13380
CREATE OR REPLACE FUNCTION unnest2(anyarray)
13381
RETURNS SETOF anyelement AS $$
13382
select $1[i][j]
13383
   from generate_subscripts($1,1) g1(i),
13384
        generate_subscripts($1,2) g2(j);
13385
$$ LANGUAGE sql IMMUTABLE;
13386
CREATE FUNCTION
13387
postgres=# SELECT * FROM unnest2(ARRAY[[1,2],[3,4]]);
13388
 unnest2 
13389
---------
13390
       1
13391
       2
13392
       3
13393
       4
13394
(4 rows)
13395
</programlisting>
13396
  </para>
13397
13398
 </sect1>
13399
13400
 <sect1 id="functions-info">
13401
  <title>System Information Functions</title>
13402
13403
  <para>
13404
   <xref linkend="functions-info-session-table"> shows several
13405
   functions that extract session and system information.
13406
  </para>
13407
13408
  <para>
13409
   In addition to the functions listed in this section, there are a number of
13410
   functions related to the statistics system that also provide system
13411
   information. See <xref linkend="monitoring-stats-views"> for more
13412
   information.
13413
  </para>
13414
13415
   <table id="functions-info-session-table">
13416
    <title>Session Information Functions</title>
13417
    <tgroup cols="3">
13418
     <thead>
13419
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
13420
     </thead>
13421
13422
     <tbody>
13423
      <row>
13424
       <entry><literal><function>current_catalog</function></literal></entry>
13425
       <entry><type>name</type></entry>
13426
       <entry>name of current database (called <quote>catalog</quote> in the SQL standard)</entry>
13427
      </row>
13428
13429
      <row>
13430
       <entry><literal><function>current_database()</function></literal></entry>
13431
       <entry><type>name</type></entry>
13432
       <entry>name of current database</entry>
13433
      </row>
13434
13435
      <row>
13436
       <entry><literal><function>current_query()</function></literal></entry>
13437
       <entry><type>text</type></entry>
13438
       <entry>text of the currently executing query, as submitted
13439
       by the client (might contain more than one statement)</entry>
13440
      </row>
13441
13442
      <row>
13443
       <entry><literal><function>current_schema</function>[()]</literal></entry>
13444
       <entry><type>name</type></entry>
13445
       <entry>name of current schema</entry>
13446
      </row>
13447
13448
      <row>
13449
       <entry><literal><function>current_schemas(<type>boolean</type>)</function></literal></entry>
13450
       <entry><type>name[]</type></entry>
13451
       <entry>names of schemas in search path, optionally including implicit schemas</entry>
13452
      </row>
13453
13454
      <row>
13455
       <entry><literal><function>current_user</function></literal></entry>
13456
       <entry><type>name</type></entry>
13457
       <entry>user name of current execution context</entry>
13458
      </row>
13459
13460
      <row>
13461
       <entry><literal><function>inet_client_addr()</function></literal></entry>
13462
       <entry><type>inet</type></entry>
13463
       <entry>address of the remote connection</entry>
13464
      </row>
13465
13466
      <row>
13467
       <entry><literal><function>inet_client_port()</function></literal></entry>
13468
       <entry><type>int</type></entry>
13469
       <entry>port of the remote connection</entry>
13470
      </row>
13471
13472
      <row>
13473
       <entry><literal><function>inet_server_addr()</function></literal></entry>
13474
       <entry><type>inet</type></entry>
13475
       <entry>address of the local connection</entry>
13476
      </row>
13477
13478
      <row>
13479
       <entry><literal><function>inet_server_port()</function></literal></entry>
13480
       <entry><type>int</type></entry>
13481
       <entry>port of the local connection</entry>
13482
      </row>
13483
13484
      <row>
13485
       <!-- See also the entry for this in monitoring.sgml -->
13486
       <entry><literal><function>pg_backend_pid()</function></literal></entry>
13487
       <entry><type>int</type></entry>
13488
       <entry>
13489
        Process ID of the server process attached to the current session
13490
       </entry>
13491
      </row>
13492
13493
      <row>
13494
       <entry><literal><function>pg_conf_load_time()</function></literal></entry>
13495
       <entry><type>timestamp with time zone</type></entry>
13496
       <entry>configuration load time</entry>
13497
      </row>
13498
13499
      <row>
13500
       <entry><literal><function>pg_is_other_temp_schema(<type>oid</type>)</function></literal></entry>
13501
       <entry><type>boolean</type></entry>
13502
       <entry>is schema another session's temporary schema?</entry>
13503
      </row>
13504
13505
      <row>
13506
       <entry><literal><function>pg_listening_channels()</function></literal></entry>
13507
       <entry><type>setof text</type></entry>
13508
       <entry>channel names that the session is currently listening on</entry>
13509
      </row>
13510
13511
      <row>
13512
       <entry><literal><function>pg_my_temp_schema()</function></literal></entry>
13513
       <entry><type>oid</type></entry>
13514
       <entry>OID of session's temporary schema, or 0 if none</entry>
13515
      </row>
13516
13517
      <row>
13518
       <entry><literal><function>pg_postmaster_start_time()</function></literal></entry>
13519
       <entry><type>timestamp with time zone</type></entry>
13520
       <entry>server start time</entry>
13521
      </row>
13522
13523
      <row>
13524
       <entry><literal><function>pg_trigger_depth()</function></literal></entry>
13525
       <entry><type>int</type></entry>
13526
       <entry>current nesting level of <productname>PostgreSQL</> triggers
13527
       (0 if not called, directly or indirectly, from inside a trigger)</entry>
13528
      </row>
13529
13530
      <row>
13531
       <entry><literal><function>session_user</function></literal></entry>
13532
       <entry><type>name</type></entry>
13533
       <entry>session user name</entry>
13534
      </row>
13535
13536
      <row>
13537
       <entry><literal><function>user</function></literal></entry>
13538
       <entry><type>name</type></entry>
13539
       <entry>equivalent to <function>current_user</function></entry>
13540
      </row>
13541
13542
      <row>
13543
       <entry><literal><function>version()</function></literal></entry>
13544
       <entry><type>text</type></entry>
13545
       <entry><productname>PostgreSQL</> version information</entry>
13546
      </row>
13547
     </tbody>
13548
    </tgroup>
13549
   </table>
13550
13551
   <note>
13552
    <para>
13553
     <function>current_catalog</function>, <function>current_schema</function>,
13554
     <function>current_user</function>, <function>session_user</function>,
13555
     and <function>user</function> have special syntactic status
13556
     in <acronym>SQL</acronym>: they must be called without trailing
13557
     parentheses.  (In PostgreSQL, parentheses can optionally be used with
13558
     <function>current_schema</function>, but not with the others.)
13559
    </para>
13560
   </note>
13561
13562
   <indexterm>
13563
    <primary>current_catalog</primary>
13564
   </indexterm>
13565
13566
   <indexterm>
13567
    <primary>current_database</primary>
13568
   </indexterm>
13569
13570
   <indexterm>
13571
    <primary>current_query</primary>
13572
   </indexterm>
13573
13574
   <indexterm>
13575
    <primary>current_schema</primary>
13576
   </indexterm>
13577
13578
   <indexterm>
13579
    <primary>current_schemas</primary>
13580
   </indexterm>
13581
13582
   <indexterm>
13583
    <primary>current_user</primary>
13584
   </indexterm>
13585
13586
   <indexterm>
13587
    <primary>pg_backend_pid</primary>
13588
   </indexterm>
13589
13590
   <indexterm>
13591
    <primary>schema</primary>
13592
    <secondary>current</secondary>
13593
   </indexterm>
13594
13595
   <indexterm>
13596
    <primary>search path</primary>
13597
    <secondary>current</secondary>
13598
   </indexterm>
13599
13600
   <indexterm>
13601
    <primary>session_user</primary>
13602
   </indexterm>
13603
13604
   <indexterm>
13605
    <primary>user</primary>
13606
    <secondary>current</secondary>
13607
   </indexterm>
13608
13609
   <indexterm>
13610
    <primary>user</primary>
13611
   </indexterm>
13612
13613
   <para>
13614
    The <function>session_user</function> is normally the user who initiated
13615
    the current database connection; but superusers can change this setting
13616
    with <xref linkend="sql-set-session-authorization">.
13617
    The <function>current_user</function> is the user identifier
13618
    that is applicable for permission checking. Normally it is equal
13619
    to the session user, but it can be changed with
13620
    <xref linkend="sql-set-role">.
13621
    It also changes during the execution of
13622
    functions with the attribute <literal>SECURITY DEFINER</literal>.
13623
    In Unix parlance, the session user is the <quote>real user</quote> and
13624
    the current user is the <quote>effective user</quote>.
13625
   </para>
13626
13627
   <para>
13628
    <function>current_schema</function> returns the name of the schema that is
13629
    first in the search path (or a null value if the search path is
13630
    empty).  This is the schema that will be used for any tables or
13631
    other named objects that are created without specifying a target schema.
13632
    <function>current_schemas(boolean)</function> returns an array of the names of all
13633
    schemas presently in the search path.  The Boolean option determines whether or not
13634
    implicitly included system schemas such as <literal>pg_catalog</> are included in the
13635
    returned search path.
13636
   </para>
13637
13638
   <note>
13639
    <para>
13640
     The search path can be altered at run time.  The command is:
13641
<programlisting>
13642
SET search_path TO <replaceable>schema</> <optional>, <replaceable>schema</>, ...</optional>
13643
</programlisting>
13644
    </para>
13645
   </note>
13646
13647
   <indexterm>
13648
    <primary>pg_listening_channels</primary>
13649
   </indexterm>
13650
13651
   <para>
13652
    <function>pg_listening_channels</function> returns a set of names of
13653
    channels that the current session is listening to.  See <xref
13654
    linkend="sql-listen"> for more information.
13655
   </para>
13656
13657
   <indexterm>
13658
    <primary>inet_client_addr</primary>
13659
   </indexterm>
13660
13661
   <indexterm>
13662
    <primary>inet_client_port</primary>
13663
   </indexterm>
13664
13665
   <indexterm>
13666
    <primary>inet_server_addr</primary>
13667
   </indexterm>
13668
13669
   <indexterm>
13670
    <primary>inet_server_port</primary>
13671
   </indexterm>
13672
13673
   <para>
13674
     <function>inet_client_addr</function> returns the IP address of the
13675
     current client, and <function>inet_client_port</function> returns the
13676
     port number.
13677
     <function>inet_server_addr</function> returns the IP address on which
13678
     the server accepted the current connection, and
13679
     <function>inet_server_port</function> returns the port number.
13680
     All these functions return NULL if the current connection is via a
13681
     Unix-domain socket.
13682
   </para>
13683
13684
   <indexterm>
13685
    <primary>pg_my_temp_schema</primary>
13686
   </indexterm>
13687
13688
   <indexterm>
13689
    <primary>pg_is_other_temp_schema</primary>
13690
   </indexterm>
13691
13692
   <para>
13693
    <function>pg_my_temp_schema</function> returns the OID of the current
13694
    session's temporary schema, or zero if it has none (because it has not
13695
    created any temporary tables).
13696
    <function>pg_is_other_temp_schema</function> returns true if the
13697
    given OID is the OID of another session's temporary schema.
13698
    (This can be useful, for example, to exclude other sessions' temporary
13699
    tables from a catalog display.)
13700
   </para>
13701
13702
   <indexterm>
13703
    <primary>pg_postmaster_start_time</primary>
13704
   </indexterm>
13705
13706
   <para>
13707
    <function>pg_postmaster_start_time</function> returns the
13708
    <type>timestamp with time zone</type> when the
13709
    server started.
13710
   </para>
13711
13712
   <indexterm>
13713
    <primary>pg_conf_load_time</primary>
13714
   </indexterm>
13715
13716
   <para>
13717
    <function>pg_conf_load_time</function> returns the
13718
    <type>timestamp with time zone</type> when the
13719
    server configuration files were last loaded.
13720
    (If the current session was alive at the time, this will be the time
13721
    when the session itself re-read the configuration files, so the
13722
    reading will vary a little in different sessions.  Otherwise it is
13723
    the time when the postmaster process re-read the configuration files.)
13724
   </para>
13725
13726
   <indexterm>
13727
    <primary>version</primary>
13728
   </indexterm>
13729
13730
   <para>
13731
    <function>version</function> returns a string describing the
13732
    <productname>PostgreSQL</productname> server's version.
13733
   </para>
13734
13735
  <indexterm>
13736
   <primary>privilege</primary>
13737
   <secondary>querying</secondary>
13738
  </indexterm>
13739
13740
  <para>
13741
   <xref linkend="functions-info-access-table"> lists functions that
13742
   allow the user to query object access privileges programmatically.
13743
   See <xref linkend="ddl-priv"> for more information about
13744
   privileges.
13745
  </para>
13746
13747
   <table id="functions-info-access-table">
13748
    <title>Access Privilege Inquiry Functions</title>
13749
    <tgroup cols="3">
13750
     <thead>
13751
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
13752
     </thead>
13753
13754
     <tbody>
13755
      <row>
13756
       <entry><literal><function>has_any_column_privilege</function>(<parameter>user</parameter>,
13757
                                  <parameter>table</parameter>,
13758
                                  <parameter>privilege</parameter>)</literal>
13759
       </entry>
13760
       <entry><type>boolean</type></entry>
13761
       <entry>does user have privilege for any column of table</entry>
13762
      </row>
13763
      <row>
13764
       <entry><literal><function>has_any_column_privilege</function>(<parameter>table</parameter>,
13765
                                  <parameter>privilege</parameter>)</literal>
13766
       </entry>
13767
       <entry><type>boolean</type></entry>
13768
       <entry>does current user have privilege for any column of table</entry>
13769
      </row>
13770
      <row>
13771
       <entry><literal><function>has_column_privilege</function>(<parameter>user</parameter>,
13772
                                  <parameter>table</parameter>,
13773
                                  <parameter>column</parameter>,
13774
                                  <parameter>privilege</parameter>)</literal>
13775
       </entry>
13776
       <entry><type>boolean</type></entry>
13777
       <entry>does user have privilege for column</entry>
13778
      </row>
13779
      <row>
13780
       <entry><literal><function>has_column_privilege</function>(<parameter>table</parameter>,
13781
                                  <parameter>column</parameter>,
13782
                                  <parameter>privilege</parameter>)</literal>
13783
       </entry>
13784
       <entry><type>boolean</type></entry>
13785
       <entry>does current user have privilege for column</entry>
13786
      </row>
13787
      <row>
13788
       <entry><literal><function>has_database_privilege</function>(<parameter>user</parameter>,
13789
                                  <parameter>database</parameter>,
13790
                                  <parameter>privilege</parameter>)</literal>
13791
       </entry>
13792
       <entry><type>boolean</type></entry>
13793
       <entry>does user have privilege for database</entry>
13794
      </row>
13795
      <row>
13796
       <entry><literal><function>has_database_privilege</function>(<parameter>database</parameter>,
13797
                                  <parameter>privilege</parameter>)</literal>
13798
       </entry>
13799
       <entry><type>boolean</type></entry>
13800
       <entry>does current user have privilege for database</entry>
13801
      </row>
13802
      <row>
13803
       <entry><literal><function>has_foreign_data_wrapper_privilege</function>(<parameter>user</parameter>,
13804
                                  <parameter>fdw</parameter>,
13805
                                  <parameter>privilege</parameter>)</literal>
13806
       </entry>
13807
       <entry><type>boolean</type></entry>
13808
       <entry>does user have privilege for foreign-data wrapper</entry>
13809
      </row>
13810
      <row>
13811
       <entry><literal><function>has_foreign_data_wrapper_privilege</function>(<parameter>fdw</parameter>,
13812
                                  <parameter>privilege</parameter>)</literal>
13813
       </entry>
13814
       <entry><type>boolean</type></entry>
13815
       <entry>does current user have privilege for foreign-data wrapper</entry>
13816
      </row>
13817
      <row>
13818
       <entry><literal><function>has_function_privilege</function>(<parameter>user</parameter>,
13819
                                  <parameter>function</parameter>,
13820
                                  <parameter>privilege</parameter>)</literal>
13821
       </entry>
13822
       <entry><type>boolean</type></entry>
13823
       <entry>does user have privilege for function</entry>
13824
      </row>
13825
      <row>
13826
       <entry><literal><function>has_function_privilege</function>(<parameter>function</parameter>,
13827
                                  <parameter>privilege</parameter>)</literal>
13828
       </entry>
13829
       <entry><type>boolean</type></entry>
13830
       <entry>does current user have privilege for function</entry>
13831
      </row>
13832
      <row>
13833
       <entry><literal><function>has_language_privilege</function>(<parameter>user</parameter>,
13834
                                  <parameter>language</parameter>,
13835
                                  <parameter>privilege</parameter>)</literal>
13836
       </entry>
13837
       <entry><type>boolean</type></entry>
13838
       <entry>does user have privilege for language</entry>
13839
      </row>
13840
      <row>
13841
       <entry><literal><function>has_language_privilege</function>(<parameter>language</parameter>,
13842
                                  <parameter>privilege</parameter>)</literal>
13843
       </entry>
13844
       <entry><type>boolean</type></entry>
13845
       <entry>does current user have privilege for language</entry>
13846
      </row>
13847
      <row>
13848
       <entry><literal><function>has_schema_privilege</function>(<parameter>user</parameter>,
13849
                                  <parameter>schema</parameter>,
13850
                                  <parameter>privilege</parameter>)</literal>
13851
       </entry>
13852
       <entry><type>boolean</type></entry>
13853
       <entry>does user have privilege for schema</entry>
13854
      </row>
13855
      <row>
13856
       <entry><literal><function>has_schema_privilege</function>(<parameter>schema</parameter>,
13857
                                  <parameter>privilege</parameter>)</literal>
13858
       </entry>
13859
       <entry><type>boolean</type></entry>
13860
       <entry>does current user have privilege for schema</entry>
13861
      </row>
13862
      <row>
13863
       <entry><literal><function>has_sequence_privilege</function>(<parameter>user</parameter>,
13864
                                  <parameter>sequence</parameter>,
13865
                                  <parameter>privilege</parameter>)</literal>
13866
       </entry>
13867
       <entry><type>boolean</type></entry>
13868
       <entry>does user have privilege for sequence</entry>
13869
      </row>
13870
      <row>
13871
       <entry><literal><function>has_sequence_privilege</function>(<parameter>sequence</parameter>,
13872
                                  <parameter>privilege</parameter>)</literal>
13873
       </entry>
13874
       <entry><type>boolean</type></entry>
13875
       <entry>does current user have privilege for sequence</entry>
13876
      </row>
13877
      <row>
13878
       <entry><literal><function>has_server_privilege</function>(<parameter>user</parameter>,
13879
                                  <parameter>server</parameter>,
13880
                                  <parameter>privilege</parameter>)</literal>
13881
       </entry>
13882
       <entry><type>boolean</type></entry>
13883
       <entry>does user have privilege for foreign server</entry>
13884
      </row>
13885
      <row>
13886
       <entry><literal><function>has_server_privilege</function>(<parameter>server</parameter>,
13887
                                  <parameter>privilege</parameter>)</literal>
13888
       </entry>
13889
       <entry><type>boolean</type></entry>
13890
       <entry>does current user have privilege for foreign server</entry>
13891
      </row>
13892
      <row>
13893
       <entry><literal><function>has_table_privilege</function>(<parameter>user</parameter>,
13894
                                  <parameter>table</parameter>,
13895
                                  <parameter>privilege</parameter>)</literal>
13896
       </entry>
13897
       <entry><type>boolean</type></entry>
13898
       <entry>does user have privilege for table</entry>
13899
      </row>
13900
      <row>
13901
       <entry><literal><function>has_table_privilege</function>(<parameter>table</parameter>,
13902
                                  <parameter>privilege</parameter>)</literal>
13903
       </entry>
13904
       <entry><type>boolean</type></entry>
13905
       <entry>does current user have privilege for table</entry>
13906
      </row>
13907
      <row>
13908
       <entry><literal><function>has_tablespace_privilege</function>(<parameter>user</parameter>,
13909
                                  <parameter>tablespace</parameter>,
13910
                                  <parameter>privilege</parameter>)</literal>
13911
       </entry>
13912
       <entry><type>boolean</type></entry>
13913
       <entry>does user have privilege for tablespace</entry>
13914
      </row>
13915
      <row>
13916
       <entry><literal><function>has_tablespace_privilege</function>(<parameter>tablespace</parameter>,
13917
                                  <parameter>privilege</parameter>)</literal>
13918
       </entry>
13919
       <entry><type>boolean</type></entry>
13920
       <entry>does current user have privilege for tablespace</entry>
13921
      </row>
13922
      <row>
13923
       <entry><literal><function>pg_has_role</function>(<parameter>user</parameter>,
13924
                                  <parameter>role</parameter>,
13925
                                  <parameter>privilege</parameter>)</literal>
13926
       </entry>
13927
       <entry><type>boolean</type></entry>
13928
       <entry>does user have privilege for role</entry>
13929
      </row>
13930
      <row>
13931
       <entry><literal><function>pg_has_role</function>(<parameter>role</parameter>,
13932
                                  <parameter>privilege</parameter>)</literal>
13933
       </entry>
13934
       <entry><type>boolean</type></entry>
13935
       <entry>does current user have privilege for role</entry>
13936
      </row>
13937
     </tbody>
13938
    </tgroup>
13939
   </table>
13940
13941
   <indexterm>
13942
    <primary>has_any_column_privilege</primary>
13943
   </indexterm>
13944
   <indexterm>
13945
    <primary>has_column_privilege</primary>
13946
   </indexterm>
13947
   <indexterm>
13948
    <primary>has_database_privilege</primary>
13949
   </indexterm>
13950
   <indexterm>
13951
    <primary>has_function_privilege</primary>
13952
   </indexterm>
13953
   <indexterm>
13954
    <primary>has_foreign_data_wrapper_privilege</primary>
13955
   </indexterm>
13956
   <indexterm>
13957
    <primary>has_language_privilege</primary>
13958
   </indexterm>
13959
   <indexterm>
13960
    <primary>has_schema_privilege</primary>
13961
   </indexterm>
13962
   <indexterm>
13963
    <primary>has_server_privilege</primary>
13964
   </indexterm>
13965
   <indexterm>
13966
    <primary>has_sequence_privilege</primary>
13967
   </indexterm>
13968
   <indexterm>
13969
    <primary>has_table_privilege</primary>
13970
   </indexterm>
13971
   <indexterm>
13972
    <primary>has_tablespace_privilege</primary>
13973
   </indexterm>
13974
   <indexterm>
13975
    <primary>pg_has_role</primary>
13976
   </indexterm>
13977
13978
   <para>
13979
    <function>has_table_privilege</function> checks whether a user
13980
    can access a table in a particular way.  The user can be
13981
    specified by name, by OID (<literal>pg_authid.oid</literal>),
13982
    <literal>public</> to indicate the PUBLIC pseudo-role, or if the argument is
13983
    omitted
13984
    <function>current_user</function> is assumed.  The table can be specified
13985
    by name or by OID.  (Thus, there are actually six variants of
13986
    <function>has_table_privilege</function>, which can be distinguished by
13987
    the number and types of their arguments.)  When specifying by name,
13988
    the name can be schema-qualified if necessary.
13989
    The desired access privilege type
13990
    is specified by a text string, which must evaluate to one of the
13991
    values <literal>SELECT</literal>, <literal>INSERT</literal>,
13992
    <literal>UPDATE</literal>, <literal>DELETE</literal>, <literal>TRUNCATE</>,
13993
    <literal>REFERENCES</literal>, or <literal>TRIGGER</literal>.  Optionally,
13994
    <literal>WITH GRANT OPTION</> can be added to a privilege type to test
13995
    whether the privilege is held with grant option.  Also, multiple privilege
13996
    types can be listed separated by commas, in which case the result will
13997
    be <literal>true</> if any of the listed privileges is held.
13998
    (Case of the privilege string is not significant, and extra whitespace
13999
    is allowed between but not within privilege names.)
14000
    Some examples:
14001
<programlisting>
14002
SELECT has_table_privilege('myschema.mytable', 'select');
14003
SELECT has_table_privilege('joe', 'mytable', 'INSERT, SELECT WITH GRANT OPTION');
14004
</programlisting>
14005
   </para>
14006
14007
   <para>
14008
    <function>has_sequence_privilege</function> checks whether a user
14009
    can access a sequence in a particular way.  The possibilities for its
14010
    arguments are analogous to <function>has_table_privilege</function>.
14011
    The desired access privilege type must evaluate to one of
14012
    <literal>USAGE</literal>,
14013
    <literal>SELECT</literal>, or
14014
    <literal>UPDATE</literal>.
14015
   </para>
14016
14017
   <para>
14018
    <function>has_any_column_privilege</function> checks whether a user can
14019
    access any column of a table in a particular way.
14020
    Its argument possibilities
14021
    are analogous to <function>has_table_privilege</>,
14022
    except that the desired access privilege type must evaluate to some
14023
    combination of
14024
    <literal>SELECT</literal>,
14025
    <literal>INSERT</literal>,
14026
    <literal>UPDATE</literal>, or
14027
    <literal>REFERENCES</literal>.  Note that having any of these privileges
14028
    at the table level implicitly grants it for each column of the table,
14029
    so <function>has_any_column_privilege</function> will always return
14030
    <literal>true</> if <function>has_table_privilege</> does for the same
14031
    arguments.  But <function>has_any_column_privilege</> also succeeds if
14032
    there is a column-level grant of the privilege for at least one column.
14033
   </para>
14034
14035
   <para>
14036
    <function>has_column_privilege</function> checks whether a user
14037
    can access a column in a particular way.
14038
    Its argument possibilities
14039
    are analogous to <function>has_table_privilege</function>,
14040
    with the addition that the column can be specified either by name
14041
    or attribute number.
14042
    The desired access privilege type must evaluate to some combination of
14043
    <literal>SELECT</literal>,
14044
    <literal>INSERT</literal>,
14045
    <literal>UPDATE</literal>, or
14046
    <literal>REFERENCES</literal>.  Note that having any of these privileges
14047
    at the table level implicitly grants it for each column of the table.
14048
   </para>
14049
14050
   <para>
14051
    <function>has_database_privilege</function> checks whether a user
14052
    can access a database in a particular way.
14053
    Its argument possibilities
14054
    are analogous to <function>has_table_privilege</function>.
14055
    The desired access privilege type must evaluate to some combination of
14056
    <literal>CREATE</literal>,
14057
    <literal>CONNECT</literal>,
14058
    <literal>TEMPORARY</literal>, or
14059
    <literal>TEMP</literal> (which is equivalent to
14060
    <literal>TEMPORARY</literal>).
14061
   </para>
14062
14063
   <para>
14064
    <function>has_function_privilege</function> checks whether a user
14065
    can access a function in a particular way.
14066
    Its argument possibilities
14067
    are analogous to <function>has_table_privilege</function>.
14068
    When specifying a function by a text string rather than by OID,
14069
    the allowed input is the same as for the <type>regprocedure</> data type
14070
    (see <xref linkend="datatype-oid">).
14071
    The desired access privilege type must evaluate to
14072
    <literal>EXECUTE</literal>.
14073
    An example is:
14074
<programlisting>
14075
SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');
14076
</programlisting>
14077
   </para>
14078
14079
   <para>
14080
    <function>has_foreign_data_wrapper_privilege</function> checks whether a user
14081
    can access a foreign-data wrapper in a particular way.
14082
    Its argument possibilities
14083
    are analogous to <function>has_table_privilege</function>.
14084
    The desired access privilege type must evaluate to
14085
    <literal>USAGE</literal>.
14086
   </para>
14087
14088
   <para>
14089
    <function>has_language_privilege</function> checks whether a user
14090
    can access a procedural language in a particular way.
14091
    Its argument possibilities
14092
    are analogous to <function>has_table_privilege</function>.
14093
    The desired access privilege type must evaluate to
14094
    <literal>USAGE</literal>.
14095
   </para>
14096
14097
   <para>
14098
    <function>has_schema_privilege</function> checks whether a user
14099
    can access a schema in a particular way.
14100
    Its argument possibilities
14101
    are analogous to <function>has_table_privilege</function>.
14102
    The desired access privilege type must evaluate to some combination of
14103
    <literal>CREATE</literal> or
14104
    <literal>USAGE</literal>.
14105
   </para>
14106
14107
   <para>
14108
    <function>has_server_privilege</function> checks whether a user
14109
    can access a foreign server in a particular way.
14110
    Its argument possibilities
14111
    are analogous to <function>has_table_privilege</function>.
14112
    The desired access privilege type must evaluate to
14113
    <literal>USAGE</literal>.
14114
   </para>
14115
14116
   <para>
14117
    <function>has_tablespace_privilege</function> checks whether a user
14118
    can access a tablespace in a particular way.
14119
    Its argument possibilities
14120
    are analogous to <function>has_table_privilege</function>.
14121
    The desired access privilege type must evaluate to
14122
    <literal>CREATE</literal>.
14123
   </para>
14124
14125
   <para>
14126
    <function>pg_has_role</function> checks whether a user
14127
    can access a role in a particular way.
14128
    Its argument possibilities
14129
    are analogous to <function>has_table_privilege</function>,
14130
    except that <literal>public</> is not allowed as a user name.
14131
    The desired access privilege type must evaluate to some combination of
14132
    <literal>MEMBER</literal> or
14133
    <literal>USAGE</literal>.
14134
    <literal>MEMBER</literal> denotes direct or indirect membership in
14135
    the role (that is, the right to do <command>SET ROLE</>), while
14136
    <literal>USAGE</literal> denotes whether the privileges of the role
14137
    are immediately available without doing <command>SET ROLE</>.
14138
   </para>
14139
14140
  <para>
14141
   <xref linkend="functions-info-schema-table"> shows functions that
14142
   determine whether a certain object is <firstterm>visible</> in the
14143
   current schema search path.
14144
   For example, a table is said to be visible if its
14145
   containing schema is in the search path and no table of the same
14146
   name appears earlier in the search path.  This is equivalent to the
14147
   statement that the table can be referenced by name without explicit
14148
   schema qualification.  To list the names of all visible tables:
14149
<programlisting>
14150
SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
14151
</programlisting>
14152
  </para>
14153
14154
   <indexterm>
14155
    <primary>search path</primary>
14156
    <secondary>object visibility</secondary>
14157
   </indexterm>
14158
14159
   <table id="functions-info-schema-table">
14160
    <title>Schema Visibility Inquiry Functions</title>
14161
    <tgroup cols="3">
14162
     <thead>
14163
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
14164
     </thead>
14165
14166
     <tbody>
14167
      <row>
14168
       <entry><literal><function>pg_collation_is_visible(<parameter>collation_oid</parameter>)</function></literal>
14169
       </entry>
14170
       <entry><type>boolean</type></entry>
14171
       <entry>is collation visible in search path</entry>
14172
      </row>
14173
      <row>
14174
       <entry><literal><function>pg_conversion_is_visible(<parameter>conversion_oid</parameter>)</function></literal>
14175
       </entry>
14176
       <entry><type>boolean</type></entry>
14177
       <entry>is conversion visible in search path</entry>
14178
      </row>
14179
      <row>
14180
       <entry><literal><function>pg_function_is_visible(<parameter>function_oid</parameter>)</function></literal>
14181
       </entry>
14182
       <entry><type>boolean</type></entry>
14183
       <entry>is function visible in search path</entry>
14184
      </row>
14185
      <row>
14186
       <entry><literal><function>pg_opclass_is_visible(<parameter>opclass_oid</parameter>)</function></literal>
14187
       </entry>
14188
       <entry><type>boolean</type></entry>
14189
       <entry>is operator class visible in search path</entry>
14190
      </row>
14191
      <row>
14192
       <entry><literal><function>pg_operator_is_visible(<parameter>operator_oid</parameter>)</function></literal>
14193
       </entry>
14194
       <entry><type>boolean</type></entry>
14195
       <entry>is operator visible in search path</entry>
14196
      </row>
14197
      <row>
14198
       <entry><literal><function>pg_opfamily_is_visible(<parameter>opclass_oid</parameter>)</function></literal>
14199
       </entry>
14200
       <entry><type>boolean</type></entry>
14201
       <entry>is operator family visible in search path</entry>
14202
      </row>
14203
      <row>
14204
       <entry><literal><function>pg_table_is_visible(<parameter>table_oid</parameter>)</function></literal>
14205
       </entry>
14206
       <entry><type>boolean</type></entry>
14207
       <entry>is table visible in search path</entry>
14208
      </row>
14209
      <row>
14210
       <entry><literal><function>pg_ts_config_is_visible(<parameter>config_oid</parameter>)</function></literal>
14211
       </entry>
14212
       <entry><type>boolean</type></entry>
14213
       <entry>is text search configuration visible in search path</entry>
14214
      </row>
14215
      <row>
14216
       <entry><literal><function>pg_ts_dict_is_visible(<parameter>dict_oid</parameter>)</function></literal>
14217
       </entry>
14218
       <entry><type>boolean</type></entry>
14219
       <entry>is text search dictionary visible in search path</entry>
14220
      </row>
14221
      <row>
14222
       <entry><literal><function>pg_ts_parser_is_visible(<parameter>parser_oid</parameter>)</function></literal>
14223
       </entry>
14224
       <entry><type>boolean</type></entry>
14225
       <entry>is text search parser visible in search path</entry>
14226
      </row>
14227
      <row>
14228
       <entry><literal><function>pg_ts_template_is_visible(<parameter>template_oid</parameter>)</function></literal>
14229
       </entry>
14230
       <entry><type>boolean</type></entry>
14231
       <entry>is text search template visible in search path</entry>
14232
      </row>
14233
      <row>
14234
       <entry><literal><function>pg_type_is_visible(<parameter>type_oid</parameter>)</function></literal>
14235
       </entry>
14236
       <entry><type>boolean</type></entry>
14237
       <entry>is type (or domain) visible in search path</entry>
14238
      </row>
14239
     </tbody>
14240
    </tgroup>
14241
   </table>
14242
14243
   <indexterm>
14244
    <primary>pg_collation_is_visible</primary>
14245
   </indexterm>
14246
   <indexterm>
14247
    <primary>pg_conversion_is_visible</primary>
14248
   </indexterm>
14249
   <indexterm>
14250
    <primary>pg_function_is_visible</primary>
14251
   </indexterm>
14252
   <indexterm>
14253
    <primary>pg_opclass_is_visible</primary>
14254
   </indexterm>
14255
   <indexterm>
14256
    <primary>pg_operator_is_visible</primary>
14257
   </indexterm>
14258
   <indexterm>
14259
    <primary>pg_opfamily_is_visible</primary>
14260
   </indexterm>
14261
   <indexterm>
14262
    <primary>pg_table_is_visible</primary>
14263
   </indexterm>
14264
   <indexterm>
14265
    <primary>pg_ts_config_is_visible</primary>
14266
   </indexterm>
14267
   <indexterm>
14268
    <primary>pg_ts_dict_is_visible</primary>
14269
   </indexterm>
14270
   <indexterm>
14271
    <primary>pg_ts_parser_is_visible</primary>
14272
   </indexterm>
14273
   <indexterm>
14274
    <primary>pg_ts_template_is_visible</primary>
14275
   </indexterm>
14276
   <indexterm>
14277
    <primary>pg_type_is_visible</primary>
14278
   </indexterm>
14279
14280
   <para>
14281
    Each function performs the visibility check for one type of database
14282
    object.  Note that <function>pg_table_is_visible</function> can also be used
14283
    with views, indexes and sequences; <function>pg_type_is_visible</function>
14284
    can also be used with domains. For functions and operators, an object in
14285
    the search path is visible if there is no object of the same name
14286
    <emphasis>and argument data type(s)</> earlier in the path.  For operator
14287
    classes, both name and associated index access method are considered.
14288
   </para>
14289
14290
   <para>
14291
    All these functions require object OIDs to identify the object to be
14292
    checked.  If you want to test an object by name, it is convenient to use
14293
    the OID alias types (<type>regclass</>, <type>regtype</>,
14294
    <type>regprocedure</>, <type>regoperator</>, <type>regconfig</>,
14295
    or <type>regdictionary</>),
14296
    for example:
14297
<programlisting>
14298
SELECT pg_type_is_visible('myschema.widget'::regtype);
14299
</programlisting>
14300
    Note that it would not make much sense to test a non-schema-qualified
14301
    type name in this way &mdash; if the name can be recognized at all, it must be visible.
14302
   </para>
14303
14304
   <indexterm>
14305
    <primary>format_type</primary>
14306
   </indexterm>
14307
14308
   <indexterm>
14309
    <primary>pg_describe_object</primary>
14310
   </indexterm>
14311
14312
   <indexterm>
14313
    <primary>pg_identify_object</primary>
14314
   </indexterm>
14315
14316
   <indexterm>
14317
    <primary>pg_get_constraintdef</primary>
14318
   </indexterm>
14319
14320
   <indexterm>
14321
    <primary>pg_get_expr</primary>
14322
   </indexterm>
14323
14324
   <indexterm>
14325
    <primary>pg_get_functiondef</primary>
14326
   </indexterm>
14327
14328
   <indexterm>
14329
    <primary>pg_get_function_arguments</primary>
14330
   </indexterm>
14331
14332
   <indexterm>
14333
    <primary>pg_get_function_identity_arguments</primary>
14334
   </indexterm>
14335
14336
   <indexterm>
14337
    <primary>pg_get_function_result</primary>
14338
   </indexterm>
14339
14340
   <indexterm>
14341
    <primary>pg_get_indexdef</primary>
14342
   </indexterm>
14343
14344
   <indexterm>
14345
    <primary>pg_get_keywords</primary>
14346
   </indexterm>
14347
14348
   <indexterm>
14349
    <primary>pg_get_ruledef</primary>
14350
   </indexterm>
14351
14352
   <indexterm>
14353
    <primary>pg_get_serial_sequence</primary>
14354
   </indexterm>
14355
14356
   <indexterm>
14357
    <primary>pg_get_triggerdef</primary>
14358
   </indexterm>
14359
14360
   <indexterm>
14361
    <primary>pg_get_userbyid</primary>
14362
   </indexterm>
14363
14364
   <indexterm>
14365
    <primary>pg_get_viewdef</primary>
14366
   </indexterm>
14367
14368
   <indexterm>
14369
    <primary>pg_options_to_table</primary>
14370
   </indexterm>
14371
14372
   <indexterm>
14373
    <primary>pg_tablespace_databases</primary>
14374
   </indexterm>
14375
14376
   <indexterm>
14377
    <primary>pg_tablespace_location</primary>
14378
   </indexterm>
14379
14380
   <indexterm>
14381
    <primary>pg_typeof</primary>
14382
   </indexterm>
14383
14384
   <indexterm>
14385
    <primary>collation for</primary>
14386
   </indexterm>
14387
14388
  <para>
14389
   <xref linkend="functions-info-catalog-table"> lists functions that
14390
   extract information from the system catalogs.
14391
  </para>
14392
14393
   <table id="functions-info-catalog-table">
14394
    <title>System Catalog Information Functions</title>
14395
    <tgroup cols="3">
14396
     <thead>
14397
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
14398
     </thead>
14399
14400
     <tbody>
14401
      <row>
14402
       <entry><literal><function>format_type(<parameter>type_oid</parameter>, <parameter>typemod</>)</function></literal></entry>
14403
       <entry><type>text</type></entry>
14404
       <entry>get SQL name of a data type</entry>
14405
      </row>
14406
      <row>
14407
       <entry><literal><function>pg_describe_object(<parameter>catalog_id</parameter>, <parameter>object_id</parameter>, <parameter>object_sub_id</parameter>)</function></literal></entry>
14408
       <entry><type>text</type></entry>
14409
       <entry>get description of a database object</entry>
14410
      </row>
14411
      <row>
14412
       <entry><literal><function>pg_identify_object(<parameter>catalog_id</parameter> <type>oid</>, <parameter>object_id</parameter> <type>oid</>, <parameter>object_sub_id</parameter> <type>integer</>)</function></literal></entry>
14413
       <entry><parameter>type</> <type>text</>, <parameter>schema</> <type>text</>, <parameter>name</> <type>text</>, <parameter>identity</> <type>text</></entry>
14414
       <entry>get identity of a database object</entry>
14415
      </row>
14416
      <row>
14417
       <entry><literal><function>pg_get_constraintdef(<parameter>constraint_oid</parameter>)</function></literal></entry>
14418
       <entry><type>text</type></entry>
14419
       <entry>get definition of a constraint</entry>
14420
      </row>
14421
      <row>
14422
       <entry><literal><function>pg_get_constraintdef(<parameter>constraint_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
14423
       <entry><type>text</type></entry>
14424
       <entry>get definition of a constraint</entry>
14425
      </row>
14426
      <row>
14427
       <entry><literal><function>pg_get_expr(<parameter>pg_node_tree</parameter>, <parameter>relation_oid</>)</function></literal></entry>
14428
       <entry><type>text</type></entry>
14429
       <entry>decompile internal form of an expression, assuming that any Vars
14430
       in it refer to the relation indicated by the second parameter</entry>
14431
      </row>
14432
      <row>
14433
       <entry><literal><function>pg_get_expr(<parameter>pg_node_tree</parameter>, <parameter>relation_oid</>, <parameter>pretty_bool</>)</function></literal></entry>
14434
       <entry><type>text</type></entry>
14435
       <entry>decompile internal form of an expression, assuming that any Vars
14436
       in it refer to the relation indicated by the second parameter</entry>
14437
      </row>
14438
      <row>
14439
       <entry><literal><function>pg_get_functiondef(<parameter>func_oid</parameter>)</function></literal></entry>
14440
       <entry><type>text</type></entry>
14441
       <entry>get definition of a function</entry>
14442
      </row>
14443
      <row>
14444
       <entry><literal><function>pg_get_function_arguments(<parameter>func_oid</parameter>)</function></literal></entry>
14445
       <entry><type>text</type></entry>
14446
       <entry>get argument list of function's definition (with default values)</entry>
14447
      </row>
14448
      <row>
14449
       <entry><literal><function>pg_get_function_identity_arguments(<parameter>func_oid</parameter>)</function></literal></entry>
14450
       <entry><type>text</type></entry>
14451
       <entry>get argument list to identify a function (without default values)</entry>
14452
      </row>
14453
      <row>
14454
       <entry><literal><function>pg_get_function_result(<parameter>func_oid</parameter>)</function></literal></entry>
14455
       <entry><type>text</type></entry>
14456
       <entry>get <literal>RETURNS</> clause for function</entry>
14457
      </row>
14458
      <row>
14459
       <entry><literal><function>pg_get_indexdef(<parameter>index_oid</parameter>)</function></literal></entry>
14460
       <entry><type>text</type></entry>
14461
       <entry>get <command>CREATE INDEX</> command for index</entry>
14462
      </row>
14463
      <row>
14464
       <entry><literal><function>pg_get_indexdef(<parameter>index_oid</parameter>, <parameter>column_no</>, <parameter>pretty_bool</>)</function></literal></entry>
14465
       <entry><type>text</type></entry>
14466
       <entry>get <command>CREATE INDEX</> command for index,
14467
       or definition of just one index column when
14468
       <parameter>column_no</> is not zero</entry>
14469
      </row>
14470
      <row>
14471
       <entry><literal><function>pg_get_keywords()</function></literal></entry>
14472
       <entry><type>setof record</type></entry>
14473
       <entry>get list of SQL keywords and their categories</entry>
14474
      </row>
14475
      <row>
14476
       <entry><literal><function>pg_get_ruledef(<parameter>rule_oid</parameter>)</function></literal></entry>
14477
       <entry><type>text</type></entry>
14478
       <entry>get <command>CREATE RULE</> command for rule</entry>
14479
      </row>
14480
      <row>
14481
       <entry><literal><function>pg_get_ruledef(<parameter>rule_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
14482
       <entry><type>text</type></entry>
14483
       <entry>get <command>CREATE RULE</> command for rule</entry>
14484
      </row>
14485
      <row>
14486
       <entry><literal><function>pg_get_serial_sequence(<parameter>table_name</parameter>, <parameter>column_name</parameter>)</function></literal></entry>
14487
       <entry><type>text</type></entry>
14488
       <entry>get name of the sequence that a <type>serial</type>, <type>smallserial</type> or <type>bigserial</type> column
14489
       uses</entry>
14490
      </row>
14491
      <row>
14492
       <entry><function>pg_get_triggerdef</function>(<parameter>trigger_oid</parameter>)</entry>
14493
       <entry><type>text</type></entry>
14494
       <entry>get <command>CREATE [ CONSTRAINT ] TRIGGER</> command for trigger</entry>
14495
      </row>
14496
      <row>
14497
       <entry><function>pg_get_triggerdef</function>(<parameter>trigger_oid</parameter>, <parameter>pretty_bool</>)</entry>
14498
       <entry><type>text</type></entry>
14499
       <entry>get <command>CREATE [ CONSTRAINT ] TRIGGER</> command for trigger</entry>
14500
      </row>
14501
      <row>
14502
       <entry><literal><function>pg_get_userbyid(<parameter>role_oid</parameter>)</function></literal></entry>
14503
       <entry><type>name</type></entry>
14504
       <entry>get role name with given OID</entry>
14505
      </row>
14506
      <row>
14507
       <entry><literal><function>pg_get_viewdef(<parameter>view_name</parameter>)</function></literal></entry>
14508
       <entry><type>text</type></entry>
14509
       <entry>get underlying <command>SELECT</command> command for view or materialized view (<emphasis>deprecated</emphasis>)</entry>
14510
      </row>
14511
      <row>
14512
       <entry><literal><function>pg_get_viewdef(<parameter>view_name</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
14513
       <entry><type>text</type></entry>
14514
       <entry>get underlying <command>SELECT</command> command for view or materialized view (<emphasis>deprecated</emphasis>)</entry>
14515
      </row>
14516
      <row>
14517
       <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>)</function></literal></entry>
14518
       <entry><type>text</type></entry>
14519
       <entry>get underlying <command>SELECT</command> command for view or materialized view</entry>
14520
      </row>
14521
      <row>
14522
       <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>, <parameter>pretty_bool</>)</function></literal></entry>
14523
       <entry><type>text</type></entry>
14524
       <entry>get underlying <command>SELECT</command> command for view or materialized view</entry>
14525
      </row>
14526
      <row>
14527
       <entry><literal><function>pg_get_viewdef(<parameter>view_oid</parameter>, <parameter>wrap_column_int</>)</function></literal></entry>
14528
       <entry><type>text</type></entry>
14529
       <entry>get underlying <command>SELECT</command> command for view or
14530
              materialized view; lines with fields are wrapped to specified
14531
              number of columns, pretty-printing is implied</entry>
14532
      </row>
14533
      <row>
14534
       <entry><literal><function>pg_options_to_table(<parameter>reloptions</parameter>)</function></literal></entry>
14535
       <entry><type>setof record</type></entry>
14536
       <entry>get the set of storage option name/value pairs</entry>
14537
      </row>
14538
      <row>
14539
       <entry><literal><function>pg_tablespace_databases(<parameter>tablespace_oid</parameter>)</function></literal></entry>
14540
       <entry><type>setof oid</type></entry>
14541
       <entry>get the set of database OIDs that have objects in the tablespace</entry>
14542
      </row>
14543
      <row>
14544
       <entry><literal><function>pg_tablespace_location(<parameter>tablespace_oid</parameter>)</function></literal></entry>
14545
       <entry><type>text</type></entry>
14546
       <entry>get the path in the file system that this tablespace is located in</entry>
14547
      </row>
14548
      <row>
14549
       <entry><literal><function>pg_typeof(<parameter>any</parameter>)</function></literal></entry>
14550
       <entry><type>regtype</type></entry>
14551
       <entry>get the data type of any value</entry>
14552
      </row>
14553
      <row>
14554
       <entry><literal><function>collation for (<parameter>any</parameter>)</function></literal></entry>
14555
       <entry><type>text</type></entry>
14556
       <entry>get the collation of the argument</entry>
14557
      </row>
14558
     </tbody>
14559
    </tgroup>
14560
   </table>
14561
14562
  <para>
14563
   <function>format_type</function> returns the SQL name of a data type that
14564
   is identified by its type OID and possibly a type modifier.  Pass NULL
14565
   for the type modifier if no specific modifier is known.
14566
  </para>
14567
14568
  <para>
14569
   <function>pg_get_keywords</function> returns a set of records describing
14570
   the SQL keywords recognized by the server. The <structfield>word</> column
14571
   contains the keyword.  The <structfield>catcode</> column contains a
14572
   category code: <literal>U</> for unreserved, <literal>C</> for column name,
14573
   <literal>T</> for type or function name, or <literal>R</> for reserved.
14574
   The <structfield>catdesc</> column contains a possibly-localized string
14575
   describing the category.
14576
  </para>
14577
14578
  <para>
14579
   <function>pg_get_constraintdef</function>,
14580
   <function>pg_get_indexdef</function>, <function>pg_get_ruledef</function>,
14581
   and <function>pg_get_triggerdef</function>, respectively reconstruct the
14582
   creating command for a constraint, index, rule, or trigger. (Note that this
14583
   is a decompiled reconstruction, not the original text of the command.)
14584
   <function>pg_get_expr</function> decompiles the internal form of an
14585
   individual expression, such as the default value for a column.  It can be
14586
   useful when examining the contents of system catalogs.  If the expression
14587
   might contain Vars, specify the OID of the relation they refer to as the
14588
   second parameter; if no Vars are expected, zero is sufficient.
14589
   <function>pg_get_viewdef</function> reconstructs the <command>SELECT</>
14590
   query that defines a view. Most of these functions come in two variants,
14591
   one of which can optionally <quote>pretty-print</> the result.  The
14592
   pretty-printed format is more readable, but the default format is more
14593
   likely to be interpreted the same way by future versions of
14594
   <productname>PostgreSQL</>; avoid using pretty-printed output for dump
14595
   purposes.  Passing <literal>false</> for the pretty-print parameter yields
14596
   the same result as the variant that does not have the parameter at all.
14597
  </para>
14598
14599
  <para>
14600
   <function>pg_get_functiondef</> returns a complete
14601
   <command>CREATE OR REPLACE FUNCTION</> statement for a function.
14602
   <function>pg_get_function_arguments</function> returns the argument list
14603
   of a function, in the form it would need to appear in within
14604
   <command>CREATE FUNCTION</>.
14605
   <function>pg_get_function_result</function> similarly returns the
14606
   appropriate <literal>RETURNS</> clause for the function.
14607
   <function>pg_get_function_identity_arguments</function> returns the
14608
   argument list necessary to identify a function, in the form it
14609
   would need to appear in within <command>ALTER FUNCTION</>, for
14610
   instance.  This form omits default values.
14611
  </para>
14612
14613
  <para>
14614
   <function>pg_get_serial_sequence</function> returns the name of the
14615
   sequence associated with a column, or NULL if no sequence is associated
14616
   with the column.  The first input parameter is a table name with
14617
   optional schema, and the second parameter is a column name.  Because
14618
   the first parameter is potentially a schema and table, it is not treated
14619
   as a double-quoted identifier, meaning it is lower cased by default,
14620
   while the second parameter, being just a column name, is treated as
14621
   double-quoted and has its case preserved.  The function returns a value
14622
   suitably formatted for passing to sequence functions (see <xref
14623
   linkend="functions-sequence">).  This association can be modified or
14624
   removed with <command>ALTER SEQUENCE OWNED BY</>.  (The function
14625
   probably should have been called
14626
   <function>pg_get_owned_sequence</function>; its current name reflects the fact
14627
   that it's typically used with <type>serial</> or <type>bigserial</>
14628
   columns.)
14629
  </para>
14630
14631
  <para>
14632
   <function>pg_get_userbyid</function> extracts a role's name given
14633
   its OID.
14634
  </para>
14635
14636
  <para>
14637
   <function>pg_options_to_table</function> returns the set of storage
14638
   option name/value pairs
14639
   (<literal>option_name</>/<literal>option_value</>) when passed
14640
   <structname>pg_class</>.<structfield>reloptions</> or
14641
   <structname>pg_attribute</>.<structfield>attoptions</>.
14642
  </para>
14643
14644
  <para>
14645
   <function>pg_tablespace_databases</function> allows a tablespace to be
14646
   examined. It returns the set of OIDs of databases that have objects stored
14647
   in the tablespace. If this function returns any rows, the tablespace is not
14648
   empty and cannot be dropped. To display the specific objects populating the
14649
   tablespace, you will need to connect to the databases identified by
14650
   <function>pg_tablespace_databases</function> and query their
14651
   <structname>pg_class</> catalogs.
14652
  </para>
14653
14654
  <para>
14655
   <function>pg_describe_object</function> returns a textual description of a database
14656
   object specified by catalog OID, object OID and a (possibly zero) sub-object ID.
14657
   This description is intended to be human-readable, and might be translated,
14658
   depending on server configuration.
14659
   This is useful to determine the identity of an object as stored in the
14660
   <structname>pg_depend</structname> catalog.
14661
  </para>
14662
14663
  <para>
14664
   <function>pg_identify_object</function> returns a row containing enough information
14665
   to uniquely identify the database object specified by catalog OID, object OID and a
14666
   (possibly zero) sub-object ID.  This information is intended to be machine-readable,
14667
   and is never translated.
14668
   <parameter>type</> identifies the type of database object;
14669
   <parameter>schema</> is the schema name that the object belongs in, or
14670
   <literal>NULL</> for object types that do not belong to schemas;
14671
   <parameter>name</> is the name of the object, quoted if necessary, only
1.2.1 by Martin Pitt
Import upstream version 9.3.6
14672
   present if it can be used (alongside schema name, if pertinent) as a unique
1 by Martin Pitt
Import upstream version 9.3~beta1
14673
   identifier of the object, otherwise <literal>NULL</>;
14674
   <parameter>identity</> is the complete object identity, with the precise format
14675
   depending on object type, and each part within the format being
14676
   schema-qualified and quoted as necessary.
14677
  </para>
14678
14679
  <para>
14680
   <function>pg_typeof</function> returns the OID of the data type of the
14681
   value that is passed to it.  This can be helpful for troubleshooting or
14682
   dynamically constructing SQL queries.  The function is declared as
14683
   returning <type>regtype</>, which is an OID alias type (see
14684
   <xref linkend="datatype-oid">); this means that it is the same as an
14685
   OID for comparison purposes but displays as a type name.  For example:
14686
<programlisting>
14687
SELECT pg_typeof(33);
14688
14689
 pg_typeof 
14690
-----------
14691
 integer
14692
(1 row)
14693
14694
SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
14695
 typlen 
14696
--------
14697
      4
14698
(1 row)
14699
</programlisting>
14700
  </para>
14701
14702
  <para>
14703
   The expression <literal>collation for</literal> returns the collation of the
14704
   value that is passed to it.  Example:
14705
<programlisting>
14706
SELECT collation for (description) FROM pg_description LIMIT 1;
14707
 pg_collation_for 
14708
------------------
14709
 "default"
14710
(1 row)
14711
14712
SELECT collation for ('foo' COLLATE "de_DE");
14713
 pg_collation_for 
14714
------------------
14715
 "de_DE"
14716
(1 row)
14717
</programlisting>
14718
  The value might be quoted and schema-qualified.  If no collation is derived
14719
  for the argument expression, then a null value is returned.  If the argument
14720
  is not of a collatable data type, then an error is raised.
14721
  </para>
14722
14723
   <indexterm>
14724
    <primary>col_description</primary>
14725
   </indexterm>
14726
14727
   <indexterm>
14728
    <primary>obj_description</primary>
14729
   </indexterm>
14730
14731
   <indexterm>
14732
    <primary>shobj_description</primary>
14733
   </indexterm>
14734
14735
   <indexterm>
14736
    <primary>comment</primary>
14737
    <secondary sortas="database objects">about database objects</secondary>
14738
   </indexterm>
14739
14740
   <para>
14741
    The functions shown in <xref linkend="functions-info-comment-table">
14742
    extract comments previously stored with the <xref linkend="sql-comment">
14743
    command.  A null value is returned if no
14744
    comment could be found for the specified parameters.
14745
   </para>
14746
14747
   <table id="functions-info-comment-table">
14748
    <title>Comment Information Functions</title>
14749
    <tgroup cols="3">
14750
     <thead>
14751
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
14752
     </thead>
14753
14754
     <tbody>
14755
      <row>
14756
       <entry><literal><function>col_description(<parameter>table_oid</parameter>, <parameter>column_number</parameter>)</function></literal></entry>
14757
       <entry><type>text</type></entry>
14758
       <entry>get comment for a table column</entry>
14759
      </row>
14760
      <row>
14761
       <entry><literal><function>obj_description(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</function></literal></entry>
14762
       <entry><type>text</type></entry>
14763
       <entry>get comment for a database object</entry>
14764
      </row>
14765
      <row>
14766
       <entry><literal><function>obj_description(<parameter>object_oid</parameter>)</function></literal></entry>
14767
       <entry><type>text</type></entry>
14768
       <entry>get comment for a database object (<emphasis>deprecated</emphasis>)</entry>
14769
      </row>
14770
      <row>
14771
       <entry><literal><function>shobj_description(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</function></literal></entry>
14772
       <entry><type>text</type></entry>
14773
       <entry>get comment for a shared database object</entry>
14774
      </row>
14775
     </tbody>
14776
    </tgroup>
14777
   </table>
14778
14779
   <para>
14780
    <function>col_description</function> returns the comment for a table
14781
    column, which is specified by the OID of its table and its column number.
14782
    (<function>obj_description</function> cannot be used for table columns
14783
    since columns do not have OIDs of their own.)
14784
   </para>
14785
14786
   <para>
14787
    The two-parameter form of <function>obj_description</function> returns the
14788
    comment for a database object specified by its OID and the name of the
14789
    containing system catalog.  For example,
14790
    <literal>obj_description(123456,'pg_class')</literal>
14791
    would retrieve the comment for the table with OID 123456.
14792
    The one-parameter form of <function>obj_description</function> requires only
14793
    the object OID.  It is deprecated since there is no guarantee that
14794
    OIDs are unique across different system catalogs; therefore, the wrong
14795
    comment might be returned.
14796
   </para>
14797
14798
   <para>
14799
    <function>shobj_description</function> is used just like
14800
    <function>obj_description</function> except it is used for retrieving
14801
    comments on shared objects.  Some system catalogs are global to all
14802
    databases within each cluster, and the descriptions for objects in them
14803
    are stored globally as well.
14804
   </para>
14805
14806
   <indexterm>
14807
    <primary>txid_current</primary>
14808
   </indexterm>
14809
14810
   <indexterm>
14811
    <primary>txid_current_snapshot</primary>
14812
   </indexterm>
14813
14814
   <indexterm>
14815
    <primary>txid_snapshot_xip</primary>
14816
   </indexterm>
14817
14818
   <indexterm>
14819
    <primary>txid_snapshot_xmax</primary>
14820
   </indexterm>
14821
14822
   <indexterm>
14823
    <primary>txid_snapshot_xmin</primary>
14824
   </indexterm>
14825
14826
   <indexterm>
14827
    <primary>txid_visible_in_snapshot</primary>
14828
   </indexterm>
14829
14830
   <para>
14831
    The functions shown in <xref linkend="functions-txid-snapshot">
14832
    provide server transaction information in an exportable form.  The main
14833
    use of these functions is to determine which transactions were committed
14834
    between two snapshots.
14835
   </para>
14836
14837
   <table id="functions-txid-snapshot">
14838
    <title>Transaction IDs and Snapshots</title>
14839
    <tgroup cols="3">
14840
     <thead>
14841
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
14842
     </thead>
14843
14844
     <tbody>
14845
      <row>
14846
       <entry><literal><function>txid_current()</function></literal></entry>
14847
       <entry><type>bigint</type></entry>
14848
       <entry>get current transaction ID</entry>
14849
      </row>
14850
      <row>
14851
       <entry><literal><function>txid_current_snapshot()</function></literal></entry>
14852
       <entry><type>txid_snapshot</type></entry>
14853
       <entry>get current snapshot</entry>
14854
      </row>
14855
      <row>
14856
       <entry><literal><function>txid_snapshot_xip(<parameter>txid_snapshot</parameter>)</function></literal></entry>
14857
       <entry><type>setof bigint</type></entry>
14858
       <entry>get in-progress transaction IDs in snapshot</entry>
14859
      </row>
14860
      <row>
14861
       <entry><literal><function>txid_snapshot_xmax(<parameter>txid_snapshot</parameter>)</function></literal></entry>
14862
       <entry><type>bigint</type></entry>
14863
       <entry>get <literal>xmax</literal> of snapshot</entry>
14864
      </row>
14865
      <row>
14866
       <entry><literal><function>txid_snapshot_xmin(<parameter>txid_snapshot</parameter>)</function></literal></entry>
14867
       <entry><type>bigint</type></entry>
14868
       <entry>get <literal>xmin</literal> of snapshot</entry>
14869
      </row>
14870
      <row>
14871
       <entry><literal><function>txid_visible_in_snapshot(<parameter>bigint</parameter>, <parameter>txid_snapshot</parameter>)</function></literal></entry>
14872
       <entry><type>boolean</type></entry>
14873
       <entry>is transaction ID visible in snapshot? (do not use with subtransaction ids)</entry>
14874
      </row>
14875
     </tbody>
14876
    </tgroup>
14877
   </table>
14878
14879
   <para>
14880
    The internal transaction ID type (<type>xid</>) is 32 bits wide and
14881
    wraps around every 4 billion transactions.  However, these functions
14882
    export a 64-bit format that is extended with an <quote>epoch</> counter
14883
    so it will not wrap around during the life of an installation.
14884
    The data type used by these functions, <type>txid_snapshot</type>,
14885
    stores information about transaction ID
14886
    visibility at a particular moment in time.  Its components are
14887
    described in <xref linkend="functions-txid-snapshot-parts">.
14888
   </para>
14889
14890
   <table id="functions-txid-snapshot-parts">
14891
    <title>Snapshot Components</title>
14892
    <tgroup cols="2">
14893
     <thead>
14894
      <row>
14895
       <entry>Name</entry>
14896
       <entry>Description</entry>
14897
      </row>
14898
     </thead>
14899
14900
     <tbody>
14901
14902
      <row>
14903
       <entry><type>xmin</type></entry>
14904
       <entry>
14905
         Earliest transaction ID (txid) that is still active.  All earlier
14906
         transactions will either be committed and visible, or rolled
14907
         back and dead.
14908
       </entry>
14909
      </row>
14910
14911
      <row>
14912
       <entry><type>xmax</type></entry>
14913
       <entry>
14914
        First as-yet-unassigned txid.  All txids greater than or equal to this
14915
        are not yet started as of the time of the snapshot, and thus invisible.
14916
       </entry>
14917
      </row>
14918
14919
      <row>
14920
       <entry><type>xip_list</type></entry>
14921
       <entry>
14922
        Active txids at the time of the snapshot.  The list
14923
        includes only those active txids between <literal>xmin</>
14924
        and <literal>xmax</>; there might be active txids higher
14925
        than <literal>xmax</>.  A txid that is <literal>xmin &lt;= txid &lt;
14926
        xmax</literal> and not in this list was already completed
14927
        at the time of the snapshot, and thus either visible or
14928
        dead according to its commit status.  The list does not
14929
        include txids of subtransactions.
14930
       </entry>
14931
      </row>
14932
14933
     </tbody>
14934
    </tgroup>
14935
   </table>
14936
14937
   <para>
14938
    <type>txid_snapshot</>'s textual representation is
14939
    <literal><replaceable>xmin</>:<replaceable>xmax</>:<replaceable>xip_list</></literal>.
14940
    For example <literal>10:20:10,14,15</literal> means
14941
    <literal>xmin=10, xmax=20, xip_list=10, 14, 15</literal>.
14942
   </para>
14943
  </sect1>
14944
14945
  <sect1 id="functions-admin">
14946
   <title>System Administration Functions</title>
14947
14948
   <para>
14949
    The functions described in this section are used to control and
14950
    monitor a <productname>PostgreSQL</> installation.
14951
   </para>
14952
14953
  <sect2 id="functions-admin-set">
14954
   <title>Configuration Settings Functions</title>
14955
14956
   <para>
14957
    <xref linkend="functions-admin-set-table"> shows the functions
14958
    available to query and alter run-time configuration parameters.
14959
   </para>
14960
14961
   <table id="functions-admin-set-table">
14962
    <title>Configuration Settings Functions</title>
14963
    <tgroup cols="3">
14964
     <thead>
14965
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
14966
     </thead>
14967
14968
     <tbody>
14969
      <row>
14970
       <entry>
14971
        <indexterm>
14972
         <primary>current_setting</primary>
14973
        </indexterm>
14974
        <literal><function>current_setting(<parameter>setting_name</parameter>)</function></literal>
14975
       </entry>
14976
       <entry><type>text</type></entry>
14977
       <entry>get current value of setting</entry>
14978
      </row>
14979
      <row>
14980
       <entry>
14981
        <indexterm>
14982
         <primary>set_config</primary>
14983
        </indexterm>
14984
        <literal><function>set_config(<parameter>setting_name</parameter>,
14985
                             <parameter>new_value</parameter>,
14986
                             <parameter>is_local</parameter>)</function></literal>
14987
       </entry>
14988
       <entry><type>text</type></entry>
14989
       <entry>set parameter and return new value</entry>
14990
      </row>
14991
     </tbody>
14992
    </tgroup>
14993
   </table>
14994
14995
   <indexterm>
14996
    <primary>SET</primary>
14997
   </indexterm>
14998
14999
   <indexterm>
15000
    <primary>SHOW</primary>
15001
   </indexterm>
15002
15003
   <indexterm>
15004
    <primary>configuration</primary>
15005
    <secondary sortas="server">of the server</secondary>
15006
    <tertiary>functions</tertiary>
15007
   </indexterm>
15008
15009
   <para>
15010
    The function <function>current_setting</function> yields the
15011
    current value of the setting <parameter>setting_name</parameter>.
15012
    It corresponds to the <acronym>SQL</acronym> command
15013
    <command>SHOW</command>.  An example:
15014
<programlisting>
15015
SELECT current_setting('datestyle');
15016
15017
 current_setting
15018
-----------------
15019
 ISO, MDY
15020
(1 row)
15021
</programlisting>
15022
   </para>
15023
15024
   <para>
15025
    <function>set_config</function> sets the parameter
15026
    <parameter>setting_name</parameter> to
15027
    <parameter>new_value</parameter>.  If
15028
    <parameter>is_local</parameter> is <literal>true</literal>, the
15029
    new value will only apply to the current transaction. If you want
15030
    the new value to apply for the current session, use
15031
    <literal>false</literal> instead. The function corresponds to the
15032
    SQL command <command>SET</command>. An example:
15033
<programlisting>
15034
SELECT set_config('log_statement_stats', 'off', false);
15035
15036
 set_config
15037
------------
15038
 off
15039
(1 row)
15040
</programlisting>
15041
   </para>
15042
15043
  </sect2>
15044
15045
  <sect2 id="functions-admin-signal">
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
15046
   <title>Server Signaling Functions</title>
1 by Martin Pitt
Import upstream version 9.3~beta1
15047
15048
   <indexterm>
15049
    <primary>pg_cancel_backend</primary>
15050
   </indexterm>
15051
   <indexterm>
15052
    <primary>pg_reload_conf</primary>
15053
   </indexterm>
15054
   <indexterm>
15055
    <primary>pg_rotate_logfile</primary>
15056
   </indexterm>
15057
   <indexterm>
15058
    <primary>pg_terminate_backend</primary>
15059
   </indexterm>
15060
15061
   <indexterm>
15062
    <primary>signal</primary>
15063
    <secondary sortas="backend">backend processes</secondary>
15064
   </indexterm>
15065
15066
   <para>
15067
    The functions shown in <xref
15068
    linkend="functions-admin-signal-table"> send control signals to
15069
    other server processes.  Use of these functions is usually restricted
15070
    to superusers, with noted exceptions.
15071
   </para>
15072
15073
   <table id="functions-admin-signal-table">
1.1.1 by Martin Pitt
Import upstream version 9.3~beta2
15074
    <title>Server Signaling Functions</title>
1 by Martin Pitt
Import upstream version 9.3~beta1
15075
    <tgroup cols="3">
15076
     <thead>
15077
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
15078
      </row>
15079
     </thead>
15080
15081
     <tbody>
15082
      <row>
15083
       <entry>
15084
        <literal><function>pg_cancel_backend(<parameter>pid</parameter> <type>int</>)</function></literal>
15085
        </entry>
15086
       <entry><type>boolean</type></entry>
15087
       <entry>Cancel a backend's current query.  You can execute this against
15088
        another backend that has exactly the same role as the user calling the
15089
        function.  In all other cases, you must be a superuser.
15090
        </entry>
15091
      </row>
15092
      <row>
15093
       <entry>
15094
        <literal><function>pg_reload_conf()</function></literal>
15095
        </entry>
15096
       <entry><type>boolean</type></entry>
15097
       <entry>Cause server processes to reload their configuration files</entry>
15098
      </row>
15099
      <row>
15100
       <entry>
15101
        <literal><function>pg_rotate_logfile()</function></literal>
15102
        </entry>
15103
       <entry><type>boolean</type></entry>
15104
       <entry>Rotate server's log file</entry>
15105
      </row>
15106
      <row>
15107
       <entry>
15108
        <literal><function>pg_terminate_backend(<parameter>pid</parameter> <type>int</>)</function></literal>
15109
        </entry>
15110
       <entry><type>boolean</type></entry>
15111
       <entry>Terminate a backend.  You can execute this against
15112
        another backend that has exactly the same role as the user
15113
        calling the function.  In all other cases, you must be a
15114
        superuser.
15115
       </entry>
15116
      </row>
15117
     </tbody>
15118
    </tgroup>
15119
   </table>
15120
15121
   <para>
15122
    Each of these functions returns <literal>true</literal> if
15123
    successful and <literal>false</literal> otherwise.
15124
   </para>
15125
15126
   <para>
15127
    <function>pg_cancel_backend</> and <function>pg_terminate_backend</>
15128
    send signals (<systemitem>SIGINT</> or <systemitem>SIGTERM</>
15129
    respectively) to backend processes identified by process ID.
15130
    The process ID of an active backend can be found from
15131
    the <structfield>pid</structfield> column of the
15132
    <structname>pg_stat_activity</structname> view, or by listing the
15133
    <command>postgres</command> processes on the server (using
15134
    <application>ps</> on Unix or the <application>Task
15135
    Manager</> on <productname>Windows</>).
15136
    The role of an active backend can be found from the
15137
    <structfield>usename</structfield> column of the
15138
    <structname>pg_stat_activity</structname> view.
15139
   </para>
15140
15141
   <para>
15142
    <function>pg_reload_conf</> sends a <systemitem>SIGHUP</> signal
15143
    to the server, causing configuration files
15144
    to be reloaded by all server processes.
15145
   </para>
15146
15147
   <para>
15148
    <function>pg_rotate_logfile</> signals the log-file manager to switch
15149
    to a new output file immediately.  This works only when the built-in
15150
    log collector is running, since otherwise there is no log-file manager
15151
    subprocess.
15152
   </para>
15153
15154
  </sect2>
15155
15156
  <sect2 id="functions-admin-backup">
15157
   <title>Backup Control Functions</title>
15158
15159
   <indexterm>
15160
    <primary>backup</primary>
15161
   </indexterm>
15162
   <indexterm>
15163
    <primary>pg_create_restore_point</primary>
15164
   </indexterm>
15165
   <indexterm>
15166
    <primary>pg_current_xlog_insert_location</primary>
15167
   </indexterm>
15168
   <indexterm>
15169
    <primary>pg_current_xlog_location</primary>
15170
   </indexterm>
15171
   <indexterm>
15172
    <primary>pg_start_backup</primary>
15173
   </indexterm>
15174
   <indexterm>
15175
    <primary>pg_stop_backup</primary>
15176
   </indexterm>
15177
   <indexterm>
15178
    <primary>pg_is_in_backup</primary>
15179
   </indexterm>
15180
   <indexterm>
15181
    <primary>pg_backup_start_time</primary>
15182
   </indexterm>
15183
   <indexterm>
15184
    <primary>pg_switch_xlog</primary>
15185
   </indexterm>
15186
   <indexterm>
15187
    <primary>pg_xlogfile_name</primary>
15188
   </indexterm>
15189
   <indexterm>
15190
    <primary>pg_xlogfile_name_offset</primary>
15191
   </indexterm>
15192
   <indexterm>
15193
    <primary>pg_xlog_location_diff</primary>
15194
   </indexterm>
15195
15196
   <para>
15197
    The functions shown in <xref
15198
    linkend="functions-admin-backup-table"> assist in making on-line backups.
15199
    These functions cannot be executed during recovery (except
15200
    <function>pg_is_in_backup</function>, <function>pg_backup_start_time</function>
15201
    and <function>pg_xlog_location_diff</function>).
15202
   </para>
15203
15204
   <table id="functions-admin-backup-table">
15205
    <title>Backup Control Functions</title>
15206
    <tgroup cols="3">
15207
     <thead>
15208
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
15209
      </row>
15210
     </thead>
15211
15212
     <tbody>
15213
      <row>
15214
       <entry>
15215
        <literal><function>pg_create_restore_point(<parameter>name</> <type>text</>)</function></literal>
15216
        </entry>
15217
       <entry><type>text</type></entry>
15218
       <entry>Create a named point for performing restore (restricted to superusers)</entry>
15219
      </row>
15220
      <row>
15221
       <entry>
15222
        <literal><function>pg_current_xlog_insert_location()</function></literal>
15223
        </entry>
15224
       <entry><type>text</type></entry>
15225
       <entry>Get current transaction log insert location</entry>
15226
      </row>
15227
      <row>
15228
       <entry>
15229
        <literal><function>pg_current_xlog_location()</function></literal>
15230
        </entry>
15231
       <entry><type>text</type></entry>
15232
       <entry>Get current transaction log write location</entry>
15233
      </row>
15234
      <row>
15235
       <entry>
15236
        <literal><function>pg_start_backup(<parameter>label</> <type>text</> <optional>, <parameter>fast</> <type>boolean</> </optional>)</function></literal>
15237
        </entry>
15238
       <entry><type>text</type></entry>
15239
       <entry>Prepare for performing on-line backup (restricted to superusers or replication roles)</entry>
15240
      </row>
15241
      <row>
15242
       <entry>
15243
        <literal><function>pg_stop_backup()</function></literal>
15244
        </entry>
15245
       <entry><type>text</type></entry>
15246
       <entry>Finish performing on-line backup (restricted to superusers or replication roles)</entry>
15247
      </row>
15248
      <row>
15249
       <entry>
15250
        <literal><function>pg_is_in_backup()</function></literal>
15251
        </entry>
15252
       <entry><type>bool</type></entry>
15253
       <entry>True if an on-line exclusive backup is still in progress.</entry>
15254
      </row>
15255
      <row>
15256
       <entry>
15257
        <literal><function>pg_backup_start_time()</function></literal>
15258
        </entry>
15259
       <entry><type>timestamp with time zone</type></entry>
15260
       <entry>Get start time of an on-line exclusive backup in progress.</entry>
15261
      </row>
15262
      <row>
15263
       <entry>
15264
        <literal><function>pg_switch_xlog()</function></literal>
15265
        </entry>
15266
       <entry><type>text</type></entry>
15267
       <entry>Force switch to a new transaction log file (restricted to superusers)</entry>
15268
      </row>
15269
      <row>
15270
       <entry>
15271
        <literal><function>pg_xlogfile_name(<parameter>location</> <type>text</>)</function></literal>
15272
        </entry>
15273
       <entry><type>text</type></entry>
15274
       <entry>Convert transaction log location string to file name</entry>
15275
      </row>
15276
      <row>
15277
       <entry>
15278
        <literal><function>pg_xlogfile_name_offset(<parameter>location</> <type>text</>)</function></literal>
15279
        </entry>
15280
       <entry><type>text</>, <type>integer</></entry>
15281
       <entry>Convert transaction log location string to file name and decimal byte offset within file</entry>
15282
      </row>
15283
      <row>
15284
       <entry>
15285
        <literal><function>pg_xlog_location_diff(<parameter>location</> <type>text</>, <parameter>location</> <type>text</>)</function></literal>
15286
       </entry>
15287
       <entry><type>numeric</></entry>
15288
       <entry>Calculate the difference between two transaction log locations</entry>
15289
      </row>
15290
     </tbody>
15291
    </tgroup>
15292
   </table>
15293
15294
   <para>
15295
    <function>pg_start_backup</> accepts an
15296
    arbitrary user-defined label for the backup.  (Typically this would be
15297
    the name under which the backup dump file will be stored.)  The function
15298
    writes a backup label file (<filename>backup_label</>) into the
15299
    database cluster's data directory, performs a checkpoint,
15300
    and then returns the backup's starting transaction log location as text.
15301
    The user can ignore this result value, but it is
15302
    provided in case it is useful.
15303
<programlisting>
15304
postgres=# select pg_start_backup('label_goes_here');
15305
 pg_start_backup
15306
-----------------
15307
 0/D4445B8
15308
(1 row)
15309
</programlisting>
15310
    There is an optional second parameter of type <type>boolean</type>.  If <literal>true</>,
15311
    it specifies executing <function>pg_start_backup</> as quickly as
15312
    possible.  This forces an immediate checkpoint which will cause a
15313
    spike in I/O operations, slowing any concurrently executing queries.
15314
   </para>
15315
15316
   <para>
15317
    <function>pg_stop_backup</> removes the label file created by
15318
    <function>pg_start_backup</>, and creates a backup history file in
15319
    the transaction log archive area.  The history file includes the label given to
15320
    <function>pg_start_backup</>, the starting and ending transaction log locations for
15321
    the backup, and the starting and ending times of the backup.  The return
15322
    value is the backup's ending transaction log location (which again
15323
    can be ignored).  After recording the ending location, the current
15324
    transaction log insertion
15325
    point is automatically advanced to the next transaction log file, so that the
15326
    ending transaction log file can be archived immediately to complete the backup.
15327
   </para>
15328
15329
   <para>
15330
    <function>pg_switch_xlog</> moves to the next transaction log file, allowing the
15331
    current file to be archived (assuming you are using continuous archiving).
15332
    The return value is the ending transaction log location + 1 within the just-completed transaction log file.
15333
    If there has been no transaction log activity since the last transaction log switch,
15334
    <function>pg_switch_xlog</> does nothing and returns the start location
15335
    of the transaction log file currently in use.
15336
   </para>
15337
15338
   <para>
15339
    <function>pg_create_restore_point</> creates a named transaction log
15340
    record that can be used as recovery target, and returns the corresponding
15341
    transaction log location.  The given name can then be used with
15342
    <xref linkend="recovery-target-name"> to specify the point up to which
15343
    recovery will proceed.  Avoid creating multiple restore points with the
15344
    same name, since recovery will stop at the first one whose name matches
15345
    the recovery target.
15346
   </para>
15347
15348
   <para>
15349
    <function>pg_current_xlog_location</> displays the current transaction log write
15350
    location in the same format used by the above functions.  Similarly,
15351
    <function>pg_current_xlog_insert_location</> displays the current transaction log
15352
    insertion point.  The insertion point is the <quote>logical</> end
15353
    of the transaction log
15354
    at any instant, while the write location is the end of what has actually
15355
    been written out from the server's internal buffers.  The write location
15356
    is the end of what can be examined from outside the server, and is usually
15357
    what you want if you are interested in archiving partially-complete transaction log
15358
    files.  The insertion point is made available primarily for server
15359
    debugging purposes.  These are both read-only operations and do not
15360
    require superuser permissions.
15361
   </para>
15362
15363
   <para>
15364
    You can use <function>pg_xlogfile_name_offset</> to extract the
15365
    corresponding transaction log file name and byte offset from the results of any of the
15366
    above functions.  For example:
15367
<programlisting>
15368
postgres=# SELECT * FROM pg_xlogfile_name_offset(pg_stop_backup());
15369
        file_name         | file_offset 
15370
--------------------------+-------------
15371
 00000001000000000000000D |     4039624
15372
(1 row)
15373
</programlisting>
15374
    Similarly, <function>pg_xlogfile_name</> extracts just the transaction log file name.
15375
    When the given transaction log location is exactly at a transaction log file boundary, both
15376
    these functions return the name of the preceding transaction log file.
15377
    This is usually the desired behavior for managing transaction log archiving
15378
    behavior, since the preceding file is the last one that currently
15379
    needs to be archived.
15380
   </para>
15381
15382
   <para>
15383
    <function>pg_xlog_location_diff</> calculates the difference in bytes
15384
    between two transaction log locations. It can be used with
15385
    <structname>pg_stat_replication</structname> or some functions shown in
15386
    <xref linkend="functions-admin-backup-table"> to get the replication lag.
15387
   </para>
15388
15389
   <para>
15390
    For details about proper usage of these functions, see
15391
    <xref linkend="continuous-archiving">.
15392
   </para>
15393
15394
  </sect2>
15395
15396
  <sect2 id="functions-recovery-control">
15397
   <title>Recovery Control Functions</title>
15398
15399
   <indexterm>
15400
    <primary>pg_is_in_recovery</primary>
15401
   </indexterm>
15402
   <indexterm>
15403
    <primary>pg_last_xlog_receive_location</primary>
15404
   </indexterm>
15405
   <indexterm>
15406
    <primary>pg_last_xlog_replay_location</primary>
15407
   </indexterm>
15408
   <indexterm>
15409
    <primary>pg_last_xact_replay_timestamp</primary>
15410
   </indexterm>
15411
15412
   <para>
15413
    The functions shown in <xref
15414
    linkend="functions-recovery-info-table"> provide information
15415
    about the current status of the standby.
15416
    These functions may be executed both during recovery and in normal running.
15417
   </para>
15418
15419
   <table id="functions-recovery-info-table">
15420
    <title>Recovery Information Functions</title>
15421
    <tgroup cols="3">
15422
     <thead>
15423
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
15424
      </row>
15425
     </thead>
15426
15427
     <tbody>
15428
      <row>
15429
       <entry>
15430
        <literal><function>pg_is_in_recovery()</function></literal>
15431
        </entry>
15432
       <entry><type>bool</type></entry>
15433
       <entry>True if recovery is still in progress.
15434
       </entry>
15435
      </row>
15436
      <row>
15437
       <entry>
15438
        <literal><function>pg_last_xlog_receive_location()</function></literal>
15439
        </entry>
15440
       <entry><type>text</type></entry>
15441
       <entry>Get last transaction log location received and synced to disk by
15442
        streaming replication. While streaming replication is in progress
15443
        this will increase monotonically. If recovery has completed this will
15444
        remain static at
15445
        the value of the last WAL record received and synced to disk during
15446
        recovery. If streaming replication is disabled, or if it has not yet
15447
        started, the function returns NULL.
15448
       </entry>
15449
      </row>
15450
      <row>
15451
       <entry>
15452
        <literal><function>pg_last_xlog_replay_location()</function></literal>
15453
        </entry>
15454
       <entry><type>text</type></entry>
15455
       <entry>Get last transaction log location replayed during recovery.
15456
        If recovery is still in progress this will increase monotonically.
15457
        If recovery has completed then this value will remain static at
15458
        the value of the last WAL record applied during that recovery.
15459
        When the server has been started normally without recovery
15460
        the function returns NULL.
15461
       </entry>
15462
      </row>
15463
      <row>
15464
       <entry>
15465
        <literal><function>pg_last_xact_replay_timestamp()</function></literal>
15466
        </entry>
15467
       <entry><type>timestamp with time zone</type></entry>
15468
       <entry>Get time stamp of last transaction replayed during recovery.
15469
        This is the time at which the commit or abort WAL record for that
15470
        transaction was generated on the primary.
15471
        If no transactions have been replayed during recovery, this function
15472
        returns NULL.  Otherwise, if recovery is still in progress this will
15473
        increase monotonically.  If recovery has completed then this value will
15474
        remain static at the value of the last transaction applied during that
15475
        recovery.  When the server has been started normally without recovery
15476
        the function returns NULL.
15477
       </entry>
15478
      </row>
15479
     </tbody>
15480
    </tgroup>
15481
   </table>
15482
15483
   <indexterm>
15484
    <primary>pg_is_xlog_replay_paused</primary>
15485
   </indexterm>
15486
   <indexterm>
15487
    <primary>pg_xlog_replay_pause</primary>
15488
   </indexterm>
15489
   <indexterm>
15490
    <primary>pg_xlog_replay_resume</primary>
15491
   </indexterm>
15492
15493
   <para>
15494
    The functions shown in <xref
15495
    linkend="functions-recovery-control-table"> control the progress of recovery.
15496
    These functions may be executed only during recovery.
15497
   </para>
15498
15499
   <table id="functions-recovery-control-table">
15500
    <title>Recovery Control Functions</title>
15501
    <tgroup cols="3">
15502
     <thead>
15503
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
15504
      </row>
15505
     </thead>
15506
15507
     <tbody>
15508
      <row>
15509
       <entry>
15510
        <literal><function>pg_is_xlog_replay_paused()</function></literal>
15511
        </entry>
15512
       <entry><type>bool</type></entry>
15513
       <entry>True if recovery is paused.
15514
       </entry>
15515
      </row>
15516
      <row>
15517
       <entry>
15518
        <literal><function>pg_xlog_replay_pause()</function></literal>
15519
        </entry>
15520
       <entry><type>void</type></entry>
15521
       <entry>Pauses recovery immediately.
15522
       </entry>
15523
      </row>
15524
      <row>
15525
       <entry>
15526
        <literal><function>pg_xlog_replay_resume()</function></literal>
15527
        </entry>
15528
       <entry><type>void</type></entry>
15529
       <entry>Restarts recovery if it was paused.
15530
       </entry>
15531
      </row>
15532
     </tbody>
15533
    </tgroup>
15534
   </table>
15535
15536
   <para>
15537
    While recovery is paused no further database changes are applied.
15538
    If in hot standby, all new queries will see the same consistent snapshot
15539
    of the database, and no further query conflicts will be generated until
15540
    recovery is resumed.
15541
   </para>
15542
15543
   <para>
15544
    If streaming replication is disabled, the paused state may continue
15545
    indefinitely without problem. While streaming replication is in
15546
    progress WAL records will continue to be received, which will
15547
    eventually fill available disk space, depending upon the duration of
15548
    the pause, the rate of WAL generation and available disk space.
15549
   </para>
15550
15551
  </sect2>
15552
15553
  <sect2 id="functions-snapshot-synchronization">
15554
   <title>Snapshot Synchronization Functions</title>
15555
15556
   <indexterm>
15557
     <primary>pg_export_snapshot</primary>
15558
   </indexterm>
15559
15560
   <para>
15561
    <productname>PostgreSQL</> allows database sessions to synchronize their
15562
    snapshots. A <firstterm>snapshot</> determines which data is visible to the
15563
    transaction that is using the snapshot. Synchronized snapshots are
15564
    necessary when two or more sessions need to see identical content in the
15565
    database. If two sessions just start their transactions independently,
15566
    there is always a possibility that some third transaction commits
15567
    between the executions of the two <command>START TRANSACTION</> commands,
15568
    so that one session sees the effects of that transaction and the other
15569
    does not.
15570
   </para>
15571
15572
   <para>
15573
    To solve this problem, <productname>PostgreSQL</> allows a transaction to
15574
    <firstterm>export</> the snapshot it is using.  As long as the exporting
15575
    transaction remains open, other transactions can <firstterm>import</> its
15576
    snapshot, and thereby be guaranteed that they see exactly the same view
15577
    of the database that the first transaction sees.  But note that any
15578
    database changes made by any one of these transactions remain invisible
15579
    to the other transactions, as is usual for changes made by uncommitted
15580
    transactions.  So the transactions are synchronized with respect to
15581
    pre-existing data, but act normally for changes they make themselves.
15582
   </para>
15583
15584
   <para>
15585
    Snapshots are exported with the <function>pg_export_snapshot</> function,
15586
    shown in <xref linkend="functions-snapshot-synchronization-table">, and
15587
    imported with the <xref linkend="sql-set-transaction"> command.
15588
   </para>
15589
15590
   <table id="functions-snapshot-synchronization-table">
15591
    <title>Snapshot Synchronization Functions</title>
15592
    <tgroup cols="3">
15593
     <thead>
15594
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
15595
      </row>
15596
     </thead>
15597
15598
     <tbody>
15599
      <row>
15600
       <entry>
15601
        <literal><function>pg_export_snapshot()</function></literal>
15602
       </entry>
15603
       <entry><type>text</type></entry>
15604
       <entry>Save the current snapshot and return its identifier</entry>
15605
      </row>
15606
     </tbody>
15607
    </tgroup>
15608
   </table>
15609
15610
   <para>
15611
    The function <function>pg_export_snapshot</> saves the current snapshot
15612
    and returns a <type>text</> string identifying the snapshot.  This string
15613
    must be passed (outside the database) to clients that want to import the
15614
    snapshot.  The snapshot is available for import only until the end of the
15615
    transaction that exported it.  A transaction can export more than one
15616
    snapshot, if needed.  Note that doing so is only useful in <literal>READ
15617
    COMMITTED</> transactions, since in <literal>REPEATABLE READ</> and
15618
    higher isolation levels, transactions use the same snapshot throughout
15619
    their lifetime.  Once a transaction has exported any snapshots, it cannot
15620
    be prepared with <xref linkend="sql-prepare-transaction">.
15621
   </para>
15622
15623
   <para>
15624
    See  <xref linkend="sql-set-transaction"> for details of how to use an
15625
    exported snapshot.
15626
   </para>
15627
  </sect2>
15628
15629
  <sect2 id="functions-admin-dbobject">
15630
   <title>Database Object Management Functions</title>
15631
15632
   <para>
15633
    The functions shown in <xref linkend="functions-admin-dbsize"> calculate
15634
    the disk space usage of database objects.
15635
   </para>
15636
15637
   <indexterm>
15638
    <primary>pg_column_size</primary>
15639
   </indexterm>
15640
   <indexterm>
15641
    <primary>pg_database_size</primary>
15642
   </indexterm>
15643
   <indexterm>
15644
    <primary>pg_indexes_size</primary>
15645
   </indexterm>
15646
   <indexterm>
15647
    <primary>pg_relation_size</primary>
15648
   </indexterm>
15649
   <indexterm>
15650
    <primary>pg_size_pretty</primary>
15651
   </indexterm>
15652
   <indexterm>
15653
    <primary>pg_table_size</primary>
15654
   </indexterm>
15655
   <indexterm>
15656
    <primary>pg_tablespace_size</primary>
15657
   </indexterm>
15658
   <indexterm>
15659
    <primary>pg_total_relation_size</primary>
15660
   </indexterm>
15661
15662
   <table id="functions-admin-dbsize">
15663
    <title>Database Object Size Functions</title>
15664
    <tgroup cols="3">
15665
     <thead>
15666
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
15667
      </row>
15668
     </thead>
15669
15670
     <tbody>
15671
      <row>
15672
       <entry><literal><function>pg_column_size(<type>any</type>)</function></literal></entry>
15673
       <entry><type>int</type></entry>
15674
       <entry>Number of bytes used to store a particular value (possibly compressed)</entry>
15675
      </row>
15676
      <row>
15677
       <entry>
15678
        <literal><function>pg_database_size(<type>oid</type>)</function></literal>
15679
        </entry>
15680
       <entry><type>bigint</type></entry>
15681
       <entry>Disk space used by the database with the specified OID</entry>
15682
      </row>
15683
      <row>
15684
       <entry>
15685
        <literal><function>pg_database_size(<type>name</type>)</function></literal>
15686
        </entry>
15687
       <entry><type>bigint</type></entry>
15688
       <entry>Disk space used by the database with the specified name</entry>
15689
      </row>
15690
      <row>
15691
       <entry>
15692
        <literal><function>pg_indexes_size(<type>regclass</type>)</function></literal>
15693
        </entry>
15694
       <entry><type>bigint</type></entry>
15695
       <entry>
15696
        Total disk space used by indexes attached to the specified table
15697
       </entry>
15698
      </row>
15699
      <row>
15700
       <entry>
15701
        <literal><function>pg_relation_size(<parameter>relation</parameter> <type>regclass</type>, <parameter>fork</parameter> <type>text</type>)</function></literal>
15702
        </entry>
15703
       <entry><type>bigint</type></entry>
15704
       <entry>
15705
        Disk space used by the specified fork (<literal>'main'</literal>,
1.2.1 by Martin Pitt
Import upstream version 9.3.6
15706
        <literal>'fsm'</literal>, <literal>'vm'</>, or <literal>'init'</>)
1 by Martin Pitt
Import upstream version 9.3~beta1
15707
        of the specified table or index
15708
       </entry>
15709
      </row>
15710
      <row>
15711
       <entry>
15712
        <literal><function>pg_relation_size(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
15713
        </entry>
15714
       <entry><type>bigint</type></entry>
15715
       <entry>
15716
        Shorthand for <literal>pg_relation_size(..., 'main')</literal>
15717
       </entry>
15718
      </row>
15719
      <row>
15720
       <entry>
15721
        <literal><function>pg_size_pretty(<type>bigint</type>)</function></literal>
15722
        </entry>
15723
       <entry><type>text</type></entry>
15724
       <entry>
15725
         Converts a size in bytes expressed as a 64-bit integer into a
15726
         human-readable format with size units
15727
       </entry>
15728
      </row>
15729
      <row>
15730
       <entry>
15731
        <literal><function>pg_size_pretty(<type>numeric</type>)</function></literal>
15732
        </entry>
15733
       <entry><type>text</type></entry>
15734
       <entry>
15735
         Converts a size in bytes expressed as a numeric value into a
15736
         human-readable format with size units
15737
       </entry>
15738
      </row>
15739
      <row>
15740
       <entry>
15741
        <literal><function>pg_table_size(<type>regclass</type>)</function></literal>
15742
        </entry>
15743
       <entry><type>bigint</type></entry>
15744
       <entry>
15745
        Disk space used by the specified table, excluding indexes
15746
        (but including TOAST, free space map, and visibility map)
15747
       </entry>
15748
      </row>
15749
      <row>
15750
       <entry>
15751
        <literal><function>pg_tablespace_size(<type>oid</type>)</function></literal>
15752
        </entry>
15753
       <entry><type>bigint</type></entry>
15754
       <entry>Disk space used by the tablespace with the specified OID</entry>
15755
      </row>
15756
      <row>
15757
       <entry>
15758
        <literal><function>pg_tablespace_size(<type>name</type>)</function></literal>
15759
        </entry>
15760
       <entry><type>bigint</type></entry>
15761
       <entry>Disk space used by the tablespace with the specified name</entry>
15762
      </row>
15763
      <row>
15764
       <entry>
15765
        <literal><function>pg_total_relation_size(<type>regclass</type>)</function></literal>
15766
        </entry>
15767
       <entry><type>bigint</type></entry>
15768
       <entry>
15769
        Total disk space used by the specified table,
15770
        including all indexes and <acronym>TOAST</> data
15771
       </entry>
15772
      </row>
15773
     </tbody>
15774
    </tgroup>
15775
   </table>
15776
15777
   <para>
15778
    <function>pg_column_size</> shows the space used to store any individual
15779
    data value.
15780
   </para>
15781
15782
   <para>
15783
    <function>pg_total_relation_size</> accepts the OID or name of a
15784
    table or toast table, and returns the total on-disk space used for
15785
    that table, including all associated indexes.  This function is
15786
    equivalent to <function>pg_table_size</function>
15787
    <literal>+</> <function>pg_indexes_size</function>.
15788
   </para>
15789
15790
   <para>
15791
    <function>pg_table_size</> accepts the OID or name of a table and
15792
    returns the disk space needed for that table, exclusive of indexes.
15793
    (TOAST space, free space map, and visibility map are included.)
15794
   </para>
15795
15796
   <para>
15797
    <function>pg_indexes_size</> accepts the OID or name of a table and
15798
    returns the total disk space used by all the indexes attached to that
15799
    table.
15800
   </para>
15801
15802
   <para>
15803
    <function>pg_database_size</function> and <function>pg_tablespace_size</>
15804
    accept the OID or name of a database or tablespace, and return the total
1.1.8 by Martin Pitt
Import upstream version 9.3.5
15805
    disk space used therein.  To use <function>pg_database_size</function>,
15806
    you must have <literal>CONNECT</> permission on the specified database
15807
    (which is granted by default).  To use <function>pg_tablespace_size</>,
15808
    you must have <literal>CREATE</> permission on the specified tablespace,
15809
    unless it is the default tablespace for the current database.
1 by Martin Pitt
Import upstream version 9.3~beta1
15810
   </para>
15811
15812
   <para>
1.2.1 by Martin Pitt
Import upstream version 9.3.6
15813
    <function>pg_relation_size</> accepts the OID or name of a table, index
15814
    or toast table, and returns the on-disk size in bytes of one fork of
15815
    that relation.  (Note that for most purposes it is more convenient to
15816
    use the higher-level functions <function>pg_total_relation_size</>
15817
    or <function>pg_table_size</>, which sum the sizes of all forks.)
15818
    With one argument, it returns the size of the main data fork of the
15819
    relation.  The second argument can be provided to specify which fork
15820
    to examine:
15821
    <itemizedlist spacing="compact">
15822
     <listitem>
15823
      <para>
15824
       <literal>'main'</literal> returns the size of the main
15825
       data fork of the relation.
15826
      </para>
15827
     </listitem>
15828
     <listitem>
15829
      <para>
15830
       <literal>'fsm'</literal> returns the size of the Free Space Map
15831
       (see <xref linkend="storage-fsm">) associated with the relation.
15832
      </para>
15833
     </listitem>
15834
     <listitem>
15835
      <para>
15836
       <literal>'vm'</literal> returns the size of the Visibility Map
15837
       (see <xref linkend="storage-vm">) associated with the relation.
15838
      </para>
15839
     </listitem>
15840
     <listitem>
15841
      <para>
15842
       <literal>'init'</literal> returns the size of the initialization fork,
15843
       if any, (see <xref linkend="storage-init">) associated with the relation.
15844
      </para>
15845
     </listitem>
15846
    </itemizedlist>
1 by Martin Pitt
Import upstream version 9.3~beta1
15847
   </para>
15848
15849
   <para>
15850
    <function>pg_size_pretty</> can be used to format the result of one of
15851
    the other functions in a human-readable way, using kB, MB, GB or TB as
15852
    appropriate.
15853
   </para>
15854
15855
   <para>
15856
    The functions above that operate on tables or indexes accept a
15857
    <type>regclass</> argument, which is simply the OID of the table or index
15858
    in the <structname>pg_class</> system catalog.  You do not have to look up
15859
    the OID by hand, however, since the <type>regclass</> data type's input
15860
    converter will do the work for you.  Just write the table name enclosed in
15861
    single quotes so that it looks like a literal constant.  For compatibility
15862
    with the handling of ordinary <acronym>SQL</acronym> names, the string
15863
    will be converted to lower case unless it contains double quotes around
15864
    the table name.
15865
   </para>
15866
15867
   <para>
15868
    If an OID that does not represent an existing object is passed as
15869
    argument to one of the above functions, NULL is returned.
15870
   </para>
15871
15872
   <para>
15873
    The functions shown in <xref linkend="functions-admin-dblocation"> assist
15874
    in identifying the specific disk files associated with database objects.
15875
   </para>
15876
15877
   <indexterm>
15878
    <primary>pg_relation_filenode</primary>
15879
   </indexterm>
15880
   <indexterm>
15881
    <primary>pg_relation_filepath</primary>
15882
   </indexterm>
15883
15884
   <table id="functions-admin-dblocation">
15885
    <title>Database Object Location Functions</title>
15886
    <tgroup cols="3">
15887
     <thead>
15888
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
15889
      </row>
15890
     </thead>
15891
15892
     <tbody>
15893
      <row>
15894
       <entry>
15895
        <literal><function>pg_relation_filenode(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
15896
        </entry>
15897
       <entry><type>oid</type></entry>
15898
       <entry>
15899
        Filenode number of the specified relation
15900
       </entry>
15901
      </row>
15902
      <row>
15903
       <entry>
15904
        <literal><function>pg_relation_filepath(<parameter>relation</parameter> <type>regclass</type>)</function></literal>
15905
        </entry>
15906
       <entry><type>text</type></entry>
15907
       <entry>
15908
        File path name of the specified relation
15909
       </entry>
15910
      </row>
15911
     </tbody>
15912
    </tgroup>
15913
   </table>
15914
15915
   <para>
15916
    <function>pg_relation_filenode</> accepts the OID or name of a table,
15917
    index, sequence, or toast table, and returns the <quote>filenode</> number
15918
    currently assigned to it.  The filenode is the base component of the file
15919
    name(s) used for the relation (see <xref linkend="storage-file-layout">
15920
    for more information).  For most tables the result is the same as
15921
    <structname>pg_class</>.<structfield>relfilenode</>, but for certain
15922
    system catalogs <structfield>relfilenode</> is zero and this function must
15923
    be used to get the correct value.  The function returns NULL if passed
15924
    a relation that does not have storage, such as a view.
15925
   </para>
15926
15927
   <para>
15928
    <function>pg_relation_filepath</> is similar to
15929
    <function>pg_relation_filenode</>, but it returns the entire file path name
15930
    (relative to the database cluster's data directory <varname>PGDATA</>) of
15931
    the relation.
15932
   </para>
15933
15934
  </sect2>
15935
15936
  <sect2 id="functions-admin-genfile">
15937
   <title>Generic File Access Functions</title>
15938
15939
   <para>
15940
    The functions shown in <xref
15941
    linkend="functions-admin-genfile-table"> provide native access to
15942
    files on the machine hosting the server. Only files within the
15943
    database cluster directory and the <varname>log_directory</> can be
15944
    accessed.  Use a relative path for files in the cluster directory,
15945
    and a path matching the <varname>log_directory</> configuration setting
15946
    for log files.  Use of these functions is restricted to superusers.
15947
   </para>
15948
15949
   <table id="functions-admin-genfile-table">
15950
    <title>Generic File Access Functions</title>
15951
    <tgroup cols="3">
15952
     <thead>
15953
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
15954
      </row>
15955
     </thead>
15956
15957
     <tbody>
15958
      <row>
15959
       <entry>
15960
        <literal><function>pg_ls_dir(<parameter>dirname</> <type>text</>)</function></literal>
15961
       </entry>
15962
       <entry><type>setof text</type></entry>
15963
       <entry>List the contents of a directory</entry>
15964
      </row>
15965
      <row>
15966
       <entry>
15967
        <literal><function>pg_read_file(<parameter>filename</> <type>text</> [, <parameter>offset</> <type>bigint</>, <parameter>length</> <type>bigint</>])</function></literal>
15968
       </entry>
15969
       <entry><type>text</type></entry>
15970
       <entry>Return the contents of a text file</entry>
15971
      </row>
15972
      <row>
15973
       <entry>
15974
        <literal><function>pg_read_binary_file(<parameter>filename</> <type>text</> [, <parameter>offset</> <type>bigint</>, <parameter>length</> <type>bigint</>])</function></literal>
15975
       </entry>
15976
       <entry><type>bytea</type></entry>
15977
       <entry>Return the contents of a file</entry>
15978
      </row>
15979
      <row>
15980
       <entry>
15981
        <literal><function>pg_stat_file(<parameter>filename</> <type>text</>)</function></literal>
15982
       </entry>
15983
       <entry><type>record</type></entry>
15984
       <entry>Return information about a file</entry>
15985
      </row>
15986
     </tbody>
15987
    </tgroup>
15988
   </table>
15989
15990
   <indexterm>
15991
    <primary>pg_ls_dir</primary>
15992
   </indexterm>
15993
   <para>
15994
    <function>pg_ls_dir</> returns all the names in the specified
15995
    directory, except the special entries <quote><literal>.</></> and
15996
    <quote><literal>..</></>.
15997
   </para>
15998
15999
   <indexterm>
16000
    <primary>pg_read_file</primary>
16001
   </indexterm>
16002
   <para>
16003
    <function>pg_read_file</> returns part of a text file, starting
16004
    at the given <parameter>offset</>, returning at most <parameter>length</>
16005
    bytes (less if the end of file is reached first).  If <parameter>offset</>
16006
    is negative, it is relative to the end of the file.
16007
    If <parameter>offset</> and <parameter>length</> are omitted, the entire
16008
    file is returned.  The bytes read from the file are interpreted as a string
16009
    in the server encoding; an error is thrown if they are not valid in that
16010
    encoding.
16011
   </para>
16012
16013
   <indexterm>
16014
    <primary>pg_read_binary_file</primary>
16015
   </indexterm>
16016
   <para>
16017
    <function>pg_read_binary_file</> is similar to
16018
    <function>pg_read_file</>, except that the result is a <type>bytea</type> value;
16019
    accordingly, no encoding checks are performed.
16020
    In combination with the <function>convert_from</> function, this function
16021
    can be used to read a file in a specified encoding:
16022
<programlisting>
16023
SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');
16024
</programlisting>
16025
   </para>
16026
16027
   <indexterm>
16028
    <primary>pg_stat_file</primary>
16029
   </indexterm>
16030
   <para>
16031
    <function>pg_stat_file</> returns a record containing the file
16032
    size, last accessed time stamp, last modified time stamp,
16033
    last file status change time stamp (Unix platforms only),
16034
    file creation time stamp (Windows only), and a <type>boolean</type>
16035
    indicating if it is a directory.  Typical usages include:
16036
<programlisting>
16037
SELECT * FROM pg_stat_file('filename');
16038
SELECT (pg_stat_file('filename')).modification;
16039
</programlisting>
16040
   </para>
16041
16042
  </sect2>
16043
16044
  <sect2 id="functions-advisory-locks">
16045
   <title>Advisory Lock Functions</title>
16046
16047
   <para>
16048
    The functions shown in <xref linkend="functions-advisory-locks-table">
16049
    manage advisory locks.  For details about proper use of these functions,
16050
    see <xref linkend="advisory-locks">.
16051
   </para>
16052
16053
   <table id="functions-advisory-locks-table">
16054
    <title>Advisory Lock Functions</title>
16055
    <tgroup cols="3">
16056
     <thead>
16057
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
16058
      </row>
16059
     </thead>
16060
16061
     <tbody>
16062
      <row>
16063
       <entry>
16064
        <literal><function>pg_advisory_lock(<parameter>key</> <type>bigint</>)</function></literal>
16065
       </entry>
16066
       <entry><type>void</type></entry>
16067
       <entry>Obtain exclusive session level advisory lock</entry>
16068
      </row>
16069
      <row>
16070
       <entry>
16071
        <literal><function>pg_advisory_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16072
       </entry>
16073
       <entry><type>void</type></entry>
16074
       <entry>Obtain exclusive session level advisory lock</entry>
16075
      </row>
16076
      <row>
16077
       <entry>
16078
        <literal><function>pg_advisory_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
16079
       </entry>
16080
       <entry><type>void</type></entry>
16081
       <entry>Obtain shared session level advisory lock</entry>
16082
      </row>
16083
      <row>
16084
       <entry>
16085
        <literal><function>pg_advisory_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16086
       </entry>
16087
       <entry><type>void</type></entry>
16088
       <entry>Obtain shared session level advisory lock</entry>
16089
      </row>
16090
      <row>
16091
       <entry>
16092
        <literal><function>pg_advisory_unlock(<parameter>key</> <type>bigint</>)</function></literal>
16093
       </entry>
16094
       <entry><type>boolean</type></entry>
16095
       <entry>Release an exclusive session level advisory lock</entry>
16096
      </row>
16097
      <row>
16098
       <entry>
16099
        <literal><function>pg_advisory_unlock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16100
       </entry>
16101
       <entry><type>boolean</type></entry>
16102
       <entry>Release an exclusive session level advisory lock</entry>
16103
      </row>
16104
      <row>
16105
       <entry>
16106
        <literal><function>pg_advisory_unlock_all()</function></literal>
16107
       </entry>
16108
       <entry><type>void</type></entry>
16109
       <entry>Release all session level advisory locks held by the current session</entry>
16110
      </row>
16111
      <row>
16112
       <entry>
16113
        <literal><function>pg_advisory_unlock_shared(<parameter>key</> <type>bigint</>)</function></literal>
16114
       </entry>
16115
       <entry><type>boolean</type></entry>
16116
       <entry>Release a shared session level advisory lock</entry>
16117
      </row>
16118
      <row>
16119
       <entry>
16120
        <literal><function>pg_advisory_unlock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16121
       </entry>
16122
       <entry><type>boolean</type></entry>
16123
       <entry>Release a shared session level advisory lock</entry>
16124
      </row>
16125
      <row>
16126
       <entry>
16127
        <literal><function>pg_advisory_xact_lock(<parameter>key</> <type>bigint</>)</function></literal>
16128
       </entry>
16129
       <entry><type>void</type></entry>
16130
       <entry>Obtain exclusive transaction level advisory lock</entry>
16131
      </row>
16132
      <row>
16133
       <entry>
16134
        <literal><function>pg_advisory_xact_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16135
       </entry>
16136
       <entry><type>void</type></entry>
16137
       <entry>Obtain exclusive transaction level advisory lock</entry>
16138
      </row>
16139
      <row>
16140
       <entry>
16141
        <literal><function>pg_advisory_xact_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
16142
       </entry>
16143
       <entry><type>void</type></entry>
16144
       <entry>Obtain shared transaction level advisory lock</entry>
16145
      </row>
16146
      <row>
16147
       <entry>
16148
        <literal><function>pg_advisory_xact_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16149
       </entry>
16150
       <entry><type>void</type></entry>
16151
       <entry>Obtain shared transaction level advisory lock</entry>
16152
      </row>
16153
      <row>
16154
       <entry>
16155
        <literal><function>pg_try_advisory_lock(<parameter>key</> <type>bigint</>)</function></literal>
16156
       </entry>
16157
       <entry><type>boolean</type></entry>
16158
       <entry>Obtain exclusive session level advisory lock if available</entry>
16159
      </row>
16160
      <row>
16161
       <entry>
16162
        <literal><function>pg_try_advisory_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16163
       </entry>
16164
       <entry><type>boolean</type></entry>
16165
       <entry>Obtain exclusive session level advisory lock if available</entry>
16166
      </row>
16167
      <row>
16168
       <entry>
16169
        <literal><function>pg_try_advisory_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
16170
       </entry>
16171
       <entry><type>boolean</type></entry>
16172
       <entry>Obtain shared session level advisory lock if available</entry>
16173
      </row>
16174
      <row>
16175
       <entry>
16176
        <literal><function>pg_try_advisory_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16177
       </entry>
16178
       <entry><type>boolean</type></entry>
16179
       <entry>Obtain shared session level advisory lock if available</entry>
16180
      </row>
16181
      <row>
16182
       <entry>
16183
        <literal><function>pg_try_advisory_xact_lock(<parameter>key</> <type>bigint</>)</function></literal>
16184
       </entry>
16185
       <entry><type>boolean</type></entry>
16186
       <entry>Obtain exclusive transaction level advisory lock if available</entry>
16187
      </row>
16188
      <row>
16189
       <entry>
16190
        <literal><function>pg_try_advisory_xact_lock(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16191
       </entry>
16192
       <entry><type>boolean</type></entry>
16193
       <entry>Obtain exclusive transaction level advisory lock if available</entry>
16194
      </row>
16195
      <row>
16196
       <entry>
16197
        <literal><function>pg_try_advisory_xact_lock_shared(<parameter>key</> <type>bigint</>)</function></literal>
16198
       </entry>
16199
       <entry><type>boolean</type></entry>
16200
       <entry>Obtain shared transaction level advisory lock if available</entry>
16201
      </row>
16202
      <row>
16203
       <entry>
16204
        <literal><function>pg_try_advisory_xact_lock_shared(<parameter>key1</> <type>int</>, <parameter>key2</> <type>int</>)</function></literal>
16205
       </entry>
16206
       <entry><type>boolean</type></entry>
16207
       <entry>Obtain shared transaction level advisory lock if available</entry>
16208
      </row>
16209
     </tbody>
16210
    </tgroup>
16211
   </table>
16212
16213
   <indexterm>
16214
    <primary>pg_advisory_lock</primary>
16215
   </indexterm>
16216
   <para>
16217
    <function>pg_advisory_lock</> locks an application-defined resource,
16218
    which can be identified either by a single 64-bit key value or two
16219
    32-bit key values (note that these two key spaces do not overlap).
16220
    If another session already holds a lock on the same resource identifier,
16221
    this function will wait until the resource becomes available.  The lock
16222
    is exclusive.  Multiple lock requests stack, so that if the same resource
16223
    is locked three times it must then be unlocked three times to be
16224
    released for other sessions' use.
16225
   </para>
16226
16227
   <indexterm>
16228
    <primary>pg_advisory_lock_shared</primary>
16229
   </indexterm>
16230
   <para>
16231
    <function>pg_advisory_lock_shared</> works the same as
16232
    <function>pg_advisory_lock</>,
16233
    except the lock can be shared with other sessions requesting shared locks.
16234
    Only would-be exclusive lockers are locked out.
16235
   </para>
16236
16237
   <indexterm>
16238
    <primary>pg_try_advisory_lock</primary>
16239
   </indexterm>
16240
   <para>
16241
    <function>pg_try_advisory_lock</> is similar to
16242
    <function>pg_advisory_lock</>, except the function will not wait for the
16243
    lock to become available.  It will either obtain the lock immediately and
16244
    return <literal>true</>, or return <literal>false</> if the lock cannot be
16245
    acquired immediately.
16246
   </para>
16247
16248
   <indexterm>
16249
    <primary>pg_try_advisory_lock_shared</primary>
16250
   </indexterm>
16251
   <para>
16252
    <function>pg_try_advisory_lock_shared</> works the same as
16253
    <function>pg_try_advisory_lock</>, except it attempts to acquire
16254
    a shared rather than an exclusive lock.
16255
   </para>
16256
16257
   <indexterm>
16258
    <primary>pg_advisory_unlock</primary>
16259
   </indexterm>
16260
   <para>
16261
    <function>pg_advisory_unlock</> will release a previously-acquired
16262
    exclusive session level advisory lock.  It
16263
    returns <literal>true</> if the lock is successfully released.
16264
    If the lock was not held, it will return <literal>false</>,
16265
    and in addition, an SQL warning will be reported by the server.
16266
   </para>
16267
16268
   <indexterm>
16269
    <primary>pg_advisory_unlock_shared</primary>
16270
   </indexterm>
16271
   <para>
16272
    <function>pg_advisory_unlock_shared</> works the same as
16273
    <function>pg_advisory_unlock</>,
16274
    except it releases a shared session level advisory lock.
16275
   </para>
16276
16277
   <indexterm>
16278
    <primary>pg_advisory_unlock_all</primary>
16279
   </indexterm>
16280
   <para>
16281
    <function>pg_advisory_unlock_all</> will release all session level advisory
16282
    locks held by the current session.  (This function is implicitly invoked
16283
    at session end, even if the client disconnects ungracefully.)
16284
   </para>
16285
16286
   <indexterm>
16287
    <primary>pg_advisory_xact_lock</primary>
16288
   </indexterm>
16289
   <para>
16290
    <function>pg_advisory_xact_lock</> works the same as
16291
    <function>pg_advisory_lock</>, except the lock is automatically released
16292
    at the end of the current transaction and cannot be released explicitly.
16293
   </para>
16294
16295
   <indexterm>
16296
    <primary>pg_advisory_xact_lock_shared</primary>
16297
   </indexterm>
16298
   <para>
16299
    <function>pg_advisory_xact_lock_shared</> works the same as
16300
    <function>pg_advisory_lock_shared</>, except the lock is automatically released
16301
    at the end of the current transaction and cannot be released explicitly.
16302
   </para>
16303
16304
   <indexterm>
16305
    <primary>pg_try_advisory_xact_lock</primary>
16306
   </indexterm>
16307
   <para>
16308
    <function>pg_try_advisory_xact_lock</> works the same as
16309
    <function>pg_try_advisory_lock</>, except the lock, if acquired,
16310
    is automatically released at the end of the current transaction and
16311
    cannot be released explicitly.
16312
   </para>
16313
16314
   <indexterm>
16315
    <primary>pg_try_advisory_xact_lock_shared</primary>
16316
   </indexterm>
16317
   <para>
16318
    <function>pg_try_advisory_xact_lock_shared</> works the same as
16319
    <function>pg_try_advisory_lock_shared</>, except the lock, if acquired,
16320
    is automatically released at the end of the current transaction and
16321
    cannot be released explicitly.
16322
   </para>
16323
16324
  </sect2>
16325
16326
  </sect1>
16327
16328
  <sect1 id="functions-trigger">
16329
   <title>Trigger Functions</title>
16330
16331
   <indexterm>
16332
     <primary>suppress_redundant_updates_trigger</primary>
16333
   </indexterm>
16334
16335
   <para>
16336
      Currently <productname>PostgreSQL</> provides one built in trigger
16337
      function, <function>suppress_redundant_updates_trigger</>,
16338
      which will prevent any update
16339
      that does not actually change the data in the row from taking place, in
16340
      contrast to the normal behavior which always performs the update
16341
      regardless of whether or not the data has changed. (This normal behavior
16342
      makes updates run faster, since no checking is required, and is also
16343
      useful in certain cases.)
16344
    </para>
16345
16346
    <para>
16347
      Ideally, you should normally avoid running updates that don't actually
16348
      change the data in the record. Redundant updates can cost considerable
16349
      unnecessary time, especially if there are lots of indexes to alter,
16350
      and space in dead rows that will eventually have to be vacuumed.
16351
      However, detecting such situations in client code is not
16352
      always easy, or even possible, and writing expressions to detect
16353
      them can be error-prone. An alternative is to use
16354
      <function>suppress_redundant_updates_trigger</>, which will skip
16355
      updates that don't change the data. You should use this with care,
16356
      however. The trigger takes a small but non-trivial time for each record,
16357
      so if most of the records affected by an update are actually changed,
16358
      use of this trigger will actually make the update run slower.
16359
    </para>
16360
16361
    <para>
16362
      The <function>suppress_redundant_updates_trigger</> function can be
16363
      added to a table like this:
16364
<programlisting>
16365
CREATE TRIGGER z_min_update
16366
BEFORE UPDATE ON tablename
16367
FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger();
16368
</programlisting>
16369
      In most cases, you would want to fire this trigger last for each row.
16370
      Bearing in mind that triggers fire in name order, you would then
16371
      choose a trigger name that comes after the name of any other trigger
16372
      you might have on the table.
16373
    </para>
16374
    <para>
16375
       For more information about creating triggers, see
16376
        <xref linkend="SQL-CREATETRIGGER">.
16377
    </para>
16378
  </sect1>
16379
16380
  <sect1 id="functions-event-triggers">
16381
   <title>Event Trigger Functions</title>
16382
16383
   <indexterm>
16384
     <primary>pg_event_trigger_dropped_objects</primary>
16385
   </indexterm>
16386
16387
   <para>
16388
    Currently <productname>PostgreSQL</> provides one built-in event trigger
16389
    helper function, <function>pg_event_trigger_dropped_objects</>.
16390
   </para>
16391
16392
   <para>
16393
    <function>pg_event_trigger_dropped_objects</> returns a list of all object
16394
    dropped by the command in whose <literal>sql_drop</> event it is called.
16395
    If called in any other context,
16396
    <function>pg_event_trigger_dropped_objects</> raises an error.
16397
    <function>pg_event_trigger_dropped_objects</> returns the following columns:
16398
16399
    <informaltable>
16400
     <tgroup cols="3">
16401
      <thead>
16402
       <row>
16403
        <entry>Name</entry>
16404
        <entry>Type</entry>
16405
        <entry>Description</entry>
16406
       </row>
16407
      </thead>
16408
16409
      <tbody>
16410
       <row>
16411
        <entry><literal>classid</literal></entry>
16412
        <entry><type>Oid</type></entry>
16413
        <entry>OID of catalog the object belonged in</entry>
16414
       </row>
16415
       <row>
16416
        <entry><literal>objid</literal></entry>
16417
        <entry><type>Oid</type></entry>
16418
        <entry>OID the object had within the catalog</entry>
16419
       </row>
16420
       <row>
16421
        <entry><literal>objsubid</literal></entry>
16422
        <entry><type>int32</type></entry>
16423
        <entry>Object sub-id (e.g. attribute number for columns)</entry>
16424
       </row>
16425
       <row>
16426
        <entry><literal>object_type</literal></entry>
16427
        <entry><type>text</type></entry>
16428
        <entry>Type of the object</entry>
16429
       </row>
16430
       <row>
16431
        <entry><literal>schema_name</literal></entry>
16432
        <entry><type>text</type></entry>
16433
        <entry>
16434
         Name of the schema the object belonged in, if any; otherwise <literal>NULL</>.
16435
         No quoting is applied.
16436
        </entry>
16437
       </row>
16438
       <row>
16439
        <entry><literal>object_name</literal></entry>
16440
        <entry><type>text</type></entry>
16441
        <entry>
16442
         Name of the object, if the combination of schema and name can be
1.2.1 by Martin Pitt
Import upstream version 9.3.6
16443
         used as a unique identifier for the object; otherwise <literal>NULL</>.
1 by Martin Pitt
Import upstream version 9.3~beta1
16444
         No quoting is applied, and name is never schema-qualified.
16445
        </entry>
16446
       </row>
16447
       <row>
16448
        <entry><literal>object_identity</literal></entry>
16449
        <entry><type>text</type></entry>
16450
        <entry>
16451
         Text rendering of the object identity, schema-qualified. Each and every
16452
         identifier present in the identity is quoted if necessary.
16453
        </entry>
16454
       </row>
16455
      </tbody>
16456
     </tgroup>
16457
    </informaltable>
16458
   </para>
16459
16460
   <para>
16461
    The <function>pg_event_trigger_dropped_objects</> function can be used
16462
    in an event trigger like this:
16463
<programlisting>
16464
CREATE FUNCTION test_event_trigger_for_drops()
16465
        RETURNS event_trigger LANGUAGE plpgsql AS $$
16466
DECLARE
16467
    obj record;
16468
BEGIN
16469
    FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects()
16470
    LOOP
16471
        RAISE NOTICE '% dropped object: % %.% %',
16472
                     tg_tag,
16473
                     obj.object_type,
16474
                     obj.schema_name,
16475
                     obj.object_name,
16476
                     obj.object_identity;
16477
    END LOOP;
16478
END
16479
$$;
16480
CREATE EVENT TRIGGER test_event_trigger_for_drops
16481
   ON sql_drop
16482
   EXECUTE PROCEDURE test_event_trigger_for_drops();
16483
</programlisting>
16484
    </para>
16485
16486
     <para>
16487
       For more information about event triggers,
16488
       see <xref linkend="event-triggers">.
16489
    </para>
16490
  </sect1>
16491
16492
</chapter>