func.sgml 345.7 KB
Newer Older
1
<!--
2
$PostgreSQL: pgsql/doc/src/sgml/func.sgml,v 1.307 2006/02/18 16:15:21 petere Exp $
3
PostgreSQL documentation
4
-->
5

6 7 8 9
 <chapter id="functions">
  <title>Functions and Operators</title>

  <indexterm zone="functions">
P
Peter Eisentraut 已提交
10
   <primary>function</primary>
11 12
  </indexterm>

13
  <indexterm zone="functions">
P
Peter Eisentraut 已提交
14
   <primary>operator</primary>
15 16
  </indexterm>

17
  <para>
18 19
   <productname>PostgreSQL</productname> provides a large number of
   functions and operators for the built-in data types.  Users can also
20 21
   define their own functions and operators, as described in
   <xref linkend="server-programming">.  The
22 23 24 25
   <application>psql</application> commands <command>\df</command> and
   <command>\do</command> can be used to show the list of all actually
   available functions and operators, respectively.
  </para>
26

27 28 29 30 31
  <para>
   If you are concerned about portability then take note that most of
   the functions and operators described in this chapter, with the
   exception of the most trivial arithmetic and comparison operators
   and some explicitly marked functions, are not specified by the
P
Peter Eisentraut 已提交
32 33 34
   <acronym>SQL</acronym> standard. Some of the extended functionality
   is present in other <acronym>SQL</acronym> database management
   systems, and in many cases this functionality is compatible and
35
   consistent between the various implementations.  This chapter is also
36
   not exhaustive;  additional functions appear in relevant sections of 
37
   the manual.
38
  </para>
39

40 41 42 43 44

  <sect1 id="functions-logical">
   <title>Logical Operators</title>

   <indexterm zone="functions-logical">
P
Peter Eisentraut 已提交
45
    <primary>operator</primary>
46
    <secondary>logical</secondary>
47 48 49
   </indexterm>

   <indexterm>
50 51 52
    <primary>Boolean</primary>
    <secondary>operators</secondary>
    <see>operators, logical</see>
53 54
   </indexterm>

55 56
   <para>
    The usual logical operators are available:
57

58
    <indexterm>
P
Peter Eisentraut 已提交
59
     <primary>AND (operator)</primary>
60
    </indexterm>
61

62
    <indexterm>
P
Peter Eisentraut 已提交
63
     <primary>OR (operator)</primary>
64
    </indexterm>
65

66
    <indexterm>
P
Peter Eisentraut 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79
     <primary>NOT (operator)</primary>
    </indexterm>

    <indexterm>
     <primary>conjunction</primary>
    </indexterm>

    <indexterm>
     <primary>disjunction</primary>
    </indexterm>

    <indexterm>
     <primary>negation</primary>
80
    </indexterm>
81

82
    <simplelist>
83 84 85
     <member><literal>AND</></member>
     <member><literal>OR</></member>
     <member><literal>NOT</></member>
86
    </simplelist>
87

P
Peter Eisentraut 已提交
88
    <acronym>SQL</acronym> uses a three-valued Boolean logic where the null value represents
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    <quote>unknown</quote>.  Observe the following truth tables:

    <informaltable>
     <tgroup cols="4">
      <thead>
       <row>
        <entry><replaceable>a</replaceable></entry>
        <entry><replaceable>b</replaceable></entry>
        <entry><replaceable>a</replaceable> AND <replaceable>b</replaceable></entry>
        <entry><replaceable>a</replaceable> OR <replaceable>b</replaceable></entry>
       </row>
      </thead>

      <tbody>
       <row>
        <entry>TRUE</entry>
        <entry>TRUE</entry>
        <entry>TRUE</entry>
        <entry>TRUE</entry>
       </row>

       <row>
        <entry>TRUE</entry>
        <entry>FALSE</entry>
        <entry>FALSE</entry>
        <entry>TRUE</entry>
       </row>

       <row>
        <entry>TRUE</entry>
        <entry>NULL</entry>
        <entry>NULL</entry>
        <entry>TRUE</entry>
       </row>

       <row>
        <entry>FALSE</entry>
        <entry>FALSE</entry>
        <entry>FALSE</entry>
        <entry>FALSE</entry>
       </row>

       <row>
        <entry>FALSE</entry>
        <entry>NULL</entry>
        <entry>FALSE</entry>
        <entry>NULL</entry>
       </row>

       <row>
        <entry>NULL</entry>
        <entry>NULL</entry>
        <entry>NULL</entry>
        <entry>NULL</entry>
       </row>
      </tbody>
     </tgroup>
    </informaltable>

    <informaltable>
     <tgroup cols="2">
      <thead>
       <row>
        <entry><replaceable>a</replaceable></entry>
        <entry>NOT <replaceable>a</replaceable></entry>
       </row>
      </thead>

      <tbody>
       <row>
        <entry>TRUE</entry>
        <entry>FALSE</entry>
       </row>
162

163 164 165 166 167 168 169 170 171 172 173 174 175
       <row>
        <entry>FALSE</entry>
        <entry>TRUE</entry>
       </row>

       <row>
        <entry>NULL</entry>
        <entry>NULL</entry>
       </row>
      </tbody>
     </tgroup>
    </informaltable>
   </para>
176 177 178 179 180 181 182 183

   <para>
    The operators <literal>AND</literal> and <literal>OR</literal> are
    commutative, that is, you can switch the left and right operand
    without affecting the result.  But see <xref
    linkend="syntax-express-eval"> for more information about the
    order of evaluation of subexpressions.
   </para>
184 185 186 187 188 189 190 191 192 193
  </sect1>

  <sect1 id="functions-comparison">
   <title>Comparison Operators</title>

   <indexterm zone="functions-comparison">
    <primary>comparison</primary>
    <secondary>operators</secondary>
   </indexterm>

194 195 196 197 198 199
   <para>
    The usual comparison operators are available, shown in <xref
    linkend="functions-comparison-table">.
   </para>

   <table id="functions-comparison-table">
200 201 202
    <title>Comparison Operators</title>
    <tgroup cols="2">
     <thead>
203
      <row>
204 205
       <entry>Operator</entry>
       <entry>Description</entry>
206
      </row>
207
     </thead>
208

209
     <tbody>
210
      <row>
211 212
       <entry> <literal>&lt;</literal> </entry>
       <entry>less than</entry>
213
      </row>
214 215

      <row>
216 217
       <entry> <literal>&gt;</literal> </entry>
       <entry>greater than</entry>
218
      </row>
219 220

      <row>
221 222
       <entry> <literal>&lt;=</literal> </entry>
       <entry>less than or equal to</entry>
223 224 225
      </row>

      <row>
226 227
       <entry> <literal>&gt;=</literal> </entry>
       <entry>greater than or equal to</entry>
228 229 230
      </row>

      <row>
231 232
       <entry> <literal>=</literal> </entry>
       <entry>equal</entry>
233 234 235
      </row>

      <row>
236 237
       <entry> <literal>&lt;&gt;</literal> or <literal>!=</literal> </entry>
       <entry>not equal</entry>
238 239 240
      </row>
     </tbody>
    </tgroup>
241
   </table>
242

243 244 245 246 247 248 249 250
   <note>
    <para>
     The <literal>!=</literal> operator is converted to
     <literal>&lt;&gt;</literal> in the parser stage.  It is not
     possible to implement <literal>!=</literal> and
     <literal>&lt;&gt;</literal> operators that do different things.
    </para>
   </note>
251

T
Thomas G. Lockhart 已提交
252
   <para>
253 254 255 256 257 258
    Comparison operators are available for all data types where this
    makes sense.  All comparison operators are binary operators that
    return values of type <type>boolean</type>; expressions like
    <literal>1 &lt; 2 &lt; 3</literal> are not valid (because there is
    no <literal>&lt;</literal> operator to compare a Boolean value with
    <literal>3</literal>).
T
Thomas G. Lockhart 已提交
259
   </para>
260

261 262
   <para>
    <indexterm>
263
     <primary>BETWEEN</primary>
264 265
    </indexterm>
    In addition to the comparison operators, the special
266
    <token>BETWEEN</token> construct is available.
267
<synopsis>
P
Peter Eisentraut 已提交
268
<replaceable>a</replaceable> BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
269
</synopsis>
270
    is equivalent to
271
<synopsis>
B
Bruce Momjian 已提交
272
<replaceable>a</replaceable> &gt;= <replaceable>x</replaceable> AND <replaceable>a</replaceable> &lt;= <replaceable>y</replaceable>
273
</synopsis>
274
    Similarly,
275
<synopsis>
P
Peter Eisentraut 已提交
276
<replaceable>a</replaceable> NOT BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
277
</synopsis>
278
    is equivalent to
279
<synopsis>
B
Bruce Momjian 已提交
280
<replaceable>a</replaceable> &lt; <replaceable>x</replaceable> OR <replaceable>a</replaceable> &gt; <replaceable>y</replaceable>
281
</synopsis>
282 283 284
    There is no difference between the two respective forms apart from
    the <acronym>CPU</acronym> cycles required to rewrite the first one
    into the second one internally.
B
Bruce Momjian 已提交
285 286 287 288 289 290
    <indexterm>
     <primary>BETWEEN SYMETRIC</primary>
    </indexterm>
    <token>BETWEEN SYMMETRIC</> is the same as <literal>BETWEEN</>
    except there is no requirement that the argument to the left of <literal>AND</> be less than
    or equal to the argument on the right;  the proper range is automatically determined.
291
   </para>
P
Peter Eisentraut 已提交
292

293
   <para>
294 295 296 297 298 299 300 301 302 303 304 305
    <indexterm>
     <primary>IS NULL</primary>
    </indexterm>
    <indexterm>
     <primary>IS NOT NULL</primary>
    </indexterm>
    <indexterm>
     <primary>ISNULL</primary>
    </indexterm>
    <indexterm>
     <primary>NOTNULL</primary>
    </indexterm>
P
Peter Eisentraut 已提交
306
    To check whether a value is or is not null, use the constructs
307
<synopsis>
308 309
<replaceable>expression</replaceable> IS NULL
<replaceable>expression</replaceable> IS NOT NULL
310 311 312
</synopsis>
    or the equivalent, but nonstandard, constructs
<synopsis>
313 314
<replaceable>expression</replaceable> ISNULL
<replaceable>expression</replaceable> NOTNULL
315
</synopsis>
P
Peter Eisentraut 已提交
316
    <indexterm><primary>null value</primary><secondary>comparing</secondary></indexterm>
317
   </para>
318

319 320 321
   <para>
    Do <emphasis>not</emphasis> write
    <literal><replaceable>expression</replaceable> = NULL</literal>
P
Peter Eisentraut 已提交
322 323
    because <literal>NULL</> is not <quote>equal to</quote>
    <literal>NULL</>.  (The null value represents an unknown value,
324 325
    and it is not known whether two unknown values are equal.) This
    behavior conforms to the SQL standard.
326
   </para>
327

328
  <tip>
329
   <para>
330
    Some applications may expect that
331 332
    <literal><replaceable>expression</replaceable> = NULL</literal>
    returns true if <replaceable>expression</replaceable> evaluates to
333 334
    the null value.  It is highly recommended that these applications
    be modified to comply with the SQL standard. However, if that
335
    cannot be done the <xref linkend="guc-transform-null-equals">
336 337 338 339 340
    configuration variable is available. If it is enabled,
    <productname>PostgreSQL</productname> will convert <literal>x =
    NULL</literal> clauses to <literal>x IS NULL</literal>.  This was
    the default behavior in <productname>PostgreSQL</productname>
    releases 6.5 through 7.1.
341
   </para>
342
  </tip>
343

344
   <para>
345 346 347
    <indexterm>
     <primary>IS DISTINCT FROM</primary>
    </indexterm>
348 349 350
    <indexterm>
     <primary>IS NOT DISTINCT FROM</primary>
    </indexterm>
351 352
    The ordinary comparison operators yield null (signifying <quote>unknown</>)
    when either input is null.  Another way to do comparisons is with the
353
    <literal>IS <optional> NOT </> DISTINCT FROM</literal> construct:
354 355
<synopsis>
<replaceable>expression</replaceable> IS DISTINCT FROM <replaceable>expression</replaceable>
356
<replaceable>expression</replaceable> IS NOT DISTINCT FROM <replaceable>expression</replaceable>
357
</synopsis>
358
    For non-null inputs, <literal>IS DISTINCT FROM</literal> is
359 360 361 362
    the same as the <literal>&lt;&gt;</> operator.  However, when both
    inputs are null it will return false, and when just one input is
    null it will return true.  Similarly, <literal>IS NOT DISTINCT
    FROM</literal> is identical to <literal>=</literal> for non-null
363 364
    inputs, but it returns true when both inputs are null, and false when only
    one input is null. Thus, these constructs effectively act as though null
365
    were a normal data value, rather than <quote>unknown</>.
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
   </para>

   <para>
    <indexterm>
     <primary>IS TRUE</primary>
    </indexterm>
    <indexterm>
     <primary>IS NOT TRUE</primary>
    </indexterm>
    <indexterm>
     <primary>IS FALSE</primary>
    </indexterm>
    <indexterm>
     <primary>IS NOT FALSE</primary>
    </indexterm>
    <indexterm>
     <primary>IS UNKNOWN</primary>
    </indexterm>
    <indexterm>
     <primary>IS NOT UNKNOWN</primary>
    </indexterm>
387
    Boolean values can also be tested using the constructs
388
<synopsis>
389 390 391 392 393 394
<replaceable>expression</replaceable> IS TRUE
<replaceable>expression</replaceable> IS NOT TRUE
<replaceable>expression</replaceable> IS FALSE
<replaceable>expression</replaceable> IS NOT FALSE
<replaceable>expression</replaceable> IS UNKNOWN
<replaceable>expression</replaceable> IS NOT UNKNOWN
395
</synopsis>
396 397
    These will always return true or false, never a null value, even when the
    operand is null.
P
Peter Eisentraut 已提交
398
    A null input is treated as the logical value <quote>unknown</>.
399 400 401 402
    Notice that <literal>IS UNKNOWN</> and <literal>IS NOT UNKNOWN</> are
    effectively the same as <literal>IS NULL</literal> and
    <literal>IS NOT NULL</literal>, respectively, except that the input
    expression must be of Boolean type.
403 404
   </para>
  </sect1>
405

406 407
  <sect1 id="functions-math">
   <title>Mathematical Functions and Operators</title>
408

409 410 411 412
   <para>
    Mathematical operators are provided for many
    <productname>PostgreSQL</productname> types. For types without
    common mathematical conventions for all possible permutations 
413
    (e.g., date/time types) we
414 415
    describe the actual behavior in subsequent sections.
   </para>
416

417 418 419 420 421
   <para>
    <xref linkend="functions-math-op-table"> shows the available mathematical operators.
   </para>

   <table id="functions-math-op-table">
422
    <title>Mathematical Operators</title>
423

424
    <tgroup cols="4">
425 426
     <thead>
      <row>
427
       <entry>Operator</entry>
428
       <entry>Description</entry>
429 430 431 432 433 434 435
       <entry>Example</entry>
       <entry>Result</entry>
      </row>
     </thead>

     <tbody>
      <row>
436
       <entry> <literal>+</literal> </entry>
437
       <entry>addition</entry>
438 439
       <entry><literal>2 + 3</literal></entry>
       <entry><literal>5</literal></entry>
440
      </row>
441

442
      <row>
443
       <entry> <literal>-</literal> </entry>
444
       <entry>subtraction</entry>
445 446
       <entry><literal>2 - 3</literal></entry>
       <entry><literal>-1</literal></entry>
447
      </row>
448

449
      <row>
450
       <entry> <literal>*</literal> </entry>
451
       <entry>multiplication</entry>
452 453
       <entry><literal>2 * 3</literal></entry>
       <entry><literal>6</literal></entry>
454
      </row>
455

456
      <row>
457
       <entry> <literal>/</literal> </entry>
458
       <entry>division (integer division truncates results)</entry>
459 460
       <entry><literal>4 / 2</literal></entry>
       <entry><literal>2</literal></entry>
461
      </row>
462

463
      <row>
464
       <entry> <literal>%</literal> </entry>
465
       <entry>modulo (remainder)</entry>
466 467
       <entry><literal>5 % 4</literal></entry>
       <entry><literal>1</literal></entry>
468
      </row>
469

470
      <row>
471
       <entry> <literal>^</literal> </entry>
472
       <entry>exponentiation</entry>
473 474
       <entry><literal>2.0 ^ 3.0</literal></entry>
       <entry><literal>8</literal></entry>
475 476
      </row>

477 478
      <row>
       <entry> <literal>|/</literal> </entry>
479
       <entry>square root</entry>
480 481
       <entry><literal>|/ 25.0</literal></entry>
       <entry><literal>5</literal></entry>
482
      </row>
483

484 485
      <row>
       <entry> <literal>||/</literal> </entry>
486
       <entry>cube root</entry>
487 488
       <entry><literal>||/ 27.0</literal></entry>
       <entry><literal>3</literal></entry>
489
      </row>
490

491 492
      <row>
       <entry> <literal>!</literal> </entry>
493
       <entry>factorial</entry>
494 495
       <entry><literal>5 !</literal></entry>
       <entry><literal>120</literal></entry>
496
      </row>
497

498 499
      <row>
       <entry> <literal>!!</literal> </entry>
500
       <entry>factorial (prefix operator)</entry>
501 502
       <entry><literal>!! 5</literal></entry>
       <entry><literal>120</literal></entry>
503
      </row>
504

505 506
      <row>
       <entry> <literal>@</literal> </entry>
507
       <entry>absolute value</entry>
508 509
       <entry><literal>@ -5.0</literal></entry>
       <entry><literal>5</literal></entry>
510
      </row>
511

512 513
      <row>
       <entry> <literal>&amp;</literal> </entry>
514 515 516
       <entry>bitwise AND</entry>
       <entry><literal>91 &amp; 15</literal></entry>
       <entry><literal>11</literal></entry>
517
      </row>
518

519 520
      <row>
       <entry> <literal>|</literal> </entry>
521 522 523
       <entry>bitwise OR</entry>
       <entry><literal>32 | 3</literal></entry>
       <entry><literal>35</literal></entry>
524
      </row>
525

526 527
      <row>
       <entry> <literal>#</literal> </entry>
528 529 530
       <entry>bitwise XOR</entry>
       <entry><literal>17 # 5</literal></entry>
       <entry><literal>20</literal></entry>
531
      </row>
532

533 534
      <row>
       <entry> <literal>~</literal> </entry>
535 536 537
       <entry>bitwise NOT</entry>
       <entry><literal>~1</literal></entry>
       <entry><literal>-2</literal></entry>
538
      </row>
539

540
      <row>
541
       <entry> <literal>&lt;&lt;</literal> </entry>
542
       <entry>bitwise shift left</entry>
543 544
       <entry><literal>1 &lt;&lt; 4</literal></entry>
       <entry><literal>16</literal></entry>
545
      </row>
546

547
      <row>
548 549 550 551
       <entry> <literal>&gt;&gt;</literal> </entry>
       <entry>bitwise shift right</entry>
       <entry><literal>8 &gt;&gt; 2</literal></entry>
       <entry><literal>2</literal></entry>
552
      </row>
553

554 555 556
     </tbody>
    </tgroup>
   </table>
557

558
   <para>
559 560 561
    The bitwise operators work only on integral data types, whereas
    the others are available for all numeric data types.  The bitwise
    operators are also available for the bit
562
    string types <type>bit</type> and <type>bit varying</type>, as
563
    shown in <xref linkend="functions-bit-string-op-table">.
564
   </para>
565

566 567 568
  <para>
   <xref linkend="functions-math-func-table"> shows the available
   mathematical functions.  In the table, <literal>dp</literal>
569 570 571
   indicates <type>double precision</type>.  Many of these functions
   are provided in multiple forms with different argument types.
   Except where noted, any given form of a function returns the same
572
   data type as its argument.
573 574 575
   The functions working with <type>double precision</type> data are mostly
   implemented on top of the host system's C library; accuracy and behavior in
   boundary cases may therefore vary depending on the host system.
576
  </para>
577

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
   <indexterm>
    <primary>abs</primary>
   </indexterm>
   <indexterm>
    <primary>cbrt</primary>
   </indexterm>
   <indexterm>
    <primary>ceiling</primary>
   </indexterm>
   <indexterm>
    <primary>degrees</primary>
   </indexterm>
   <indexterm>
    <primary>exp</primary>
   </indexterm>
   <indexterm>
    <primary>floor</primary>
   </indexterm>
   <indexterm>
    <primary>ln</primary>
   </indexterm>
   <indexterm>
    <primary>log</primary>
   </indexterm>
   <indexterm>
    <primary>mod</primary>
   </indexterm>
   <indexterm>
    <primary>&pi;</primary>
   </indexterm>
   <indexterm>
    <primary>power</primary>
   </indexterm>
   <indexterm>
    <primary>radians</primary>
   </indexterm>
   <indexterm>
    <primary>random</primary>
   </indexterm>
   <indexterm>
    <primary>round</primary>
   </indexterm>
   <indexterm>
    <primary>setseed</primary>
   </indexterm>
   <indexterm>
    <primary>sign</primary>
   </indexterm>
   <indexterm>
    <primary>sqrt</primary>
   </indexterm>
   <indexterm>
    <primary>trunc</primary>
   </indexterm>
   <indexterm>
    <primary>width_bucket</primary>
   </indexterm>

636
   <table id="functions-math-func-table">
637 638 639 640 641 642 643 644 645 646 647 648 649 650
    <title>Mathematical Functions</title>
    <tgroup cols="5">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Return Type</entry>
       <entry>Description</entry>
       <entry>Example</entry>
       <entry>Result</entry>
      </row>
     </thead>

     <tbody>
      <row>
651
       <entry><literal><function>abs</>(<replaceable>x</replaceable>)</literal></entry>
652
       <entry>(same as <replaceable>x</>)</entry>
653 654
       <entry>absolute value</entry>
       <entry><literal>abs(-17.4)</literal></entry>
655
       <entry><literal>17.4</literal></entry>
656 657 658
      </row>

      <row>
659
       <entry><literal><function>cbrt</function>(<type>dp</type>)</literal></entry>
660 661 662
       <entry><type>dp</type></entry>
       <entry>cube root</entry>
       <entry><literal>cbrt(27.0)</literal></entry>
663
       <entry><literal>3</literal></entry>
664 665 666
      </row>

      <row>
667
       <entry><literal><function>ceil</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
668
       <entry>(same as input)</entry>
669 670
       <entry>smallest integer not less than argument</entry>
       <entry><literal>ceil(-42.8)</literal></entry>
671
       <entry><literal>-42</literal></entry>
672 673
      </row>

674 675 676 677 678 679 680 681
      <row>
       <entry><literal><function>ceiling</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
       <entry>(same as input)</entry>
       <entry>smallest integer not less than argument (alias for <function>ceil</function>)</entry>
       <entry><literal>ceiling(-95.3)</literal></entry>
       <entry><literal>-95</literal></entry>
      </row>

682
      <row>
683
       <entry><literal><function>degrees</function>(<type>dp</type>)</literal></entry>
684 685 686
       <entry><type>dp</type></entry>
       <entry>radians to degrees</entry>
       <entry><literal>degrees(0.5)</literal></entry>
687
       <entry><literal>28.6478897565412</literal></entry>
688 689 690
      </row>

      <row>
691
       <entry><literal><function>exp</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
692
       <entry>(same as input)</entry>
693 694
       <entry>exponential</entry>
       <entry><literal>exp(1.0)</literal></entry>
695
       <entry><literal>2.71828182845905</literal></entry>
696 697 698
      </row>

      <row>
699
       <entry><literal><function>floor</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
700
       <entry>(same as input)</entry>
701 702
       <entry>largest integer not greater than argument</entry>
       <entry><literal>floor(-42.8)</literal></entry>
703
       <entry><literal>-43</literal></entry>
704 705 706
      </row>

      <row>
707
       <entry><literal><function>ln</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
708
       <entry>(same as input)</entry>
709 710
       <entry>natural logarithm</entry>
       <entry><literal>ln(2.0)</literal></entry>
711
       <entry><literal>0.693147180559945</literal></entry>
712 713 714
      </row>

      <row>
715
       <entry><literal><function>log</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
716
       <entry>(same as input)</entry>
717 718
       <entry>base 10 logarithm</entry>
       <entry><literal>log(100.0)</literal></entry>
719
       <entry><literal>2</literal></entry>
720 721 722
      </row>

      <row>
723 724
       <entry><literal><function>log</function>(<parameter>b</parameter> <type>numeric</type>,
        <parameter>x</parameter> <type>numeric</type>)</literal></entry>
725 726 727
       <entry><type>numeric</type></entry>
       <entry>logarithm to base <parameter>b</parameter></entry>
       <entry><literal>log(2.0, 64.0)</literal></entry>
728
       <entry><literal>6.0000000000</literal></entry>
729 730 731
      </row>

      <row>
732 733
       <entry><literal><function>mod</function>(<parameter>y</parameter>,
        <parameter>x</parameter>)</literal></entry>
734 735 736
       <entry>(same as argument types)</entry>
       <entry>remainder of <parameter>y</parameter>/<parameter>x</parameter></entry>
       <entry><literal>mod(9,4)</literal></entry>
737
       <entry><literal>1</literal></entry>
738 739 740
      </row>

      <row>
741
       <entry><literal><function>pi</function>()</literal></entry>
742
       <entry><type>dp</type></entry>
743
       <entry><quote>&pi;</quote> constant</entry>
744
       <entry><literal>pi()</literal></entry>
745
       <entry><literal>3.14159265358979</literal></entry>
746 747 748
      </row>

      <row>
749
       <entry><literal><function>power</function>(<parameter>a</parameter> <type>dp</type>,
750
        <parameter>b</parameter> <type>dp</type>)</literal></entry>
751
       <entry><type>dp</type></entry>
752
       <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
753
       <entry><literal>power(9.0, 3.0)</literal></entry>
754
       <entry><literal>729</literal></entry>
755 756
      </row>

757
      <row>
758
       <entry><literal><function>power</function>(<parameter>a</parameter> <type>numeric</type>,
759
        <parameter>b</parameter> <type>numeric</type>)</literal></entry>
760
       <entry><type>numeric</type></entry>
761
       <entry><parameter>a</> raised to the power of <parameter>b</parameter></entry>
762
       <entry><literal>power(9.0, 3.0)</literal></entry>
763
       <entry><literal>729</literal></entry>
764 765
      </row>

766
      <row>
767
       <entry><literal><function>radians</function>(<type>dp</type>)</literal></entry>
768 769 770
       <entry><type>dp</type></entry>
       <entry>degrees to radians</entry>
       <entry><literal>radians(45.0)</literal></entry>
771
       <entry><literal>0.785398163397448</literal></entry>
772 773 774
      </row>

      <row>
775
       <entry><literal><function>random</function>()</literal></entry>
776
       <entry><type>dp</type></entry>
777
       <entry>random value between 0.0 and 1.0</entry>
778 779 780 781 782
       <entry><literal>random()</literal></entry>
       <entry></entry>
      </row>

      <row>
783
       <entry><literal><function>round</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
784
       <entry>(same as input)</entry>
785 786
       <entry>round to nearest integer</entry>
       <entry><literal>round(42.4)</literal></entry>
787
       <entry><literal>42</literal></entry>
788 789 790
      </row>

      <row>
791
       <entry><literal><function>round</function>(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</literal></entry>
792 793 794
       <entry><type>numeric</type></entry>
       <entry>round to <parameter>s</parameter> decimal places</entry>
       <entry><literal>round(42.4382, 2)</literal></entry>
795
       <entry><literal>42.44</literal></entry>
796
      </row>
797 798

      <row>
799
       <entry><literal><function>setseed</function>(<type>dp</type>)</literal></entry>
800
       <entry><type>int</type></entry>
801
       <entry>set seed for subsequent <literal>random()</literal> calls</entry>
802
       <entry><literal>setseed(0.54823)</literal></entry>
803
       <entry><literal>1177314959</literal></entry>
804 805
      </row>

806
      <row>
807
       <entry><literal><function>sign</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
808
       <entry>(same as input)</entry>
809 810
       <entry>sign of the argument (-1, 0, +1)</entry>
       <entry><literal>sign(-8.4)</literal></entry>
811
       <entry><literal>-1</literal></entry>
812
      </row>
P
Peter Eisentraut 已提交
813

814
      <row>
815
       <entry><literal><function>sqrt</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
816
       <entry>(same as input)</entry>
817 818
       <entry>square root</entry>
       <entry><literal>sqrt(2.0)</literal></entry>
819
       <entry><literal>1.4142135623731</literal></entry>
820
      </row>
821

822
      <row>
823
       <entry><literal><function>trunc</function>(<type>dp</type> or <type>numeric</type>)</literal></entry>
824
       <entry>(same as input)</entry>
825 826
       <entry>truncate toward zero</entry>
       <entry><literal>trunc(42.8)</literal></entry>
827
       <entry><literal>42</literal></entry>
828
      </row>
829

830
      <row>
831
       <entry><literal><function>trunc</function>(<parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>int</type>)</literal></entry>
832 833 834
       <entry><type>numeric</type></entry>
       <entry>truncate to <parameter>s</parameter> decimal places</entry>
       <entry><literal>trunc(42.4382, 2)</literal></entry>
835
       <entry><literal>42.43</literal></entry>
836
      </row>
837

838
      <row>
839 840
       <entry><literal><function>width_bucket</function>(<parameter>op</parameter> <type>numeric</type>, <parameter>b1</parameter> <type>numeric</type>, <parameter>b2</parameter> <type>numeric</type>, <parameter>count</parameter> <type>int</type>)</literal></entry>
       <entry><type>int</type></entry>
841 842 843 844 845 846 847
       <entry>return the bucket to which <parameter>operand</> would
       be assigned in an equidepth histogram with <parameter>count</>
       buckets, an upper bound of <parameter>b1</>, and a lower bound
       of <parameter>b2</></entry>
       <entry><literal>width_bucket(5.35, 0.024, 10.06, 5)</literal></entry>
       <entry><literal>3</literal></entry>
      </row>
848 849 850
     </tbody>
    </tgroup>
   </table>
851

852 853 854
  <para>
   Finally, <xref linkend="functions-math-trig-table"> shows the
   available trigonometric functions.  All trigonometric functions
855
   take arguments and return values of type <type>double
856 857
   precision</type>.
  </para>
858

859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
   <indexterm>
    <primary>acos</primary>
   </indexterm>
   <indexterm>
    <primary>asin</primary>
   </indexterm>
   <indexterm>
    <primary>atan</primary>
   </indexterm>
   <indexterm>
    <primary>atan2</primary>
   </indexterm>
   <indexterm>
    <primary>cos</primary>
   </indexterm>
   <indexterm>
    <primary>cot</primary>
   </indexterm>
   <indexterm>
    <primary>sin</primary>
   </indexterm>
   <indexterm>
    <primary>tan</primary>
   </indexterm>

884
   <table id="functions-math-trig-table">
885
    <title>Trigonometric Functions</title>
886

887 888 889 890 891 892 893
    <tgroup cols="2">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Description</entry>
      </row>
     </thead>
894

895 896
     <tbody>
      <row>
897
       <entry><literal><function>acos</function>(<replaceable>x</replaceable>)</literal></entry>
898 899
       <entry>inverse cosine</entry>
      </row>
900

901
      <row>
902
       <entry><literal><function>asin</function>(<replaceable>x</replaceable>)</literal></entry>
903 904
       <entry>inverse sine</entry>
      </row>
905

906
      <row>
907
       <entry><literal><function>atan</function>(<replaceable>x</replaceable>)</literal></entry>
908 909
       <entry>inverse tangent</entry>
      </row>
910

911
      <row>
912 913
       <entry><literal><function>atan2</function>(<replaceable>x</replaceable>,
        <replaceable>y</replaceable>)</literal></entry>
914
       <entry>inverse tangent of
915
        <literal><replaceable>x</replaceable>/<replaceable>y</replaceable></literal></entry>
916
      </row>
917

918
      <row>
919
       <entry><literal><function>cos</function>(<replaceable>x</replaceable>)</literal></entry>
920 921
       <entry>cosine</entry>
      </row>
922

923
      <row>
924
       <entry><literal><function>cot</function>(<replaceable>x</replaceable>)</literal></entry>
925 926
       <entry>cotangent</entry>
      </row>
927

928
      <row>
929
       <entry><literal><function>sin</function>(<replaceable>x</replaceable>)</literal></entry>
930 931
       <entry>sine</entry>
      </row>
932

933
      <row>
934
       <entry><literal><function>tan</function>(<replaceable>x</replaceable>)</literal></entry>
935 936 937 938 939
       <entry>tangent</entry>
      </row>
     </tbody>
    </tgroup>
   </table>
940

941
  </sect1>
942 943


944 945
  <sect1 id="functions-string">
   <title>String Functions and Operators</title>
946

947 948 949
   <para>
    This section describes functions and operators for examining and
    manipulating string values.  Strings in this context include values
950 951
    of all the types <type>character</type>, <type>character
     varying</type>, and <type>text</type>.  Unless otherwise noted, all
952 953
    of the functions listed below work on all of these types, but be
    wary of potential effects of the automatic padding when using the
954
    <type>character</type> type.  Generally, the functions described
955 956
    here also work on data of non-string types by converting that data
    to a string representation first.  Some functions also exist
957
    natively for the bit-string types.
958
   </para>
959

960 961
   <para>
    <acronym>SQL</acronym> defines some string functions with a special syntax where
962
    certain key words rather than commas are used to separate the
963 964 965 966
    arguments.  Details are in <xref linkend="functions-string-sql">.
    These functions are also implemented using the regular syntax for
    function invocation.  (See <xref linkend="functions-string-other">.)
   </para>
967

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
   <indexterm>
    <primary>bit_length</primary>
   </indexterm>
   <indexterm>
    <primary>char_length</primary>
   </indexterm>
   <indexterm>
    <primary>convert</primary>
   </indexterm>
   <indexterm>
    <primary>lower</primary>
   </indexterm>
   <indexterm>
    <primary>octet_length</primary>
   </indexterm>
   <indexterm>
    <primary>overlay</primary>
   </indexterm>
   <indexterm>
    <primary>position</primary>
   </indexterm>
   <indexterm>
    <primary>substring</primary>
   </indexterm>
   <indexterm>
    <primary>trim</primary>
   </indexterm>
   <indexterm>
    <primary>upper</primary>
   </indexterm>

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
   <table id="functions-string-sql">
    <title><acronym>SQL</acronym> String Functions and Operators</title>
    <tgroup cols="5">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Return Type</entry>
       <entry>Description</entry>
       <entry>Example</entry>
       <entry>Result</entry>  
      </row>
     </thead>
1011

1012 1013
     <tbody>
      <row>
1014 1015
       <entry><literal><parameter>string</parameter> <literal>||</literal>
        <parameter>string</parameter></literal></entry>
1016 1017
       <entry> <type>text</type> </entry>
       <entry>
1018
        String concatenation
1019
        <indexterm>
P
Peter Eisentraut 已提交
1020
         <primary>character string</primary>
1021 1022 1023
         <secondary>concatenation</secondary>
        </indexterm>
       </entry>
1024
       <entry><literal>'Post' || 'greSQL'</literal></entry>
1025 1026
       <entry><literal>PostgreSQL</literal></entry>
      </row>
1027

1028
      <row>
1029
       <entry><literal><function>bit_length</function>(<parameter>string</parameter>)</literal></entry>
1030
       <entry><type>int</type></entry>
1031
       <entry>Number of bits in string</entry>
1032 1033 1034
       <entry><literal>bit_length('jose')</literal></entry>
       <entry><literal>32</literal></entry>
      </row>
P
Peter Eisentraut 已提交
1035

1036
      <row>
1037
       <entry><literal><function>char_length</function>(<parameter>string</parameter>)</literal> or <literal><function>character_length</function>(<parameter>string</parameter>)</literal></entry>
1038
       <entry><type>int</type></entry>
1039
       <entry>
1040
        Number of characters in string
1041
        <indexterm>
P
Peter Eisentraut 已提交
1042
         <primary>character string</primary>
1043 1044 1045 1046
         <secondary>length</secondary>
        </indexterm>
        <indexterm>
         <primary>length</primary>
P
Peter Eisentraut 已提交
1047
         <secondary sortas="character string">of a character string</secondary>
1048
         <see>character string, length</see>
1049 1050 1051 1052 1053
        </indexterm>
       </entry>
       <entry><literal>char_length('jose')</literal></entry>
       <entry><literal>4</literal></entry>
      </row>
1054

T
Tatsuo Ishii 已提交
1055
      <row>
1056 1057
       <entry><literal><function>convert</function>(<parameter>string</parameter>
       using <parameter>conversion_name</parameter>)</literal></entry>
T
Tatsuo Ishii 已提交
1058
       <entry><type>text</type></entry>
1059 1060 1061 1062 1063 1064 1065
       <entry>
        Change encoding using specified conversion name.  Conversions
        can be defined by <command>CREATE CONVERSION</command>.  Also
        there are some pre-defined conversion names. See <xref
        linkend="conversion-names"> for available conversion
        names.
       </entry>
1066 1067
       <entry><literal>convert('PostgreSQL' using iso_8859_1_to_utf8)</literal></entry>
       <entry><literal>'PostgreSQL'</literal> in UTF8 (Unicode, 8-bit) encoding</entry>
T
Tatsuo Ishii 已提交
1068 1069
      </row>

1070
      <row>
1071
       <entry><literal><function>lower</function>(<parameter>string</parameter>)</literal></entry>
1072
       <entry><type>text</type></entry>
1073
       <entry>Convert string to lower case</entry>
1074 1075 1076
       <entry><literal>lower('TOM')</literal></entry>
       <entry><literal>tom</literal></entry>
      </row>
1077

1078
      <row>
1079
       <entry><literal><function>octet_length</function>(<parameter>string</parameter>)</literal></entry>
1080
       <entry><type>int</type></entry>
1081
       <entry>Number of bytes in string</entry>
1082 1083 1084
       <entry><literal>octet_length('jose')</literal></entry>
       <entry><literal>4</literal></entry>
      </row>
1085

1086
      <row>
1087
       <entry><literal><function>overlay</function>(<parameter>string</parameter> placing <parameter>string</parameter> from <type>int</type> <optional>for <type>int</type></optional>)</literal></entry>
1088 1089
       <entry><type>text</type></entry>
       <entry>
1090
        Replace substring
1091 1092 1093 1094
       </entry>
       <entry><literal>overlay('Txxxxas' placing 'hom' from 2 for 4)</literal></entry>
       <entry><literal>Thomas</literal></entry>
      </row>
1095

1096
      <row>
1097
       <entry><literal><function>position</function>(<parameter>substring</parameter> in <parameter>string</parameter>)</literal></entry>
1098
       <entry><type>int</type></entry>
1099
       <entry>Location of specified substring</entry>
1100 1101 1102
       <entry><literal>position('om' in 'Thomas')</literal></entry>
       <entry><literal>3</literal></entry>
      </row>
1103

1104
      <row>
1105
       <entry><literal><function>substring</function>(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</literal></entry>
1106 1107
       <entry><type>text</type></entry>
       <entry>
1108
        Extract substring
1109 1110 1111 1112
       </entry>
       <entry><literal>substring('Thomas' from 2 for 3)</literal></entry>
       <entry><literal>hom</literal></entry>
      </row>
1113

1114
      <row>
1115
       <entry><literal><function>substring</function>(<parameter>string</parameter> from <replaceable>pattern</replaceable>)</literal></entry>
1116 1117
       <entry><type>text</type></entry>
       <entry>
1118
        Extract substring matching POSIX regular expression
1119
       </entry>
1120
       <entry><literal>substring('Thomas' from '...$')</literal></entry>
1121 1122
       <entry><literal>mas</literal></entry>
      </row>
1123

1124
      <row>
1125
       <entry><literal><function>substring</function>(<parameter>string</parameter> from <replaceable>pattern</replaceable> for <replaceable>escape</replaceable>)</literal></entry>
1126 1127
       <entry><type>text</type></entry>
       <entry>
1128 1129
        Extract substring matching <acronym>SQL</acronym> regular
        expression
1130 1131 1132 1133 1134
       </entry>
       <entry><literal>substring('Thomas' from '%#"o_a#"_' for '#')</literal></entry>
       <entry><literal>oma</literal></entry>
      </row>

1135 1136
      <row>
       <entry>
1137
        <literal><function>trim</function>(<optional>leading | trailing | both</optional>
1138
        <optional><parameter>characters</parameter></optional> from
1139
        <parameter>string</parameter>)</literal>
1140 1141 1142
       </entry>
       <entry><type>text</type></entry>
       <entry>
1143
        Remove the longest string containing only the
1144
        <parameter>characters</parameter> (a space by default) from the
1145
        start/end/both ends of the <parameter>string</parameter>
1146 1147 1148 1149
       </entry>
       <entry><literal>trim(both 'x' from 'xTomxx')</literal></entry>
       <entry><literal>Tom</literal></entry>
      </row>
1150

1151
      <row>
1152
       <entry><literal><function>upper</function>(<parameter>string</parameter>)</literal></entry>
1153
       <entry><type>text</type></entry>
1154
       <entry>Convert string to uppercase</entry>
1155 1156 1157 1158 1159 1160
       <entry><literal>upper('tom')</literal></entry>
       <entry><literal>TOM</literal></entry>
      </row>
     </tbody>
    </tgroup>
   </table>
1161

1162 1163
   <para>
    Additional string manipulation functions are available and are
1164 1165
    listed in <xref linkend="functions-string-other">.  Some of them are used internally to implement the
    <acronym>SQL</acronym>-standard string functions listed in <xref linkend="functions-string-sql">.
1166 1167
   </para>

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
   <indexterm>
    <primary>ascii</primary>
   </indexterm>
   <indexterm>
    <primary>btrim</primary>
   </indexterm>
   <indexterm>
    <primary>chr</primary>
   </indexterm>
   <indexterm>
    <primary>decode</primary>
   </indexterm>
   <indexterm>
    <primary>encode</primary>
   </indexterm>
   <indexterm>
    <primary>initcap</primary>
   </indexterm>
   <indexterm>
    <primary>lpad</primary>
   </indexterm>
   <indexterm>
    <primary>ltrim</primary>
   </indexterm>
   <indexterm>
    <primary>md5</primary>
   </indexterm>
   <indexterm>
    <primary>pg_client_encoding</primary>
   </indexterm>
   <indexterm>
    <primary>quote_ident</primary>
   </indexterm>
   <indexterm>
    <primary>quote_literal</primary>
   </indexterm>
   <indexterm>
    <primary>repeat</primary>
   </indexterm>
   <indexterm>
    <primary>replace</primary>
   </indexterm>
   <indexterm>
    <primary>rpad</primary>
   </indexterm>
   <indexterm>
    <primary>rtrim</primary>
   </indexterm>
   <indexterm>
    <primary>split_part</primary>
   </indexterm>
   <indexterm>
    <primary>strpos</primary>
   </indexterm>
   <indexterm>
    <primary>substr</primary>
   </indexterm>
   <indexterm>
    <primary>to_ascii</primary>
   </indexterm>
   <indexterm>
    <primary>to_hex</primary>
   </indexterm>
   <indexterm>
    <primary>translate</primary>
   </indexterm>

1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
   <table id="functions-string-other">
    <title>Other String Functions</title>
    <tgroup cols="5">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Return Type</entry>
       <entry>Description</entry>
       <entry>Example</entry>
       <entry>Result</entry>
      </row>
     </thead>

     <tbody>
      <row>
1250
       <entry><literal><function>ascii</function>(<type>text</type>)</literal></entry>
1251
       <entry><type>int</type></entry>
1252
       <entry><acronym>ASCII</acronym> code of the first character of the argument</entry>
1253 1254 1255 1256 1257
       <entry><literal>ascii('x')</literal></entry>
       <entry><literal>120</literal></entry>
      </row>

      <row>
1258 1259
       <entry><literal><function>btrim</function>(<parameter>string</parameter> <type>text</type>
       <optional>, <parameter>characters</parameter> <type>text</type></optional>)</literal></entry>
1260 1261
       <entry><type>text</type></entry>
       <entry>
1262
        Remove the longest string consisting only of characters
B
Bruce Momjian 已提交
1263
        in <parameter>characters</parameter> (a space by default)
1264
        from the start and end of <parameter>string</parameter>
1265
       </entry>
1266
       <entry><literal>btrim('xyxtrimyyx', 'xy')</literal></entry>
1267 1268 1269 1270
       <entry><literal>trim</literal></entry>
      </row>

      <row>
1271
       <entry><literal><function>chr</function>(<type>int</type>)</literal></entry>
1272
       <entry><type>text</type></entry>
1273
       <entry>Character with the given <acronym>ASCII</acronym> code</entry>
1274 1275 1276 1277 1278 1279
       <entry><literal>chr(65)</literal></entry>
       <entry><literal>A</literal></entry>
      </row>

      <row>
       <entry>
1280
        <literal><function>convert</function>(<parameter>string</parameter>
1281 1282
        <type>text</type>,
        <optional><parameter>src_encoding</parameter> <type>name</type>,</optional>
1283
        <parameter>dest_encoding</parameter> <type>name</type>)</literal>
1284 1285 1286
       </entry>
       <entry><type>text</type></entry>
       <entry>
1287
        Convert string to <parameter>dest_encoding</parameter>.
1288 1289 1290 1291 1292
        The original encoding is specified by
        <parameter>src_encoding</parameter>.  If
        <parameter>src_encoding</parameter> is omitted, database
        encoding is assumed.
       </entry>
1293 1294
       <entry><literal>convert( 'text_in_utf8', 'UTF8', 'LATIN1')</literal></entry>
       <entry><literal>text_in_utf8</literal> represented in ISO 8859-1 encoding</entry>
1295 1296 1297 1298
      </row>

      <row>
       <entry>
1299 1300
        <literal><function>decode</function>(<parameter>string</parameter> <type>text</type>,
        <parameter>type</parameter> <type>text</type>)</literal>
1301 1302 1303
       </entry>
       <entry><type>bytea</type></entry>
       <entry>
1304
        Decode binary data from <parameter>string</parameter> previously 
1305
        encoded with <function>encode</>.  Parameter type is same as in <function>encode</>.
1306 1307 1308 1309 1310 1311 1312
       </entry>
       <entry><literal>decode('MTIzAAE=', 'base64')</literal></entry>
       <entry><literal>123\000\001</literal></entry>
      </row>       

      <row>
       <entry>
1313 1314
        <literal><function>encode</function>(<parameter>data</parameter> <type>bytea</type>,
        <parameter>type</parameter> <type>text</type>)</literal>
1315 1316 1317
       </entry>
       <entry><type>text</type></entry>
       <entry>
1318
        Encode binary data to <acronym>ASCII</acronym>-only representation.  Supported
1319
        types are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
1320
       </entry>
1321
       <entry><literal>encode( '123\\000\\001', 'base64')</literal></entry>
1322 1323 1324 1325
       <entry><literal>MTIzAAE=</literal></entry>
      </row>       

      <row>
1326
       <entry><literal><function>initcap</function>(<type>text</type>)</literal></entry>
1327
       <entry><type>text</type></entry>
1328 1329 1330 1331 1332 1333
       <entry>
        Convert the first letter of each word to uppercase and the
        rest to lowercase. Words are sequences of alphanumeric
        characters separated by non-alphanumeric characters.
       </entry>
       <entry><literal>initcap('hi THOMAS')</literal></entry>
1334 1335 1336 1337
       <entry><literal>Hi Thomas</literal></entry>
      </row>

      <row>
1338
       <entry><literal><function>length</function>(<parameter>string</parameter> <type>text</type>)</literal></entry>
1339
       <entry><type>int</type></entry>
1340
       <entry>
1341
        Number of characters in <parameter>string</parameter>
1342 1343 1344 1345 1346 1347 1348
       </entry>
       <entry><literal>length('jose')</literal></entry>
       <entry><literal>4</literal></entry>
      </row>

      <row>
       <entry>
1349
        <literal><function>lpad</function>(<parameter>string</parameter> <type>text</type>,
1350
        <parameter>length</parameter> <type>int</type>
1351
        <optional>, <parameter>fill</parameter> <type>text</type></optional>)</literal>
1352
       </entry>
1353
       <entry><type>text</type></entry>
1354
       <entry>
1355
        Fill up the <parameter>string</parameter> to length
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
        <parameter>length</parameter> by prepending the characters
        <parameter>fill</parameter> (a space by default).  If the
        <parameter>string</parameter> is already longer than
        <parameter>length</parameter> then it is truncated (on the
        right).
       </entry>
       <entry><literal>lpad('hi', 5, 'xy')</literal></entry>
       <entry><literal>xyxhi</literal></entry>
      </row>

      <row>
1367 1368 1369
       <entry><literal><function>ltrim</function>(<parameter>string</parameter> <type>text</type>
        <optional>, <parameter>characters</parameter> <type>text</type></optional>)</literal>
       </entry>
1370 1371
       <entry><type>text</type></entry>
       <entry>
1372
        Remove the longest string containing only characters from
1373
        <parameter>characters</parameter> (a space by default) from the start of
1374
        <parameter>string</parameter>
1375
       </entry>
1376
       <entry><literal>ltrim('zzzytrim', 'xyz')</literal></entry>
1377 1378 1379
       <entry><literal>trim</literal></entry>
      </row>

1380
      <row>
1381
       <entry><literal><function>md5</function>(<parameter>string</parameter> <type>text</type>)</literal></entry>
1382 1383
       <entry><type>text</type></entry>
       <entry>
1384
        Calculates the MD5 hash of <parameter>string</parameter>,
1385
        returning the result in hexadecimal
1386 1387
       </entry>
       <entry><literal>md5('abc')</literal></entry>
1388
       <entry><literal>900150983cd24fb0 d6963f7d28e17f72</literal></entry>
1389 1390
      </row>

1391
      <row>
1392
       <entry><literal><function>pg_client_encoding</function>()</literal></entry>
1393 1394
       <entry><type>name</type></entry>
       <entry>
1395
        Current client encoding name
1396 1397 1398 1399 1400 1401
       </entry>
       <entry><literal>pg_client_encoding()</literal></entry>
       <entry><literal>SQL_ASCII</literal></entry>
      </row>

      <row>
1402
       <entry><literal><function>quote_ident</function>(<parameter>string</parameter> text)</literal></entry>
1403 1404
       <entry><type>text</type></entry>
       <entry>
1405
        Return the given string suitably quoted to be used as an identifier
1406 1407 1408 1409
        in an <acronym>SQL</acronym> statement string.
        Quotes are added only if necessary (i.e., if the string contains
        non-identifier characters or would be case-folded).
        Embedded quotes are properly doubled.
1410
       </entry>
1411 1412
       <entry><literal>quote_ident('Foo bar')</literal></entry>
       <entry><literal>"Foo bar"</literal></entry>
1413 1414 1415
      </row>

      <row>
1416
       <entry><literal><function>quote_literal</function>(<parameter>string</parameter> text)</literal></entry>
1417 1418
       <entry><type>text</type></entry>
       <entry>
1419
        Return the given string suitably quoted to be used as a string literal
1420 1421
        in an <acronym>SQL</acronym> statement string.
        Embedded quotes and backslashes are properly doubled.
1422
       </entry>
1423
       <entry><literal>quote_literal( 'O\'Reilly')</literal></entry>
1424 1425 1426 1427
       <entry><literal>'O''Reilly'</literal></entry>
      </row>

      <row>
1428
       <entry><literal><function>repeat</function>(<parameter>string</parameter> <type>text</type>, <parameter>number</parameter> <type>int</type>)</literal></entry>
1429
       <entry><type>text</type></entry>
1430 1431
       <entry>Repeat <parameter>string</parameter> the specified
       <parameter>number</parameter> of times</entry>
1432 1433 1434 1435 1436
       <entry><literal>repeat('Pg', 4)</literal></entry>
       <entry><literal>PgPgPgPg</literal></entry>
      </row>

      <row>
1437
       <entry><literal><function>replace</function>(<parameter>string</parameter> <type>text</type>,
1438
       <parameter>from</parameter> <type>text</type>,
1439
       <parameter>to</parameter> <type>text</type>)</literal></entry>
1440 1441
       <entry><type>text</type></entry>
       <entry>Replace all occurrences in <parameter>string</parameter> of substring
1442
        <parameter>from</parameter> with substring <parameter>to</parameter>
1443
       </entry>
1444
       <entry><literal>replace( 'abcdefabcdef', 'cd', 'XX')</literal></entry>
1445 1446 1447 1448 1449
       <entry><literal>abXXefabXXef</literal></entry>
      </row>

      <row>
       <entry>
1450
        <literal><function>rpad</function>(<parameter>string</parameter> <type>text</type>,
1451
        <parameter>length</parameter> <type>int</type>
1452
        <optional>, <parameter>fill</parameter> <type>text</type></optional>)</literal>
1453 1454 1455
       </entry>
       <entry><type>text</type></entry>
       <entry>
1456
        Fill up the <parameter>string</parameter> to length
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
        <parameter>length</parameter> by appending the characters
        <parameter>fill</parameter> (a space by default).  If the
        <parameter>string</parameter> is already longer than
        <parameter>length</parameter> then it is truncated.
       </entry>
       <entry><literal>rpad('hi', 5, 'xy')</literal></entry>
       <entry><literal>hixyx</literal></entry>
      </row>

      <row>
1467 1468 1469
       <entry><literal><function>rtrim</function>(<parameter>string</parameter> <type>text</type>
        <optional>, <parameter>characters</parameter> <type>text</type></optional>)</literal>
       </entry>
1470 1471
       <entry><type>text</type></entry>
       <entry>
1472
        Remove the longest string containing only characters from
1473
        <parameter>characters</parameter> (a space by default) from the end of
1474
        <parameter>string</parameter>
1475
       </entry>
1476
       <entry><literal>rtrim('trimxxxx', 'x')</literal></entry>
1477 1478 1479 1480
       <entry><literal>trim</literal></entry>
      </row>

      <row>
1481
       <entry><literal><function>split_part</function>(<parameter>string</parameter> <type>text</type>,
1482
       <parameter>delimiter</parameter> <type>text</type>,
1483
       <parameter>field</parameter> <type>int</type>)</literal></entry>
1484 1485
       <entry><type>text</type></entry>
       <entry>Split <parameter>string</parameter> on <parameter>delimiter</parameter>
1486
        and return the given field (counting from one)
1487
       </entry>
1488
       <entry><literal>split_part('abc~@~def~@~ghi', '~@~', 2)</literal></entry>
1489 1490 1491 1492
       <entry><literal>def</literal></entry>
      </row>

      <row>
1493
       <entry><literal><function>strpos</function>(<parameter>string</parameter>, <parameter>substring</parameter>)</literal></entry>
1494
       <entry><type>int</type></entry>
1495
       <entry>
1496
        Location of specified substring (same as
1497 1498 1499 1500
        <literal>position(<parameter>substring</parameter> in
         <parameter>string</parameter>)</literal>, but note the reversed
        argument order)
       </entry>
1501
       <entry><literal>strpos('high', 'ig')</literal></entry>
1502 1503 1504 1505
       <entry><literal>2</literal></entry>
      </row>

      <row>
1506
       <entry><literal><function>substr</function>(<parameter>string</parameter>, <parameter>from</parameter> <optional>, <parameter>count</parameter></optional>)</literal></entry>
1507 1508
       <entry><type>text</type></entry>
       <entry>
1509
        Extract substring (same as
1510 1511 1512 1513 1514 1515 1516
        <literal>substring(<parameter>string</parameter> from <parameter>from</parameter> for <parameter>count</parameter>)</literal>)
       </entry>
       <entry><literal>substr('alphabet', 3, 2)</literal></entry>
       <entry><literal>ph</literal></entry>
      </row>

      <row>
1517 1518
       <entry><literal><function>to_ascii</function>(<type>text</type>
        <optional>, <parameter>encoding</parameter></optional>)</literal></entry>
1519
       <entry><type>text</type></entry>
1520 1521

       <entry>
N
Neil Conway 已提交
1522
       Convert <parameter>text</parameter> to <acronym>ASCII</acronym> from another encoding
1523 1524 1525
       <footnote>
        <para>
         The <function>to_ascii</function> function supports conversion from
T
Tom Lane 已提交
1526 1527
         <literal>LATIN1</>, <literal>LATIN2</>, <literal>LATIN9</>,
         and <literal>WIN1250</> encodings only.
1528 1529 1530 1531
        </para>
       </footnote>
       </entry>

1532 1533 1534 1535 1536
       <entry><literal>to_ascii('Karel')</literal></entry>
       <entry><literal>Karel</literal></entry>
      </row>

      <row>
1537
       <entry><literal><function>to_hex</function>(<parameter>number</parameter> <type>int</type>
1538
       or <type>bigint</type>)</literal></entry>
1539 1540
       <entry><type>text</type></entry>
       <entry>Convert <parameter>number</parameter> to its equivalent hexadecimal
1541
        representation
1542
       </entry>
1543 1544
       <entry><literal>to_hex(2147483647)</literal></entry>
       <entry><literal>7fffffff</literal></entry>
1545 1546 1547 1548
      </row>

      <row>
       <entry>
1549
        <literal><function>translate</function>(<parameter>string</parameter>
1550 1551
        <type>text</type>,
        <parameter>from</parameter> <type>text</type>,
1552
        <parameter>to</parameter> <type>text</type>)</literal>
1553 1554 1555 1556 1557 1558
       </entry>
       <entry><type>text</type></entry>
       <entry>
        Any character in <parameter>string</parameter> that matches a
        character in the <parameter>from</parameter> set is replaced by
        the corresponding character in the <parameter>to</parameter>
1559
        set
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
       </entry>
       <entry><literal>translate('12345', '14', 'ax')</literal></entry>
       <entry><literal>a23x5</literal></entry>
      </row>       
      
     </tbody>
    </tgroup>
   </table>


T
Tatsuo Ishii 已提交
1570
   <table id="conversion-names">
1571
    <title>Built-in Conversions</title>
T
Tatsuo Ishii 已提交
1572 1573 1574
    <tgroup cols="3">
     <thead>
      <row>
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
       <entry>Conversion Name
        <footnote>
         <para>
          The conversion names follow a standard naming scheme: The
          official name of the source encoding with all
          non-alphanumeric characters replaced by underscores followed
          by <literal>_to_</literal> followed by the equally processed
          destination encoding name. Therefore the names might deviate
          from the customary encoding names.
         </para>
        </footnote>
       </entry>
       <entry>Source Encoding</entry>
       <entry>Destination Encoding</entry>
T
Tatsuo Ishii 已提交
1589 1590
      </row>
     </thead>
1591

T
Tatsuo Ishii 已提交
1592 1593
     <tbody>
      <row>
P
Peter Eisentraut 已提交
1594 1595 1596
       <entry><literal>ascii_to_mic</literal></entry>
       <entry><literal>SQL_ASCII</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
1597 1598 1599
      </row>

      <row>
1600
       <entry><literal>ascii_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1601
       <entry><literal>SQL_ASCII</literal></entry>
1602
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1603 1604 1605
      </row>

      <row>
P
Peter Eisentraut 已提交
1606 1607 1608
       <entry><literal>big5_to_euc_tw</literal></entry>
       <entry><literal>BIG5</literal></entry>
       <entry><literal>EUC_TW</literal></entry>
T
Tatsuo Ishii 已提交
1609 1610 1611
      </row>

      <row>
P
Peter Eisentraut 已提交
1612 1613 1614
       <entry><literal>big5_to_mic</literal></entry>
       <entry><literal>BIG5</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
T
Tatsuo Ishii 已提交
1615 1616 1617
      </row>

      <row>
1618
       <entry><literal>big5_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1619
       <entry><literal>BIG5</literal></entry>
1620
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1621 1622 1623
      </row>

      <row>
P
Peter Eisentraut 已提交
1624 1625 1626
       <entry><literal>euc_cn_to_mic</literal></entry>
       <entry><literal>EUC_CN</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
1627 1628 1629
      </row>

      <row>
1630
       <entry><literal>euc_cn_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1631
       <entry><literal>EUC_CN</literal></entry>
1632
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1633 1634 1635
      </row>

      <row>
P
Peter Eisentraut 已提交
1636 1637 1638
       <entry><literal>euc_jp_to_mic</literal></entry>
       <entry><literal>EUC_JP</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
T
Tatsuo Ishii 已提交
1639 1640 1641
      </row>

      <row>
P
Peter Eisentraut 已提交
1642 1643 1644
       <entry><literal>euc_jp_to_sjis</literal></entry>
       <entry><literal>EUC_JP</literal></entry>
       <entry><literal>SJIS</literal></entry>
T
Tatsuo Ishii 已提交
1645 1646 1647
      </row>

      <row>
1648
       <entry><literal>euc_jp_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1649
       <entry><literal>EUC_JP</literal></entry>
1650
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1651 1652 1653
      </row>

      <row>
P
Peter Eisentraut 已提交
1654 1655 1656
       <entry><literal>euc_kr_to_mic</literal></entry>
       <entry><literal>EUC_KR</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
1657 1658 1659
      </row>

      <row>
1660
       <entry><literal>euc_kr_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1661
       <entry><literal>EUC_KR</literal></entry>
1662
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1663 1664 1665
      </row>

      <row>
P
Peter Eisentraut 已提交
1666 1667 1668
       <entry><literal>euc_tw_to_big5</literal></entry>
       <entry><literal>EUC_TW</literal></entry>
       <entry><literal>BIG5</literal></entry>
T
Tatsuo Ishii 已提交
1669 1670 1671
      </row>

      <row>
P
Peter Eisentraut 已提交
1672 1673 1674
       <entry><literal>euc_tw_to_mic</literal></entry>
       <entry><literal>EUC_TW</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
T
Tatsuo Ishii 已提交
1675 1676 1677
      </row>

      <row>
1678
       <entry><literal>euc_tw_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1679
       <entry><literal>EUC_TW</literal></entry>
1680
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1681 1682 1683
      </row>

      <row>
1684
       <entry><literal>gb18030_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1685
       <entry><literal>GB18030</literal></entry>
1686
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1687 1688 1689
      </row>

      <row>
1690
       <entry><literal>gbk_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1691
       <entry><literal>GBK</literal></entry>
1692
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1693 1694 1695
      </row>

      <row>
1696
       <entry><literal>iso_8859_10_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1697
       <entry><literal>LATIN6</literal></entry>
1698
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1699 1700 1701
      </row>

      <row>
1702
       <entry><literal>iso_8859_13_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1703
       <entry><literal>LATIN7</literal></entry>
1704
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1705 1706 1707
      </row>

      <row>
1708
       <entry><literal>iso_8859_14_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1709
       <entry><literal>LATIN8</literal></entry>
1710
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1711 1712 1713
      </row>

      <row>
1714
       <entry><literal>iso_8859_15_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1715
       <entry><literal>LATIN9</literal></entry>
1716
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1717 1718 1719
      </row>

      <row>
1720
       <entry><literal>iso_8859_16_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1721
       <entry><literal>LATIN10</literal></entry>
1722
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1723 1724 1725
      </row>

      <row>
P
Peter Eisentraut 已提交
1726 1727 1728
       <entry><literal>iso_8859_1_to_mic</literal></entry>
       <entry><literal>LATIN1</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
1729 1730 1731
      </row>

      <row>
1732
       <entry><literal>iso_8859_1_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1733
       <entry><literal>LATIN1</literal></entry>
1734
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1735 1736 1737
      </row>

      <row>
P
Peter Eisentraut 已提交
1738 1739 1740
       <entry><literal>iso_8859_2_to_mic</literal></entry>
       <entry><literal>LATIN2</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
1741 1742 1743
      </row>

      <row>
1744
       <entry><literal>iso_8859_2_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1745
       <entry><literal>LATIN2</literal></entry>
1746
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1747 1748 1749
      </row>

      <row>
1750
       <entry><literal>iso_8859_2_to_windows_1250</literal></entry>
P
Peter Eisentraut 已提交
1751 1752
       <entry><literal>LATIN2</literal></entry>
       <entry><literal>WIN1250</literal></entry>
1753 1754 1755
      </row>

      <row>
P
Peter Eisentraut 已提交
1756 1757 1758
       <entry><literal>iso_8859_3_to_mic</literal></entry>
       <entry><literal>LATIN3</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
1759 1760 1761
      </row>

      <row>
1762
       <entry><literal>iso_8859_3_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1763
       <entry><literal>LATIN3</literal></entry>
1764
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1765 1766 1767
      </row>

      <row>
P
Peter Eisentraut 已提交
1768 1769 1770
       <entry><literal>iso_8859_4_to_mic</literal></entry>
       <entry><literal>LATIN4</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
1771 1772 1773
      </row>

      <row>
1774
       <entry><literal>iso_8859_4_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1775
       <entry><literal>LATIN4</literal></entry>
1776
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1777 1778 1779
      </row>

      <row>
1780
       <entry><literal>iso_8859_5_to_koi8_r</literal></entry>
P
Peter Eisentraut 已提交
1781 1782
       <entry><literal>ISO_8859_5</literal></entry>
       <entry><literal>KOI8</literal></entry>
1783 1784 1785
      </row>

      <row>
P
Peter Eisentraut 已提交
1786 1787 1788
       <entry><literal>iso_8859_5_to_mic</literal></entry>
       <entry><literal>ISO_8859_5</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
1789 1790 1791
      </row>

      <row>
1792
       <entry><literal>iso_8859_5_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1793
       <entry><literal>ISO_8859_5</literal></entry>
1794
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1795 1796 1797
      </row>

      <row>
1798
       <entry><literal>iso_8859_5_to_windows_1251</literal></entry>
P
Peter Eisentraut 已提交
1799
       <entry><literal>ISO_8859_5</literal></entry>
1800
       <entry><literal>WIN1251</literal></entry>
1801 1802 1803
      </row>

      <row>
1804
       <entry><literal>iso_8859_5_to_windows_866</literal></entry>
P
Peter Eisentraut 已提交
1805
       <entry><literal>ISO_8859_5</literal></entry>
1806
       <entry><literal>WIN866</literal></entry>
1807 1808 1809
      </row>

      <row>
1810
       <entry><literal>iso_8859_6_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1811
       <entry><literal>ISO_8859_6</literal></entry>
1812
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1813 1814 1815
      </row>

      <row>
1816
       <entry><literal>iso_8859_7_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1817
       <entry><literal>ISO_8859_7</literal></entry>
1818
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1819 1820 1821
      </row>

      <row>
1822
       <entry><literal>iso_8859_8_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1823
       <entry><literal>ISO_8859_8</literal></entry>
1824
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1825 1826 1827
      </row>

      <row>
1828
       <entry><literal>iso_8859_9_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1829
       <entry><literal>LATIN5</literal></entry>
1830
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1831 1832 1833
      </row>

      <row>
1834
       <entry><literal>johab_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1835
       <entry><literal>JOHAB</literal></entry>
1836
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1837 1838
      </row>

1839
      <row>
1840
       <entry><literal>koi8_r_to_iso_8859_5</literal></entry>
P
Peter Eisentraut 已提交
1841 1842
       <entry><literal>KOI8</literal></entry>
       <entry><literal>ISO_8859_5</literal></entry>
1843 1844 1845
      </row>

      <row>
1846
       <entry><literal>koi8_r_to_mic</literal></entry>
P
Peter Eisentraut 已提交
1847 1848
       <entry><literal>KOI8</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
1849 1850 1851
      </row>

      <row>
1852
       <entry><literal>koi8_r_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1853
       <entry><literal>KOI8</literal></entry>
1854
       <entry><literal>UTF8</literal></entry>
1855 1856 1857
      </row>

      <row>
1858
       <entry><literal>koi8_r_to_windows_1251</literal></entry>
P
Peter Eisentraut 已提交
1859
       <entry><literal>KOI8</literal></entry>
1860
       <entry><literal>WIN1251</literal></entry>
1861 1862 1863
      </row>

      <row>
1864
       <entry><literal>koi8_r_to_windows_866</literal></entry>
P
Peter Eisentraut 已提交
1865
       <entry><literal>KOI8</literal></entry>
1866
       <entry><literal>WIN866</literal></entry>
1867 1868 1869
      </row>

      <row>
P
Peter Eisentraut 已提交
1870 1871 1872
       <entry><literal>mic_to_ascii</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>SQL_ASCII</literal></entry>
1873 1874
      </row>

T
Tatsuo Ishii 已提交
1875
      <row>
P
Peter Eisentraut 已提交
1876 1877 1878
       <entry><literal>mic_to_big5</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>BIG5</literal></entry>
T
Tatsuo Ishii 已提交
1879 1880
      </row>

1881
      <row>
P
Peter Eisentraut 已提交
1882 1883 1884
       <entry><literal>mic_to_euc_cn</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>EUC_CN</literal></entry>
1885 1886
      </row>

T
Tatsuo Ishii 已提交
1887
      <row>
P
Peter Eisentraut 已提交
1888 1889 1890
       <entry><literal>mic_to_euc_jp</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>EUC_JP</literal></entry>
T
Tatsuo Ishii 已提交
1891 1892
      </row>

1893
      <row>
P
Peter Eisentraut 已提交
1894 1895 1896
       <entry><literal>mic_to_euc_kr</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>EUC_KR</literal></entry>
1897 1898
      </row>

T
Tatsuo Ishii 已提交
1899
      <row>
P
Peter Eisentraut 已提交
1900 1901 1902
       <entry><literal>mic_to_euc_tw</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>EUC_TW</literal></entry>
T
Tatsuo Ishii 已提交
1903 1904
      </row>

1905
      <row>
P
Peter Eisentraut 已提交
1906 1907 1908
       <entry><literal>mic_to_iso_8859_1</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>LATIN1</literal></entry>
1909 1910 1911
      </row>

      <row>
P
Peter Eisentraut 已提交
1912 1913 1914
       <entry><literal>mic_to_iso_8859_2</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>LATIN2</literal></entry>
1915 1916 1917
      </row>

      <row>
P
Peter Eisentraut 已提交
1918 1919 1920
       <entry><literal>mic_to_iso_8859_3</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>LATIN3</literal></entry>
1921 1922 1923
      </row>

      <row>
P
Peter Eisentraut 已提交
1924 1925 1926
       <entry><literal>mic_to_iso_8859_4</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>LATIN4</literal></entry>
1927 1928 1929
      </row>

      <row>
P
Peter Eisentraut 已提交
1930 1931 1932
       <entry><literal>mic_to_iso_8859_5</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>ISO_8859_5</literal></entry>
1933 1934 1935
      </row>

      <row>
1936
       <entry><literal>mic_to_koi8_r</literal></entry>
P
Peter Eisentraut 已提交
1937 1938
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>KOI8</literal></entry>
1939 1940
      </row>

T
Tatsuo Ishii 已提交
1941
      <row>
P
Peter Eisentraut 已提交
1942 1943 1944
       <entry><literal>mic_to_sjis</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>SJIS</literal></entry>
T
Tatsuo Ishii 已提交
1945 1946
      </row>

1947
      <row>
1948
       <entry><literal>mic_to_windows_1250</literal></entry>
P
Peter Eisentraut 已提交
1949 1950
       <entry><literal>MULE_INTERNAL</literal></entry>
       <entry><literal>WIN1250</literal></entry>
1951 1952 1953
      </row>

      <row>
1954
       <entry><literal>mic_to_windows_1251</literal></entry>
P
Peter Eisentraut 已提交
1955
       <entry><literal>MULE_INTERNAL</literal></entry>
1956
       <entry><literal>WIN1251</literal></entry>
1957 1958 1959
      </row>

      <row>
1960
       <entry><literal>mic_to_windows_866</literal></entry>
P
Peter Eisentraut 已提交
1961
       <entry><literal>MULE_INTERNAL</literal></entry>
1962
       <entry><literal>WIN866</literal></entry>
1963 1964
      </row>

T
Tatsuo Ishii 已提交
1965
      <row>
P
Peter Eisentraut 已提交
1966 1967 1968
       <entry><literal>sjis_to_euc_jp</literal></entry>
       <entry><literal>SJIS</literal></entry>
       <entry><literal>EUC_JP</literal></entry>
T
Tatsuo Ishii 已提交
1969 1970 1971
      </row>

      <row>
P
Peter Eisentraut 已提交
1972 1973 1974
       <entry><literal>sjis_to_mic</literal></entry>
       <entry><literal>SJIS</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
T
Tatsuo Ishii 已提交
1975 1976 1977
      </row>

      <row>
1978
       <entry><literal>sjis_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1979
       <entry><literal>SJIS</literal></entry>
1980
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1981 1982 1983
      </row>

      <row>
1984 1985 1986
       <entry><literal>tcvn_to_utf8</literal></entry>
       <entry><literal>WIN1258</literal></entry>
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1987 1988 1989
      </row>

      <row>
1990
       <entry><literal>uhc_to_utf8</literal></entry>
P
Peter Eisentraut 已提交
1991
       <entry><literal>UHC</literal></entry>
1992
       <entry><literal>UTF8</literal></entry>
T
Tatsuo Ishii 已提交
1993 1994 1995
      </row>

      <row>
1996 1997
       <entry><literal>utf8_to_ascii</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
1998
       <entry><literal>SQL_ASCII</literal></entry>
T
Tatsuo Ishii 已提交
1999 2000 2001
      </row>

      <row>
2002 2003
       <entry><literal>utf8_to_big5</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2004
       <entry><literal>BIG5</literal></entry>
T
Tatsuo Ishii 已提交
2005 2006 2007
      </row>

      <row>
2008 2009
       <entry><literal>utf8_to_euc_cn</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2010
       <entry><literal>EUC_CN</literal></entry>
T
Tatsuo Ishii 已提交
2011 2012 2013
      </row>

      <row>
2014 2015
       <entry><literal>utf8_to_euc_jp</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2016
       <entry><literal>EUC_JP</literal></entry>
T
Tatsuo Ishii 已提交
2017 2018 2019
      </row>

      <row>
2020 2021
       <entry><literal>utf8_to_euc_kr</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2022
       <entry><literal>EUC_KR</literal></entry>
T
Tatsuo Ishii 已提交
2023 2024 2025
      </row>

      <row>
2026 2027
       <entry><literal>utf8_to_euc_tw</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2028
       <entry><literal>EUC_TW</literal></entry>
T
Tatsuo Ishii 已提交
2029 2030 2031
      </row>

      <row>
2032 2033
       <entry><literal>utf8_to_gb18030</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2034
       <entry><literal>GB18030</literal></entry>
T
Tatsuo Ishii 已提交
2035 2036 2037
      </row>

      <row>
2038 2039
       <entry><literal>utf8_to_gbk</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2040
       <entry><literal>GBK</literal></entry>
T
Tatsuo Ishii 已提交
2041 2042 2043
      </row>

      <row>
2044 2045
       <entry><literal>utf8_to_iso_8859_1</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2046
       <entry><literal>LATIN1</literal></entry>
T
Tatsuo Ishii 已提交
2047 2048 2049
      </row>

      <row>
2050 2051
       <entry><literal>utf8_to_iso_8859_10</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2052
       <entry><literal>LATIN6</literal></entry>
T
Tatsuo Ishii 已提交
2053 2054 2055
      </row>

      <row>
2056 2057
       <entry><literal>utf8_to_iso_8859_13</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2058
       <entry><literal>LATIN7</literal></entry>
T
Tatsuo Ishii 已提交
2059 2060 2061
      </row>

      <row>
2062 2063
       <entry><literal>utf8_to_iso_8859_14</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2064
       <entry><literal>LATIN8</literal></entry>
T
Tatsuo Ishii 已提交
2065 2066 2067
      </row>

      <row>
2068 2069
       <entry><literal>utf8_to_iso_8859_15</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2070
       <entry><literal>LATIN9</literal></entry>
T
Tatsuo Ishii 已提交
2071 2072 2073
      </row>

      <row>
2074 2075
       <entry><literal>utf8_to_iso_8859_16</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2076
       <entry><literal>LATIN10</literal></entry>
T
Tatsuo Ishii 已提交
2077 2078 2079
      </row>

      <row>
2080 2081
       <entry><literal>utf8_to_iso_8859_2</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2082
       <entry><literal>LATIN2</literal></entry>
T
Tatsuo Ishii 已提交
2083 2084 2085
      </row>

      <row>
2086 2087
       <entry><literal>utf8_to_iso_8859_3</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2088
       <entry><literal>LATIN3</literal></entry>
T
Tatsuo Ishii 已提交
2089 2090 2091
      </row>

      <row>
2092 2093
       <entry><literal>utf8_to_iso_8859_4</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2094
       <entry><literal>LATIN4</literal></entry>
T
Tatsuo Ishii 已提交
2095 2096 2097
      </row>

      <row>
2098 2099
       <entry><literal>utf8_to_iso_8859_5</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2100
       <entry><literal>ISO_8859_5</literal></entry>
T
Tatsuo Ishii 已提交
2101 2102 2103
      </row>

      <row>
2104 2105
       <entry><literal>utf8_to_iso_8859_6</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2106
       <entry><literal>ISO_8859_6</literal></entry>
T
Tatsuo Ishii 已提交
2107 2108 2109
      </row>

      <row>
2110 2111
       <entry><literal>utf8_to_iso_8859_7</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2112
       <entry><literal>ISO_8859_7</literal></entry>
T
Tatsuo Ishii 已提交
2113 2114 2115
      </row>

      <row>
2116 2117
       <entry><literal>utf8_to_iso_8859_8</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2118
       <entry><literal>ISO_8859_8</literal></entry>
T
Tatsuo Ishii 已提交
2119 2120 2121
      </row>

      <row>
2122 2123
       <entry><literal>utf8_to_iso_8859_9</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2124
       <entry><literal>LATIN5</literal></entry>
T
Tatsuo Ishii 已提交
2125 2126 2127
      </row>

      <row>
2128 2129
       <entry><literal>utf8_to_johab</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2130
       <entry><literal>JOHAB</literal></entry>
T
Tatsuo Ishii 已提交
2131 2132 2133
      </row>

      <row>
2134 2135
       <entry><literal>utf8_to_koi8_r</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2136
       <entry><literal>KOI8</literal></entry>
2137 2138 2139
      </row>

      <row>
2140 2141
       <entry><literal>utf8_to_sjis</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2142
       <entry><literal>SJIS</literal></entry>
T
Tatsuo Ishii 已提交
2143 2144 2145
      </row>

      <row>
2146 2147 2148
       <entry><literal>utf8_to_tcvn</literal></entry>
       <entry><literal>UTF8</literal></entry>
       <entry><literal>WIN1258</literal></entry>
T
Tatsuo Ishii 已提交
2149 2150 2151
      </row>

      <row>
2152 2153
       <entry><literal>utf8_to_uhc</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2154
       <entry><literal>UHC</literal></entry>
T
Tatsuo Ishii 已提交
2155 2156
      </row>

2157
      <row>
2158 2159
       <entry><literal>utf8_to_windows_1250</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2160
       <entry><literal>WIN1250</literal></entry>
2161 2162 2163
      </row>

      <row>
2164 2165 2166
       <entry><literal>utf8_to_windows_1251</literal></entry>
       <entry><literal>UTF8</literal></entry>
       <entry><literal>WIN1251</literal></entry>
2167 2168
      </row>

2169 2170 2171 2172 2173 2174
      <row>
       <entry><literal>utf8_to_windows_1252</literal></entry>
       <entry><literal>UTF8</literal></entry>
       <entry><literal>WIN1252</literal></entry>
      </row>

2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
      <row>
       <entry><literal>utf8_to_windows_1253</literal></entry>
       <entry><literal>UTF8</literal></entry>
       <entry><literal>WIN1253</literal></entry>
      </row>

      <row>
       <entry><literal>utf8_to_windows_1254</literal></entry>
       <entry><literal>UTF8</literal></entry>
       <entry><literal>WIN1254</literal></entry>
      </row>

      <row>
       <entry><literal>utf8_to_windows_1255</literal></entry>
       <entry><literal>UTF8</literal></entry>
       <entry><literal>WIN1255</literal></entry>
      </row>

2193
      <row>
2194 2195
       <entry><literal>utf8_to_windows_1256</literal></entry>
       <entry><literal>UTF8</literal></entry>
P
Peter Eisentraut 已提交
2196
       <entry><literal>WIN1256</literal></entry>
2197 2198
      </row>

2199 2200 2201 2202 2203 2204
      <row>
       <entry><literal>utf8_to_windows_1257</literal></entry>
       <entry><literal>UTF8</literal></entry>
       <entry><literal>WIN1257</literal></entry>
      </row>

2205
      <row>
2206 2207 2208
       <entry><literal>utf8_to_windows_866</literal></entry>
       <entry><literal>UTF8</literal></entry>
       <entry><literal>WIN866</literal></entry>
2209 2210 2211
      </row>

      <row>
2212 2213
       <entry><literal>utf8_to_windows_874</literal></entry>
       <entry><literal>UTF8</literal></entry>
2214
       <entry><literal>WIN874</literal></entry>
2215
      </row>
2216

2217
      <row>
2218
       <entry><literal>windows_1250_to_iso_8859_2</literal></entry>
2219 2220
       <entry><literal>WIN1250</literal></entry>
       <entry><literal>LATIN2</literal></entry>
2221
      </row>
2222

2223
      <row>
2224
       <entry><literal>windows_1250_to_mic</literal></entry>
2225 2226
       <entry><literal>WIN1250</literal></entry>
       <entry><literal>MULE_INTERNAL</literal></entry>
2227 2228 2229
      </row>

      <row>
2230
       <entry><literal>windows_1250_to_utf8</literal></entry>
2231
       <entry><literal>WIN1250</literal></entry>
2232
       <entry><literal>UTF8</literal></entry>
2233 2234
      </row>

2235
      <row>
2236
       <entry><literal>windows_1251_to_iso_8859_5</literal></entry>
2237
       <entry><literal>WIN1251</literal></entry>
2238
       <entry><literal>ISO_8859_5</literal></entry>
2239
      </row>
2240

2241
      <row>
2242
       <entry><literal>windows_1251_to_koi8_r</literal></entry>
2243
       <entry><literal>WIN1251</literal></entry>
2244
       <entry><literal>KOI8</literal></entry>
2245 2246
      </row>

2247
      <row>
2248
       <entry><literal>windows_1251_to_mic</literal></entry>
2249
       <entry><literal>WIN1251</literal></entry>
2250
       <entry><literal>MULE_INTERNAL</literal></entry>
2251
      </row>
2252

2253
      <row>
2254 2255 2256
       <entry><literal>windows_1251_to_utf8</literal></entry>
       <entry><literal>WIN1251</literal></entry>
       <entry><literal>UTF8</literal></entry>
2257
      </row>
2258

2259
      <row>
2260
       <entry><literal>windows_1251_to_windows_866</literal></entry>
2261 2262
       <entry><literal>WIN1251</literal></entry>
       <entry><literal>WIN866</literal></entry>
2263 2264
      </row>

2265 2266 2267 2268 2269 2270
      <row>
       <entry><literal>windows_1252_to_utf8</literal></entry>
       <entry><literal>WIN1252</literal></entry>
       <entry><literal>UTF8</literal></entry>
      </row>

2271
      <row>
2272
       <entry><literal>windows_1256_to_utf8</literal></entry>
2273
       <entry><literal>WIN1256</literal></entry>
2274
       <entry><literal>UTF8</literal></entry>
2275
      </row>
2276

2277
      <row>
2278
       <entry><literal>windows_866_to_iso_8859_5</literal></entry>
2279
       <entry><literal>WIN866</literal></entry>
2280
       <entry><literal>ISO_8859_5</literal></entry>
2281
      </row>
2282

2283
      <row>
2284
       <entry><literal>windows_866_to_koi8_r</literal></entry>
2285
       <entry><literal>WIN866</literal></entry>
2286
       <entry><literal>KOI8</literal></entry>
2287
      </row>
2288

2289
      <row>
2290
       <entry><literal>windows_866_to_mic</literal></entry>
2291
       <entry><literal>WIN866</literal></entry>
2292
       <entry><literal>MULE_INTERNAL</literal></entry>
2293 2294
      </row>

2295
      <row>
2296 2297 2298
       <entry><literal>windows_866_to_utf8</literal></entry>
       <entry><literal>WIN866</literal></entry>
       <entry><literal>UTF8</literal></entry>
2299 2300 2301
      </row>

      <row>
2302
       <entry><literal>windows_866_to_windows_1251</literal></entry>
2303
       <entry><literal>WIN866</literal></entry>
2304 2305 2306 2307
       <entry><literal>WIN</literal></entry>
      </row>

      <row>
2308
       <entry><literal>windows_874_to_utf8</literal></entry>
2309
       <entry><literal>WIN874</literal></entry>
2310
       <entry><literal>UTF8</literal></entry>
2311 2312
      </row>

2313 2314 2315
     </tbody>
    </tgroup>
   </table>
2316

2317
  </sect1>
2318

2319

2320 2321
  <sect1 id="functions-binarystring">
   <title>Binary String Functions and Operators</title>
2322

P
Peter Eisentraut 已提交
2323 2324 2325 2326 2327
   <indexterm zone="functions-binarystring">
    <primary>binary data</primary>
    <secondary>functions</secondary>
   </indexterm>

2328 2329
   <para>
    This section describes functions and operators for examining and
2330
    manipulating values of type <type>bytea</type>.
2331
   </para>
2332

2333 2334 2335
   <para>
    <acronym>SQL</acronym> defines some string functions with a
    special syntax where 
2336
    certain key words rather than commas are used to separate the
2337 2338 2339 2340 2341 2342
    arguments.  Details are in
    <xref linkend="functions-binarystring-sql">.
    Some functions are also implemented using the regular syntax for
    function invocation.
    (See <xref linkend="functions-binarystring-other">.)
   </para>
2343

2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
   <table id="functions-binarystring-sql">
    <title><acronym>SQL</acronym> Binary String Functions and Operators</title>
    <tgroup cols="5">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Return Type</entry>
       <entry>Description</entry>
       <entry>Example</entry>
       <entry>Result</entry>  
      </row>
     </thead>
2356

2357 2358
     <tbody>
      <row>
2359 2360
       <entry><literal><parameter>string</parameter> <literal>||</literal>
        <parameter>string</parameter></literal></entry>
2361 2362
       <entry> <type>bytea</type> </entry>
       <entry>
2363
        String concatenation
2364
        <indexterm>
P
Peter Eisentraut 已提交
2365
         <primary>binary string</primary>
2366 2367 2368
         <secondary>concatenation</secondary>
        </indexterm>
       </entry>
2369 2370
       <entry><literal>'\\\\Post'::bytea || '\\047gres\\000'::bytea</literal></entry>
       <entry><literal>\\Post'gres\000</literal></entry>
2371
      </row>
2372

2373
      <row>
2374
       <entry><literal><function>octet_length</function>(<parameter>string</parameter>)</literal></entry>
2375
       <entry><type>int</type></entry>
2376
       <entry>Number of bytes in binary string</entry>
2377
       <entry><literal>octet_length( 'jo\\000se'::bytea)</literal></entry>
2378 2379
       <entry><literal>5</literal></entry>
      </row>
2380

2381
      <row>
2382
       <entry><literal><function>position</function>(<parameter>substring</parameter> in <parameter>string</parameter>)</literal></entry>
2383
       <entry><type>int</type></entry>
2384
       <entry>Location of specified substring</entry>
2385 2386 2387
      <entry><literal>position('\\000om'::bytea in 'Th\\000omas'::bytea)</literal></entry>
       <entry><literal>3</literal></entry>
      </row>
2388

2389
      <row>
2390
       <entry><literal><function>substring</function>(<parameter>string</parameter> <optional>from <type>int</type></optional> <optional>for <type>int</type></optional>)</literal></entry>
2391 2392
       <entry><type>bytea</type></entry>
       <entry>
2393
        Extract substring
2394 2395 2396 2397 2398 2399 2400
        <indexterm>
         <primary>substring</primary>
        </indexterm>
       </entry>
       <entry><literal>substring('Th\\000omas'::bytea from 2 for 3)</literal></entry>
       <entry><literal>h\000o</literal></entry>
      </row>
2401

2402 2403
      <row>
       <entry>
2404 2405 2406
        <literal><function>trim</function>(<optional>both</optional>
        <parameter>bytes</parameter> from
        <parameter>string</parameter>)</literal>
2407 2408 2409
       </entry>
       <entry><type>bytea</type></entry>
       <entry>
2410 2411 2412
        Remove the longest string containing only the bytes in
        <parameter>bytes</parameter> from the start
        and end of <parameter>string</parameter>
2413 2414 2415 2416
       </entry>
       <entry><literal>trim('\\000'::bytea from '\\000Tom\\000'::bytea)</literal></entry>
       <entry><literal>Tom</literal></entry>
      </row>
2417 2418 2419

      <row>
       <entry><function>get_byte</function>(<parameter>string</parameter>, <parameter>offset</parameter>)</entry>
2420
       <entry><type>int</type></entry>
2421
       <entry>
2422
        Extract byte from string
2423 2424 2425 2426 2427 2428 2429 2430 2431
        <indexterm>
         <primary>get_byte</primary>
        </indexterm>
       </entry>
       <entry><literal>get_byte('Th\\000omas'::bytea, 4)</literal></entry>
       <entry><literal>109</literal></entry>
      </row>

      <row>
2432 2433
       <entry><function>set_byte</function>(<parameter>string</parameter>,
       <parameter>offset</parameter>, <parameter>newvalue</>)</entry>
2434 2435
       <entry><type>bytea</type></entry>
       <entry>
2436
        Set byte in string
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
        <indexterm>
         <primary>set_byte</primary>
        </indexterm>
       </entry>
       <entry><literal>set_byte('Th\\000omas'::bytea, 4, 64)</literal></entry>
       <entry><literal>Th\000o@as</literal></entry>
      </row>

      <row>
       <entry><function>get_bit</function>(<parameter>string</parameter>, <parameter>offset</parameter>)</entry>
2447
       <entry><type>int</type></entry>
2448
       <entry>
2449
        Extract bit from string
2450 2451 2452 2453 2454 2455 2456 2457 2458
        <indexterm>
         <primary>get_bit</primary>
        </indexterm>
       </entry>
       <entry><literal>get_bit('Th\\000omas'::bytea, 45)</literal></entry>
       <entry><literal>1</literal></entry>
      </row>

      <row>
2459 2460
       <entry><function>set_bit</function>(<parameter>string</parameter>,
       <parameter>offset</parameter>, <parameter>newvalue</>)</entry>
2461 2462
       <entry><type>bytea</type></entry>
       <entry>
2463
        Set bit in string
2464 2465 2466 2467 2468 2469 2470
        <indexterm>
         <primary>set_bit</primary>
        </indexterm>
       </entry>
       <entry><literal>set_bit('Th\\000omas'::bytea, 45, 0)</literal></entry>
       <entry><literal>Th\000omAs</literal></entry>
      </row>
2471 2472 2473
     </tbody>
    </tgroup>
   </table>
2474

2475
   <para>
2476 2477 2478 2479 2480
    Additional binary string manipulation functions are available and
    are listed in <xref linkend="functions-binarystring-other">.  Some
    of them are used internally to implement the
    <acronym>SQL</acronym>-standard string functions listed in <xref
    linkend="functions-binarystring-sql">.
2481
   </para>
2482

2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
   <table id="functions-binarystring-other">
    <title>Other Binary String Functions</title>
    <tgroup cols="5">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Return Type</entry>
       <entry>Description</entry>
       <entry>Example</entry>
       <entry>Result</entry>
      </row>
     </thead>
2495

2496 2497
     <tbody>
      <row>
2498
       <entry><literal><function>btrim</function>(<parameter>string</parameter>
N
Neil Conway 已提交
2499
        <type>bytea</type>, <parameter>bytes</parameter> <type>bytea</type>)</literal></entry>
2500 2501
       <entry><type>bytea</type></entry>
       <entry>
2502 2503
        Remove the longest string consisting only of bytes
        in <parameter>bytes</parameter> from the start and end of
2504
        <parameter>string</parameter>
2505
      </entry>
2506
      <entry><literal>btrim('\\000trim\\000'::bytea, '\\000'::bytea)</literal></entry>
2507 2508 2509 2510
      <entry><literal>trim</literal></entry>
     </row>

     <row>
2511
      <entry><literal><function>length</function>(<parameter>string</parameter>)</literal></entry>
2512
      <entry><type>int</type></entry>
2513
      <entry>
2514
       Length of binary string
2515
       <indexterm>
P
Peter Eisentraut 已提交
2516
        <primary>binary string</primary>
2517
        <secondary>length</secondary>
2518 2519 2520
       </indexterm>
       <indexterm>
        <primary>length</primary>
2521 2522
        <secondary sortas="binary string">of a binary string</secondary>
        <see>binary strings, length</see>
2523 2524
       </indexterm>
      </entry>
2525 2526
      <entry><literal>length('jo\\000se'::bytea)</literal></entry>
      <entry><literal>5</literal></entry>
2527 2528
     </row>

2529 2530 2531 2532 2533
     <row>
      <entry><literal><function>md5</function>(<parameter>string</parameter>)</literal></entry>
      <entry><type>text</type></entry>
      <entry>
       Calculates the MD5 hash of <parameter>string</parameter>,
2534
       returning the result in hexadecimal
2535 2536 2537 2538 2539
      </entry>
      <entry><literal>md5('Th\\000omas'::bytea)</literal></entry>
      <entry><literal>8ab2d3c9689aaf18 b4958c334c82d8b1</literal></entry>
     </row>

2540 2541
     <row>
      <entry>
2542 2543
       <literal><function>decode</function>(<parameter>string</parameter> <type>text</type>,
              <parameter>type</parameter> <type>text</type>)</literal>
2544
      </entry>
2545
      <entry><type>bytea</type></entry>
2546
      <entry>
2547 2548
       Decode binary string from <parameter>string</parameter> previously 
       encoded with <literal>encode</>.  Parameter type is same as in <literal>encode</>.
2549
      </entry>
2550
      <entry><literal>decode('123\\000456', 'escape')</literal></entry>
2551 2552 2553 2554 2555
      <entry><literal>123\000456</literal></entry>
     </row>       

     <row>
      <entry>
2556 2557
       <literal><function>encode</function>(<parameter>string</parameter> <type>bytea</type>,
              <parameter>type</parameter> <type>text</type>)</literal>
2558
      </entry>
2559
      <entry><type>text</type></entry>
2560
      <entry>
2561 2562
       Encode binary string to <acronym>ASCII</acronym>-only representation.  Supported
       types are: <literal>base64</>, <literal>hex</>, <literal>escape</>.
2563
      </entry>
2564
      <entry><literal>encode('123\\000456'::bytea, 'escape')</literal></entry>
2565
      <entry><literal>123\000456</literal></entry>
2566
     </row>
2567 2568 2569 2570 2571 2572 2573 2574

    </tbody>
   </tgroup>
  </table>

 </sect1>


2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
  <sect1 id="functions-bitstring">
   <title>Bit String Functions and Operators</title>

   <indexterm zone="functions-bitstring">
    <primary>bit strings</primary>
    <secondary>functions</secondary>
   </indexterm>

   <para>
    This section describes functions and operators for examining and
    manipulating bit strings, that is values of the types
    <type>bit</type> and <type>bit varying</type>.  Aside from the
    usual comparison operators, the operators
    shown in <xref linkend="functions-bit-string-op-table"> can be used.
    Bit string operands of <literal>&amp;</literal>, <literal>|</literal>,
    and <literal>#</literal> must be of equal length.  When bit
    shifting, the original length of the string is preserved, as shown
    in the examples.
   </para>

   <table id="functions-bit-string-op-table">
    <title>Bit String Operators</title>

    <tgroup cols="4">
     <thead>
      <row>
       <entry>Operator</entry>
       <entry>Description</entry>
       <entry>Example</entry>
       <entry>Result</entry>
      </row>
     </thead>

     <tbody>
      <row>
       <entry> <literal>||</literal> </entry>
       <entry>concatenation</entry>
       <entry><literal>B'10001' || B'011'</literal></entry>
       <entry><literal>10001011</literal></entry>
      </row>

      <row>
       <entry> <literal>&amp;</literal> </entry>
       <entry>bitwise AND</entry>
       <entry><literal>B'10001' &amp; B'01101'</literal></entry>
       <entry><literal>00001</literal></entry>
      </row>

      <row>
       <entry> <literal>|</literal> </entry>
       <entry>bitwise OR</entry>
       <entry><literal>B'10001' | B'01101'</literal></entry>
       <entry><literal>11101</literal></entry>
      </row>

      <row>
       <entry> <literal>#</literal> </entry>
       <entry>bitwise XOR</entry>
       <entry><literal>B'10001' # B'01101'</literal></entry>
       <entry><literal>11100</literal></entry>
      </row>

      <row>
       <entry> <literal>~</literal> </entry>
       <entry>bitwise NOT</entry>
       <entry><literal>~ B'10001'</literal></entry>
       <entry><literal>01110</literal></entry>
      </row>

      <row>
       <entry> <literal>&lt;&lt;</literal> </entry>
       <entry>bitwise shift left</entry>
       <entry><literal>B'10001' &lt;&lt; 3</literal></entry>
       <entry><literal>01000</literal></entry>
      </row>

      <row>
       <entry> <literal>&gt;&gt;</literal> </entry>
       <entry>bitwise shift right</entry>
       <entry><literal>B'10001' &gt;&gt; 2</literal></entry>
       <entry><literal>00100</literal></entry>
      </row>
     </tbody>
    </tgroup>
   </table>

   <para>
    The following <acronym>SQL</acronym>-standard functions work on bit
    strings as well as character strings:
    <literal><function>length</function></literal>,
    <literal><function>bit_length</function></literal>,
    <literal><function>octet_length</function></literal>,
    <literal><function>position</function></literal>,
    <literal><function>substring</function></literal>.
   </para>

   <para>
    In addition, it is possible to cast integral values to and from type
    <type>bit</>.
    Some examples:
<programlisting>
44::bit(10)                    <lineannotation>0000101100</lineannotation>
44::bit(3)                     <lineannotation>100</lineannotation>
cast(-44 as bit(12))           <lineannotation>111111010100</lineannotation>
'1110'::bit(4)::integer        <lineannotation>14</lineannotation>
</programlisting>
    Note that casting to just <quote>bit</> means casting to
    <literal>bit(1)</>, and so it will deliver only the least significant
    bit of the integer.
   </para>

    <note>
     <para>
2688
      Prior to <productname>PostgreSQL</productname> 8.0, casting an
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
      integer to <type>bit(n)</> would copy the leftmost <literal>n</>
      bits of the integer, whereas now it copies the rightmost <literal>n</>
      bits.  Also, casting an integer to a bit string width wider than
      the integer itself will sign-extend on the left.
     </para>
    </note>

  </sect1>


2699 2700 2701
 <sect1 id="functions-matching">
  <title>Pattern Matching</title>

2702 2703 2704 2705
  <indexterm zone="functions-matching">
   <primary>pattern matching</primary>
  </indexterm>

2706
   <para>
2707 2708 2709
    There are three separate approaches to pattern matching provided
    by <productname>PostgreSQL</productname>: the traditional
    <acronym>SQL</acronym> <function>LIKE</function> operator, the
2710 2711 2712
    more recent <function>SIMILAR TO</function> operator (added in
    SQL:1999), and <acronym>POSIX</acronym>-style regular
    expressions.
2713
    Additionally, a pattern matching function,
2714
    <function>substring</function>, is available, using either
T
Tom Lane 已提交
2715
    <function>SIMILAR TO</function>-style or POSIX-style regular
2716
    expressions.
2717 2718 2719 2720 2721 2722 2723 2724
   </para>

   <tip>
    <para>
     If you have pattern matching needs that go beyond this,
     consider writing a user-defined function in Perl or Tcl.
    </para>
   </tip>
2725

2726
  <sect2 id="functions-like">
2727
   <title><function>LIKE</function></title>
2728

2729
   <indexterm>
P
Peter Eisentraut 已提交
2730
    <primary>LIKE</primary>
2731 2732
   </indexterm>

2733
<synopsis>
2734 2735
<replaceable>string</replaceable> LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
<replaceable>string</replaceable> NOT LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
2736
</synopsis>
2737

2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
    <para>
     Every <replaceable>pattern</replaceable> defines a set of strings.
     The <function>LIKE</function> expression returns true if the
     <replaceable>string</replaceable> is contained in the set of
     strings represented by <replaceable>pattern</replaceable>.  (As
     expected, the <function>NOT LIKE</function> expression returns
     false if <function>LIKE</function> returns true, and vice versa.
     An equivalent expression is
     <literal>NOT (<replaceable>string</replaceable> LIKE
      <replaceable>pattern</replaceable>)</literal>.)
    </para>
2749 2750

    <para>
2751 2752 2753 2754 2755 2756 2757 2758 2759
     If <replaceable>pattern</replaceable> does not contain percent
     signs or underscore, then the pattern only represents the string
     itself; in that case <function>LIKE</function> acts like the
     equals operator.  An underscore (<literal>_</literal>) in
     <replaceable>pattern</replaceable> stands for (matches) any single
     character; a percent sign (<literal>%</literal>) matches any string
     of zero or more characters.
    </para>

2760 2761 2762
   <para>
    Some examples:
<programlisting>
2763 2764 2765 2766
'abc' LIKE 'abc'    <lineannotation>true</lineannotation>
'abc' LIKE 'a%'     <lineannotation>true</lineannotation>
'abc' LIKE '_b_'    <lineannotation>true</lineannotation>
'abc' LIKE 'c'      <lineannotation>false</lineannotation>
2767 2768 2769
</programlisting>
   </para>
   
T
Thomas G. Lockhart 已提交
2770
   <para>
2771
    <function>LIKE</function> pattern matches always cover the entire
T
Tom Lane 已提交
2772
    string.  To match a sequence anywhere within a string, the
2773
    pattern must therefore start and end with a percent sign.
T
Thomas G. Lockhart 已提交
2774
   </para>
2775 2776

   <para>
2777 2778 2779 2780
    To match a literal underscore or percent sign without matching
    other characters, the respective character in
    <replaceable>pattern</replaceable> must be 
    preceded by the escape character.  The default escape
2781
    character is the backslash but a different one may be selected by
2782 2783 2784 2785 2786 2787 2788
    using the <literal>ESCAPE</literal> clause.  To match the escape
    character itself, write two escape characters.
   </para>

   <para>
    Note that the backslash already has a special meaning in string
    literals, so to write a pattern constant that contains a backslash
2789
    you must write two backslashes in an SQL statement.  Thus, writing a pattern
2790
    that actually matches a literal backslash means writing four backslashes
2791 2792
    in the statement.  You can avoid this by selecting a different escape
    character with <literal>ESCAPE</literal>; then a backslash is not special
2793
    to <function>LIKE</function> anymore. (But it is still special to the string
2794 2795 2796 2797 2798
    literal parser, so you still need two of them.)
   </para>

   <para>
    It's also possible to select no escape character by writing
2799
    <literal>ESCAPE ''</literal>.  This effectively disables the
B
Bruce Momjian 已提交
2800 2801
    escape mechanism, which makes it impossible to turn off the
    special meaning of underscore and percent signs in the pattern.
2802
   </para>
2803 2804

   <para>
2805
    The key word <token>ILIKE</token> can be used instead of
T
Tom Lane 已提交
2806
    <token>LIKE</token> to make the match case-insensitive according
2807
    to the active locale.  This is not in the <acronym>SQL</acronym> standard but is a
2808
    <productname>PostgreSQL</productname> extension.
T
Thomas G. Lockhart 已提交
2809
   </para>
2810

2811 2812
   <para>
    The operator <literal>~~</literal> is equivalent to
2813 2814 2815
    <function>LIKE</function>, and <literal>~~*</literal> corresponds to
    <function>ILIKE</function>.  There are also
    <literal>!~~</literal> and <literal>!~~*</literal> operators that
2816
    represent <function>NOT LIKE</function> and <function>NOT
2817
    ILIKE</function>, respectively.  All of these operators are
2818
    <productname>PostgreSQL</productname>-specific.
2819 2820
   </para>
  </sect2>
2821

2822

2823 2824
  <sect2 id="functions-similarto-regexp">
   <title><function>SIMILAR TO</function> Regular Expressions</title>
2825

2826
   <indexterm>
P
Peter Eisentraut 已提交
2827
    <primary>regular expression</primary>
2828
    <!-- <seealso>pattern matching</seealso> breaks index build -->
2829 2830 2831
   </indexterm>

   <indexterm>
P
Peter Eisentraut 已提交
2832
    <primary>SIMILAR TO</primary>
2833 2834 2835 2836
   </indexterm>
   <indexterm>
    <primary>substring</primary>
   </indexterm>
2837 2838 2839
   <indexterm>
    <primary>regexp_replace</primary>
   </indexterm>
2840

2841
<synopsis>
2842 2843
<replaceable>string</replaceable> SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
<replaceable>string</replaceable> NOT SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
2844
</synopsis>
2845 2846

    <para>
2847 2848 2849 2850 2851 2852 2853
     The <function>SIMILAR TO</function> operator returns true or
     false depending on whether its pattern matches the given string.
     It is much like <function>LIKE</function>, except that it
     interprets the pattern using the SQL standard's definition of a
     regular expression.  SQL regular expressions are a curious cross
     between <function>LIKE</function> notation and common regular
     expression notation.
2854 2855 2856 2857 2858 2859 2860 2861 2862
    </para>

    <para>
     Like <function>LIKE</function>, the  <function>SIMILAR TO</function>
     operator succeeds only if its pattern matches the entire string;
     this is unlike common regular expression practice, wherein the pattern
     may match any part of the string.
     Also like
     <function>LIKE</function>, <function>SIMILAR TO</function> uses
2863 2864 2865
     <literal>_</> and <literal>%</> as wildcard characters denoting
     any single character and any string, respectively (these are
     comparable to <literal>.</> and <literal>.*</> in POSIX regular
2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
     expressions).
    </para>

    <para>
     In addition to these facilities borrowed from <function>LIKE</function>,
     <function>SIMILAR TO</function> supports these pattern-matching
     metacharacters borrowed from POSIX regular expressions:

    <itemizedlist>
     <listitem>
      <para>
       <literal>|</literal> denotes alternation (either of two alternatives).
      </para>
     </listitem>
     <listitem>
      <para>
       <literal>*</literal> denotes repetition of the previous item zero
       or more times.
      </para>
     </listitem>
     <listitem>
      <para>
       <literal>+</literal> denotes repetition of the previous item one
       or more times.
      </para>
     </listitem>
     <listitem>
      <para>
       Parentheses <literal>()</literal> may be used to group items into
       a single logical item.
      </para>
     </listitem>
     <listitem>
      <para>
       A bracket expression <literal>[...]</literal> specifies a character
       class, just as in POSIX regular expressions.
      </para>
     </listitem>
    </itemizedlist>

     Notice that bounded repetition (<literal>?</> and <literal>{...}</>)
2907
     are not provided, though they exist in POSIX.  Also, the dot (<literal>.</>)
2908 2909 2910 2911 2912 2913 2914 2915 2916
     is not a metacharacter.
    </para>

    <para>
     As with <function>LIKE</>, a backslash disables the special meaning
     of any of these metacharacters; or a different escape character can
     be specified with <literal>ESCAPE</>.
    </para>

2917 2918 2919
   <para>
    Some examples:
<programlisting>
2920 2921 2922 2923
'abc' SIMILAR TO 'abc'      <lineannotation>true</lineannotation>
'abc' SIMILAR TO 'a'        <lineannotation>false</lineannotation>
'abc' SIMILAR TO '%(b|d)%'  <lineannotation>true</lineannotation>
'abc' SIMILAR TO '(b|c)%'   <lineannotation>false</lineannotation>
2924 2925
</programlisting>
   </para>
2926 2927

    <para>
2928
     The <function>substring</> function with three parameters,
T
Tom Lane 已提交
2929
     <function>substring(<replaceable>string</replaceable> from
2930 2931
     <replaceable>pattern</replaceable> for
     <replaceable>escape-character</replaceable>)</function>, provides
2932
     extraction of a substring that matches an SQL
2933 2934 2935
     regular expression pattern.  As with <literal>SIMILAR TO</>, the
     specified pattern must match to the entire data string, else the
     function fails and returns null.  To indicate the part of the
2936 2937
     pattern that should be returned on success, the pattern must contain
     two occurrences of the escape character followed by a double quote
2938 2939
     (<literal>"</>).  The text matching the portion of the pattern
     between these markers is returned.
2940 2941
    </para>

2942 2943 2944
   <para>
    Some examples:
<programlisting>
2945 2946
substring('foobar' from '%#"o_b#"%' for '#')   <lineannotation>oob</lineannotation>
substring('foobar' from '#"o_b#"%' for '#')    <lineannotation>NULL</lineannotation>
2947 2948
</programlisting>
   </para>
2949 2950 2951 2952 2953 2954
  </sect2>

  <sect2 id="functions-posix-regexp">
   <title><acronym>POSIX</acronym> Regular Expressions</title>

   <indexterm zone="functions-posix-regexp">
P
Peter Eisentraut 已提交
2955
    <primary>regular expression</primary>
2956 2957 2958
    <seealso>pattern matching</seealso>
   </indexterm>

2959 2960 2961 2962 2963 2964
   <para>
    <xref linkend="functions-posix-table"> lists the available
    operators for pattern matching using POSIX regular expressions.
   </para>

   <table id="functions-posix-table">
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975
    <title>Regular Expression Match Operators</title>

    <tgroup cols="3">
     <thead>
      <row>
       <entry>Operator</entry>
       <entry>Description</entry>
       <entry>Example</entry>
      </row>
     </thead>

2976 2977 2978 2979 2980 2981
      <tbody>
       <row>
        <entry> <literal>~</literal> </entry>
        <entry>Matches regular expression, case sensitive</entry>
        <entry><literal>'thomas' ~ '.*thomas.*'</literal></entry>
       </row>
2982

2983 2984 2985 2986 2987
       <row>
        <entry> <literal>~*</literal> </entry>
        <entry>Matches regular expression, case insensitive</entry>
        <entry><literal>'thomas' ~* '.*Thomas.*'</literal></entry>
       </row>
2988

2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
       <row>
        <entry> <literal>!~</literal> </entry>
        <entry>Does not match regular expression, case sensitive</entry>
        <entry><literal>'thomas' !~ '.*Thomas.*'</literal></entry>
       </row>

       <row>
        <entry> <literal>!~*</literal> </entry>
        <entry>Does not match regular expression, case insensitive</entry>
        <entry><literal>'thomas' !~* '.*vadim.*'</literal></entry>
       </row>
      </tbody>
     </tgroup>
    </table>

    <para>
     <acronym>POSIX</acronym> regular expressions provide a more
     powerful means for 
3007 3008
     pattern matching than the <function>LIKE</function> and
     <function>SIMILAR TO</> operators.
3009 3010 3011 3012 3013 3014 3015 3016
     Many Unix tools such as <command>egrep</command>,
     <command>sed</command>, or <command>awk</command> use a pattern
     matching language that is similar to the one described here.
    </para>

    <para>
     A regular expression is a character sequence that is an
     abbreviated definition of a set of strings (a <firstterm>regular
3017
     set</firstterm>).  A string is said to match a regular expression
3018 3019 3020
     if it is a member of the regular set described by the regular
     expression.  As with <function>LIKE</function>, pattern characters
     match string characters exactly unless they are special characters
3021
     in the regular expression language &mdash; but regular expressions use
3022 3023 3024 3025 3026 3027
     different special characters than <function>LIKE</function> does.
     Unlike <function>LIKE</function> patterns, a
     regular expression is allowed to match anywhere within a string, unless
     the regular expression is explicitly anchored to the beginning or
     end of the string.
    </para>
3028

3029 3030 3031
   <para>
    Some examples:
<programlisting>
3032 3033 3034 3035
'abc' ~ 'abc'    <lineannotation>true</lineannotation>
'abc' ~ '^a'     <lineannotation>true</lineannotation>
'abc' ~ '(b|d)'  <lineannotation>true</lineannotation>
'abc' ~ '^(b|c)' <lineannotation>false</lineannotation>
3036 3037
</programlisting>
   </para>
3038 3039

    <para>
3040
     The <function>substring</> function with two parameters,
T
Tom Lane 已提交
3041
     <function>substring(<replaceable>string</replaceable> from
3042 3043
     <replaceable>pattern</replaceable>)</function>, provides extraction of a
     substring
3044
     that matches a POSIX regular expression pattern.  It returns null if
3045 3046 3047 3048
     there is no match, otherwise the portion of the text that matched the
     pattern.  But if the pattern contains any parentheses, the portion
     of the text that matched the first parenthesized subexpression (the
     one whose left parenthesis comes first) is
T
Tom Lane 已提交
3049
     returned.  You can put parentheses around the whole expression
3050
     if you want to use parentheses within it without triggering this
T
Tom Lane 已提交
3051 3052 3053
     exception.  If you need parentheses in the pattern before the
     subexpression you want to extract, see the non-capturing parentheses
     described below.
3054 3055
    </para>

3056 3057 3058
   <para>
    Some examples:
<programlisting>
3059 3060
substring('foobar' from 'o.b')     <lineannotation>oob</lineannotation>
substring('foobar' from 'o(.)b')   <lineannotation>o</lineannotation>
3061 3062
</programlisting>
   </para>
3063

3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
    <para>
     The <function>regexp_replace</> function provides substitution of
     new text for substrings that match POSIX regular expression patterns.
     It has the syntax
     <function>regexp_replace</function>(<replaceable>source</>,
     <replaceable>pattern</>, <replaceable>replacement</>
     <optional>, <replaceable>flags</> </optional>).
     The <replaceable>source</> string is returned unchanged if
     there is no match to the <replaceable>pattern</>.  If there is a
     match, the <replaceable>source</> string is returned with the
     <replaceable>replacement</> string substituted for the matching
     substring.  The <replaceable>replacement</> string can contain
     <literal>\</><replaceable>n</>, where <replaceable>n</> is <literal>1</>
     through <literal>9</>, to indicate that the source substring matching the
     <replaceable>n</>'th parenthesized subexpression of the pattern should be
     inserted, and it can contain <literal>\&amp;</> to indicate that the
     substring matching the entire pattern should be inserted.  Write
     <literal>\\</> if you need to put a literal backslash in the replacement
     text.  (As always, remember to double backslashes written in literal
     constant strings.)
     The <replaceable>flags</> parameter is an optional text
     string containing zero or more single-letter flags that change the
     function's behavior.  Flag <literal>i</> specifies case-insensitive
     matching, while flag <literal>g</> specifies replacement of each matching
     substring rather than only the first one.
    </para>

   <para>
    Some examples:
<programlisting>
regexp_replace('foobarbaz', 'b..', 'X')
                                   <lineannotation>fooXbaz</lineannotation>
regexp_replace('foobarbaz', 'b..', 'X', 'g')
                                   <lineannotation>fooXX</lineannotation>
regexp_replace('foobarbaz', 'b(..)', 'X\\1Y', 'g')
                                   <lineannotation>fooXarYXazY</lineannotation>
</programlisting>
   </para>

3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
   <para>
    <productname>PostgreSQL</productname>'s regular expressions are implemented
    using a package written by Henry Spencer.  Much of
    the description of regular expressions below is copied verbatim from his
    manual entry.
   </para>

<!-- derived from the re_syntax.n man page -->

   <sect3 id="posix-syntax-details">
    <title>Regular Expression Details</title>

T
Thomas G. Lockhart 已提交
3115
   <para>
P
Peter Eisentraut 已提交
3116
    Regular expressions (<acronym>RE</acronym>s), as defined in
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
    <acronym>POSIX</acronym> 1003.2, come in two forms:
    <firstterm>extended</> <acronym>RE</acronym>s or <acronym>ERE</>s
    (roughly those of <command>egrep</command>), and
    <firstterm>basic</> <acronym>RE</acronym>s or <acronym>BRE</>s
    (roughly those of <command>ed</command>).
    <productname>PostgreSQL</productname> supports both forms, and
    also implements some extensions
    that are not in the POSIX standard, but have become widely used anyway
    due to their availability in programming languages such as Perl and Tcl.
    <acronym>RE</acronym>s using these non-POSIX extensions are called
    <firstterm>advanced</> <acronym>RE</acronym>s or <acronym>ARE</>s
3128 3129 3130 3131 3132
    in this documentation.  AREs are almost an exact superset of EREs,
    but BREs have several notational incompatibilities (as well as being
    much more limited).
    We first describe the ARE and ERE forms, noting features that apply
    only to AREs, and then describe how BREs differ.
T
Thomas G. Lockhart 已提交
3133
   </para>
3134

3135 3136
   <note>
    <para>
3137 3138 3139 3140 3141 3142
     The form of regular expressions accepted by
     <productname>PostgreSQL</> can be chosen by setting the <xref
     linkend="guc-regex-flavor"> run-time parameter.  The usual
     setting is <literal>advanced</>, but one might choose
     <literal>extended</> for maximum backwards compatibility with
     pre-7.4 releases of <productname>PostgreSQL</>.
3143 3144 3145
    </para>
   </note>

T
Thomas G. Lockhart 已提交
3146
   <para>
3147
    A regular expression is defined as one or more
3148 3149 3150
    <firstterm>branches</firstterm>, separated by
    <literal>|</literal>.  It matches anything that matches one of the
    branches.
T
Thomas G. Lockhart 已提交
3151
   </para>
3152

3153
   <para>
3154 3155 3156 3157
    A branch is zero or more <firstterm>quantified atoms</> or
    <firstterm>constraints</>, concatenated.
    It matches a match for the first, followed by a match for the second, etc;
    an empty branch matches the empty string.
3158
   </para>
3159

B
Bruce Momjian 已提交
3160
   <para>
3161 3162 3163 3164 3165 3166 3167 3168
    A quantified atom is an <firstterm>atom</> possibly followed
    by a single <firstterm>quantifier</>.
    Without a quantifier, it matches a match for the atom.
    With a quantifier, it can match some number of matches of the atom.
    An <firstterm>atom</firstterm> can be any of the possibilities
    shown in <xref linkend="posix-atoms-table">.
    The possible quantifiers and their meanings are shown in
    <xref linkend="posix-quantifiers-table">.
B
Bruce Momjian 已提交
3169
   </para>
3170

3171
   <para>
3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252
    A <firstterm>constraint</> matches an empty string, but matches only when
    specific conditions are met.  A constraint can be used where an atom
    could be used, except it may not be followed by a quantifier.
    The simple constraints are shown in
    <xref linkend="posix-constraints-table">;
    some more constraints are described later.
   </para>


   <table id="posix-atoms-table">
    <title>Regular Expression Atoms</title>

    <tgroup cols="2">
     <thead>
      <row>
       <entry>Atom</entry>
       <entry>Description</entry>
      </row>
     </thead>

      <tbody>
       <row>
       <entry> <literal>(</><replaceable>re</><literal>)</> </entry>
       <entry> (where <replaceable>re</> is any regular expression)
       matches a match for
       <replaceable>re</>, with the match noted for possible reporting </entry>
       </row>

       <row>
       <entry> <literal>(?:</><replaceable>re</><literal>)</> </entry>
       <entry> as above, but the match is not noted for reporting
       (a <quote>non-capturing</> set of parentheses)
       (AREs only) </entry>
       </row>

       <row>
       <entry> <literal>.</> </entry>
       <entry> matches any single character </entry>
       </row>

       <row>
       <entry> <literal>[</><replaceable>chars</><literal>]</> </entry>
       <entry> a <firstterm>bracket expression</>,
       matching any one of the <replaceable>chars</> (see
       <xref linkend="posix-bracket-expressions"> for more detail) </entry>
       </row>

       <row>
       <entry> <literal>\</><replaceable>k</> </entry>
       <entry> (where <replaceable>k</> is a non-alphanumeric character)
       matches that character taken as an ordinary character,
       e.g. <literal>\\</> matches a backslash character </entry>
       </row>

       <row>
       <entry> <literal>\</><replaceable>c</> </entry>
       <entry> where <replaceable>c</> is alphanumeric
       (possibly followed by other characters)
       is an <firstterm>escape</>, see <xref linkend="posix-escape-sequences">
       (AREs only; in EREs and BREs, this matches <replaceable>c</>) </entry>
       </row>

       <row>
       <entry> <literal>{</> </entry>
       <entry> when followed by a character other than a digit,
       matches the left-brace character <literal>{</>;
       when followed by a digit, it is the beginning of a
       <replaceable>bound</> (see below) </entry>
       </row>

       <row>
       <entry> <replaceable>x</> </entry>
       <entry> where <replaceable>x</> is a single character with no other
       significance, matches that character </entry>
       </row>
      </tbody>
     </tgroup>
    </table>

   <para>
    An RE may not end with <literal>\</>.
3253 3254 3255 3256
   </para>

   <note>
    <para>
3257 3258 3259
     Remember that the backslash (<literal>\</literal>) already has a special
     meaning in <productname>PostgreSQL</> string literals.
     To write a pattern constant that contains a backslash,
3260
     you must write two backslashes in the statement.
3261
    </para>
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
   </note>

   <table id="posix-quantifiers-table">
    <title>Regular Expression Quantifiers</title>

    <tgroup cols="2">
     <thead>
      <row>
       <entry>Quantifier</entry>
       <entry>Matches</entry>
      </row>
     </thead>

      <tbody>
       <row>
       <entry> <literal>*</> </entry>
       <entry> a sequence of 0 or more matches of the atom </entry>
       </row>

       <row>
       <entry> <literal>+</> </entry>
       <entry> a sequence of 1 or more matches of the atom </entry>
       </row>

       <row>
       <entry> <literal>?</> </entry>
       <entry> a sequence of 0 or 1 matches of the atom </entry>
       </row>

       <row>
       <entry> <literal>{</><replaceable>m</><literal>}</> </entry>
       <entry> a sequence of exactly <replaceable>m</> matches of the atom </entry>
       </row>

       <row>
       <entry> <literal>{</><replaceable>m</><literal>,}</> </entry>
       <entry> a sequence of <replaceable>m</> or more matches of the atom </entry>
       </row>

       <row>
       <entry>
       <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
       <entry> a sequence of <replaceable>m</> through <replaceable>n</>
       (inclusive) matches of the atom; <replaceable>m</> may not exceed
       <replaceable>n</> </entry>
       </row>

       <row>
       <entry> <literal>*?</> </entry>
       <entry> non-greedy version of <literal>*</> </entry>
       </row>

       <row>
       <entry> <literal>+?</> </entry>
       <entry> non-greedy version of <literal>+</> </entry>
       </row>

       <row>
       <entry> <literal>??</> </entry>
       <entry> non-greedy version of <literal>?</> </entry>
       </row>

       <row>
       <entry> <literal>{</><replaceable>m</><literal>}?</> </entry>
       <entry> non-greedy version of <literal>{</><replaceable>m</><literal>}</> </entry>
       </row>

       <row>
       <entry> <literal>{</><replaceable>m</><literal>,}?</> </entry>
       <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,}</> </entry>
       </row>

       <row>
       <entry>
       <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</> </entry>
       <entry> non-greedy version of <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</> </entry>
       </row>
      </tbody>
     </tgroup>
    </table>

   <para>
    The forms using <literal>{</><replaceable>...</><literal>}</>
T
Tom Lane 已提交
3345
    are known as <firstterm>bounds</>.
3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
    The numbers <replaceable>m</> and <replaceable>n</> within a bound are
    unsigned decimal integers with permissible values from 0 to 255 inclusive.
   </para>

    <para>
     <firstterm>Non-greedy</> quantifiers (available in AREs only) match the
     same possibilities as their corresponding normal (<firstterm>greedy</>)
     counterparts, but prefer the smallest number rather than the largest
     number of matches.
     See <xref linkend="posix-matching-rules"> for more detail.
   </para>

   <note>
    <para>
     A quantifier cannot immediately follow another quantifier.
     A quantifier cannot
3362 3363 3364 3365
     begin an expression or subexpression or follow
     <literal>^</literal> or <literal>|</literal>.
    </para>
   </note>
3366

3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405
   <table id="posix-constraints-table">
    <title>Regular Expression Constraints</title>

    <tgroup cols="2">
     <thead>
      <row>
       <entry>Constraint</entry>
       <entry>Description</entry>
      </row>
     </thead>

      <tbody>
       <row>
       <entry> <literal>^</> </entry>
       <entry> matches at the beginning of the string </entry>
       </row>

       <row>
       <entry> <literal>$</> </entry>
       <entry> matches at the end of the string </entry>
       </row>

       <row>
       <entry> <literal>(?=</><replaceable>re</><literal>)</> </entry>
       <entry> <firstterm>positive lookahead</> matches at any point
       where a substring matching <replaceable>re</> begins
       (AREs only) </entry>
       </row>

       <row>
       <entry> <literal>(?!</><replaceable>re</><literal>)</> </entry>
       <entry> <firstterm>negative lookahead</> matches at any point
       where no substring matching <replaceable>re</> begins
       (AREs only) </entry>
       </row>
      </tbody>
     </tgroup>
    </table>

3406
   <para>
3407 3408 3409
    Lookahead constraints may not contain <firstterm>back references</>
    (see <xref linkend="posix-escape-sequences">),
    and all parentheses within them are considered non-capturing.
3410
   </para>
3411 3412 3413 3414
   </sect3>

   <sect3 id="posix-bracket-expressions">
    <title>Bracket Expressions</title>
3415

T
Thomas G. Lockhart 已提交
3416
   <para>
3417 3418 3419 3420
    A <firstterm>bracket expression</firstterm> is a list of
    characters enclosed in <literal>[]</literal>.  It normally matches
    any single character from the list (but see below).  If the list
    begins with <literal>^</literal>, it matches any single character
3421 3422
    <emphasis>not</> from the rest of the list.
    If two characters
3423 3424 3425 3426 3427 3428
    in the list are separated by <literal>-</literal>, this is
    shorthand for the full range of characters between those two
    (inclusive) in the collating sequence,
    e.g. <literal>[0-9]</literal> in <acronym>ASCII</acronym> matches
    any decimal digit.  It is illegal for two ranges to share an
    endpoint, e.g.  <literal>a-c-e</literal>.  Ranges are very
3429
    collating-sequence-dependent, so portable programs should avoid
3430
    relying on them.
T
Thomas G. Lockhart 已提交
3431
   </para>
3432

T
Thomas G. Lockhart 已提交
3433
   <para>
3434 3435 3436 3437 3438 3439
    To include a literal <literal>]</literal> in the list, make it the
    first character (following a possible <literal>^</literal>).  To
    include a literal <literal>-</literal>, make it the first or last
    character, or the second endpoint of a range.  To use a literal
    <literal>-</literal> as the first endpoint of a range, enclose it
    in <literal>[.</literal> and <literal>.]</literal> to make it a
3440 3441 3442 3443 3444 3445 3446
    collating element (see below).  With the exception of these characters,
    some combinations using <literal>[</literal>
    (see next paragraphs), and escapes (AREs only), all other special
    characters lose their special significance within a bracket expression.
    In particular, <literal>\</literal> is not special when following
    ERE or BRE rules, though it is special (as introducing an escape)
    in AREs.
3447 3448 3449 3450
   </para>

   <para>
    Within a bracket expression, a collating element (a character, a
3451
    multiple-character sequence that collates as if it were a single
3452 3453 3454 3455
    character, or a collating-sequence name for either) enclosed in
    <literal>[.</literal> and <literal>.]</literal> stands for the
    sequence of characters of that collating element.  The sequence is
    a single element of the bracket expression's list.  A bracket
3456
    expression containing a multiple-character collating element can thus
3457 3458 3459 3460 3461 3462
    match more than one character, e.g. if the collating sequence
    includes a <literal>ch</literal> collating element, then the RE
    <literal>[[.ch.]]*c</literal> matches the first five characters of
    <literal>chchcc</literal>.
   </para>

3463 3464
   <note>
    <para>
3465
     <productname>PostgreSQL</> currently has no multicharacter collating
3466 3467 3468 3469
     elements. This information describes possible future behavior.
    </para>
   </note>

3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502
   <para>
    Within a bracket expression, a collating element enclosed in
    <literal>[=</literal> and <literal>=]</literal> is an equivalence
    class, standing for the sequences of characters of all collating
    elements equivalent to that one, including itself.  (If there are
    no other equivalent collating elements, the treatment is as if the
    enclosing delimiters were <literal>[.</literal> and
    <literal>.]</literal>.)  For example, if <literal>o</literal> and
    <literal>^</literal> are the members of an equivalence class, then
    <literal>[[=o=]]</literal>, <literal>[[=^=]]</literal>, and
    <literal>[o^]</literal> are all synonymous.  An equivalence class
    may not be an endpoint of a range.
   </para>

   <para>
    Within a bracket expression, the name of a character class
    enclosed in <literal>[:</literal> and <literal>:]</literal> stands
    for the list of all characters belonging to that class.  Standard
    character class names are: <literal>alnum</literal>,
    <literal>alpha</literal>, <literal>blank</literal>,
    <literal>cntrl</literal>, <literal>digit</literal>,
    <literal>graph</literal>, <literal>lower</literal>,
    <literal>print</literal>, <literal>punct</literal>,
    <literal>space</literal>, <literal>upper</literal>,
    <literal>xdigit</literal>.  These stand for the character classes
    defined in
    <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>.
    A locale may provide others.  A character class may not be used as
    an endpoint of a range.
   </para>

   <para>
    There are two special cases of bracket expressions:  the bracket
3503
    expressions <literal>[[:&lt;:]]</literal> and
3504 3505
    <literal>[[:&gt;:]]</literal> are constraints,
    matching empty strings at the beginning
3506
    and end of a word respectively.  A word is defined as a sequence
3507 3508 3509
    of word characters that is neither preceded nor followed by word
    characters.  A word character is an <literal>alnum</> character (as
    defined by
3510 3511
    <citerefentry><refentrytitle>ctype</refentrytitle><manvolnum>3</manvolnum></citerefentry>)
    or an underscore.  This is an extension, compatible with but not
3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568
    specified by <acronym>POSIX</acronym> 1003.2, and should be used with
    caution in software intended to be portable to other systems.
    The constraint escapes described below are usually preferable (they
    are no more standard, but are certainly easier to type).
   </para>
   </sect3>

   <sect3 id="posix-escape-sequences">
    <title>Regular Expression Escapes</title>

   <para>
    <firstterm>Escapes</> are special sequences beginning with <literal>\</>
    followed by an alphanumeric character. Escapes come in several varieties:
    character entry, class shorthands, constraint escapes, and back references.
    A <literal>\</> followed by an alphanumeric character but not constituting
    a valid escape is illegal in AREs.
    In EREs, there are no escapes: outside a bracket expression,
    a <literal>\</> followed by an alphanumeric character merely stands for
    that character as an ordinary character, and inside a bracket expression,
    <literal>\</> is an ordinary character.
    (The latter is the one actual incompatibility between EREs and AREs.)
   </para>

   <para>
    <firstterm>Character-entry escapes</> exist to make it easier to specify
    non-printing and otherwise inconvenient characters in REs.  They are
    shown in <xref linkend="posix-character-entry-escapes-table">.
   </para>

   <para>
    <firstterm>Class-shorthand escapes</> provide shorthands for certain
    commonly-used character classes.  They are
    shown in <xref linkend="posix-class-shorthand-escapes-table">.
   </para>

   <para>
    A <firstterm>constraint escape</> is a constraint,
    matching the empty string if specific conditions are met,
    written as an escape.  They are
    shown in <xref linkend="posix-constraint-escapes-table">.
   </para>

   <para>
    A <firstterm>back reference</> (<literal>\</><replaceable>n</>) matches the
    same string matched by the previous parenthesized subexpression specified
    by the number <replaceable>n</>
    (see <xref linkend="posix-constraint-backref-table">).  For example,
    <literal>([bc])\1</> matches <literal>bb</> or <literal>cc</>
    but not <literal>bc</> or <literal>cb</>.
    The subexpression must entirely precede the back reference in the RE.
    Subexpressions are numbered in the order of their leading parentheses.
    Non-capturing parentheses do not define subexpressions.
   </para>

   <note>
    <para>
     Keep in mind that an escape's leading <literal>\</> will need to be
3569 3570 3571 3572
     doubled when entering the pattern as an SQL string constant.  For example:
<programlisting>
'123' ~ '^\\d{3}' <lineannotation>true</lineannotation>
</programlisting>
3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619
    </para>
   </note>

   <table id="posix-character-entry-escapes-table">
    <title>Regular Expression Character-Entry Escapes</title>

    <tgroup cols="2">
     <thead>
      <row>
       <entry>Escape</entry>
       <entry>Description</entry>
      </row>
     </thead>

      <tbody>
       <row>
       <entry> <literal>\a</> </entry>
       <entry> alert (bell) character, as in C </entry>
       </row>

       <row>
       <entry> <literal>\b</> </entry>
       <entry> backspace, as in C </entry>
       </row>

       <row>
       <entry> <literal>\B</> </entry>
       <entry> synonym for <literal>\</> to help reduce the need for backslash
       doubling </entry>
       </row>

       <row>
       <entry> <literal>\c</><replaceable>X</> </entry>
       <entry> (where <replaceable>X</> is any character) the character whose
       low-order 5 bits are the same as those of
       <replaceable>X</>, and whose other bits are all zero </entry>
       </row>

       <row>
       <entry> <literal>\e</> </entry>
       <entry> the character whose collating-sequence name
       is <literal>ESC</>,
       or failing that, the character with octal value 033 </entry>
       </row>

       <row>
       <entry> <literal>\f</> </entry>
3620
       <entry> form feed, as in C </entry>
3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
       </row>

       <row>
       <entry> <literal>\n</> </entry>
       <entry> newline, as in C </entry>
       </row>

       <row>
       <entry> <literal>\r</> </entry>
       <entry> carriage return, as in C </entry>
       </row>

       <row>
       <entry> <literal>\t</> </entry>
       <entry> horizontal tab, as in C </entry>
       </row>

       <row>
       <entry> <literal>\u</><replaceable>wxyz</> </entry>
       <entry> (where <replaceable>wxyz</> is exactly four hexadecimal digits)
3641
       the UTF16 (Unicode, 16-bit) character <literal>U+</><replaceable>wxyz</>
3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758
       in the local byte ordering </entry>
       </row>

       <row>
       <entry> <literal>\U</><replaceable>stuvwxyz</> </entry>
       <entry> (where <replaceable>stuvwxyz</> is exactly eight hexadecimal
       digits)
       reserved for a somewhat-hypothetical Unicode extension to 32 bits
       </entry> 
       </row>

       <row>
       <entry> <literal>\v</> </entry>
       <entry> vertical tab, as in C </entry>
       </row>

       <row>
       <entry> <literal>\x</><replaceable>hhh</> </entry>
       <entry> (where <replaceable>hhh</> is any sequence of hexadecimal
       digits)
       the character whose hexadecimal value is
       <literal>0x</><replaceable>hhh</>
       (a single character no matter how many hexadecimal digits are used)
       </entry>
       </row>

       <row>
       <entry> <literal>\0</> </entry>
       <entry> the character whose value is <literal>0</> </entry>
       </row>

       <row>
       <entry> <literal>\</><replaceable>xy</> </entry>
       <entry> (where <replaceable>xy</> is exactly two octal digits,
       and is not a <firstterm>back reference</>)
       the character whose octal value is
       <literal>0</><replaceable>xy</> </entry>
       </row>

       <row>
       <entry> <literal>\</><replaceable>xyz</> </entry>
       <entry> (where <replaceable>xyz</> is exactly three octal digits,
       and is not a <firstterm>back reference</>)
       the character whose octal value is
       <literal>0</><replaceable>xyz</> </entry>
       </row>
      </tbody>
     </tgroup>
    </table>

   <para>
    Hexadecimal digits are <literal>0</>-<literal>9</>,
    <literal>a</>-<literal>f</>, and <literal>A</>-<literal>F</>.
    Octal digits are <literal>0</>-<literal>7</>.
   </para>

   <para>
    The character-entry escapes are always taken as ordinary characters.
    For example, <literal>\135</> is <literal>]</> in ASCII, but
    <literal>\135</> does not terminate a bracket expression.
   </para>

   <table id="posix-class-shorthand-escapes-table">
    <title>Regular Expression Class-Shorthand Escapes</title>

    <tgroup cols="2">
     <thead>
      <row>
       <entry>Escape</entry>
       <entry>Description</entry>
      </row>
     </thead>

      <tbody>
       <row>
       <entry> <literal>\d</> </entry>
       <entry> <literal>[[:digit:]]</> </entry>
       </row>

       <row>
       <entry> <literal>\s</> </entry>
       <entry> <literal>[[:space:]]</> </entry>
       </row>

       <row>
       <entry> <literal>\w</> </entry>
       <entry> <literal>[[:alnum:]_]</>
       (note underscore is included) </entry>
       </row>

       <row>
       <entry> <literal>\D</> </entry>
       <entry> <literal>[^[:digit:]]</> </entry>
       </row>

       <row>
       <entry> <literal>\S</> </entry>
       <entry> <literal>[^[:space:]]</> </entry>
       </row>

       <row>
       <entry> <literal>\W</> </entry>
       <entry> <literal>[^[:alnum:]_]</>
       (note underscore is included) </entry>
       </row>
      </tbody>
     </tgroup>
    </table>

   <para>
    Within bracket expressions, <literal>\d</>, <literal>\s</>,
    and <literal>\w</> lose their outer brackets,
    and <literal>\D</>, <literal>\S</>, and <literal>\W</> are illegal.
    (So, for example, <literal>[a-c\d]</> is equivalent to
    <literal>[a-c[:digit:]]</>.
    Also, <literal>[a-c\D]</>, which is equivalent to
    <literal>[a-c^[:digit:]]</>, is illegal.)
3759 3760
   </para>

3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854
   <table id="posix-constraint-escapes-table">
    <title>Regular Expression Constraint Escapes</title>

    <tgroup cols="2">
     <thead>
      <row>
       <entry>Escape</entry>
       <entry>Description</entry>
      </row>
     </thead>

      <tbody>
       <row>
       <entry> <literal>\A</> </entry>
       <entry> matches only at the beginning of the string
       (see <xref linkend="posix-matching-rules"> for how this differs from
       <literal>^</>) </entry>
       </row>

       <row>
       <entry> <literal>\m</> </entry>
       <entry> matches only at the beginning of a word </entry>
       </row>

       <row>
       <entry> <literal>\M</> </entry>
       <entry> matches only at the end of a word </entry>
       </row>

       <row>
       <entry> <literal>\y</> </entry>
       <entry> matches only at the beginning or end of a word </entry>
       </row>

       <row>
       <entry> <literal>\Y</> </entry>
       <entry> matches only at a point that is not the beginning or end of a
       word </entry>
       </row>

       <row>
       <entry> <literal>\Z</> </entry>
       <entry> matches only at the end of the string
       (see <xref linkend="posix-matching-rules"> for how this differs from
       <literal>$</>) </entry>
       </row>
      </tbody>
     </tgroup>
    </table>

   <para>
    A word is defined as in the specification of
    <literal>[[:&lt;:]]</> and <literal>[[:&gt;:]]</> above.
    Constraint escapes are illegal within bracket expressions.
   </para>

   <table id="posix-constraint-backref-table">
    <title>Regular Expression Back References</title>

    <tgroup cols="2">
     <thead>
      <row>
       <entry>Escape</entry>
       <entry>Description</entry>
      </row>
     </thead>

      <tbody>
       <row>
       <entry> <literal>\</><replaceable>m</> </entry>
       <entry> (where <replaceable>m</> is a nonzero digit)
       a back reference to the <replaceable>m</>'th subexpression </entry>
       </row>

       <row>
       <entry> <literal>\</><replaceable>mnn</> </entry>
       <entry> (where <replaceable>m</> is a nonzero digit, and
       <replaceable>nn</> is some more digits, and the decimal value
       <replaceable>mnn</> is not greater than the number of closing capturing
       parentheses seen so far) 
       a back reference to the <replaceable>mnn</>'th subexpression </entry>
       </row>
      </tbody>
     </tgroup>
    </table>

   <note>
    <para>
     There is an inherent historical ambiguity between octal character-entry 
     escapes and back references, which is resolved by heuristics,
     as hinted at above.
     A leading zero always indicates an octal escape.
     A single non-zero digit, not followed by another digit,
     is always taken as a back reference.
3855
     A multidigit sequence not starting with a zero is taken as a back 
3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
     reference if it comes after a suitable subexpression
     (i.e. the number is in the legal range for a back reference),
     and otherwise is taken as octal.
    </para>
   </note>
   </sect3>

   <sect3 id="posix-metasyntax">
    <title>Regular Expression Metasyntax</title>

3866
   <para>
3867 3868
    In addition to the main syntax described above, there are some special
    forms and miscellaneous syntactic facilities available.
3869 3870 3871
   </para>

   <para>
3872
    Normally the flavor of RE being used is determined by
3873
    <varname>regex_flavor</>.
3874
    However, this can be overridden by a <firstterm>director</> prefix.
T
Tom Lane 已提交
3875 3876 3877 3878
    If an RE begins with <literal>***:</>,
    the rest of the RE is taken as an ARE regardless of
    <varname>regex_flavor</>.
    If an RE begins with <literal>***=</>,
3879 3880
    the rest of the RE is taken to be a literal string,
    with all characters considered ordinary characters.
3881 3882 3883
   </para>

   <para>
3884 3885 3886 3887
    An ARE may begin with <firstterm>embedded options</>:
    a sequence <literal>(?</><replaceable>xyz</><literal>)</>
    (where <replaceable>xyz</> is one or more alphabetic characters)
    specifies options affecting the rest of the RE.
3888 3889
    These options override any previously determined options (including
    both the RE flavor and case sensitivity).
3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912
    The available option letters are
    shown in <xref linkend="posix-embedded-options-table">.
   </para>

   <table id="posix-embedded-options-table">
    <title>ARE Embedded-Option Letters</title>

    <tgroup cols="2">
     <thead>
      <row>
       <entry>Option</entry>
       <entry>Description</entry>
      </row>
     </thead>

      <tbody>
       <row>
       <entry> <literal>b</> </entry>
       <entry> rest of RE is a BRE </entry>
       </row>

       <row>
       <entry> <literal>c</> </entry>
3913
       <entry> case-sensitive matching (overrides operator type) </entry>
3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
       </row>

       <row>
       <entry> <literal>e</> </entry>
       <entry> rest of RE is an ERE </entry>
       </row>

       <row>
       <entry> <literal>i</> </entry>
       <entry> case-insensitive matching (see
3924
       <xref linkend="posix-matching-rules">) (overrides operator type) </entry>
3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
       </row>

       <row>
       <entry> <literal>m</> </entry>
       <entry> historical synonym for <literal>n</> </entry>
       </row>

       <row>
       <entry> <literal>n</> </entry>
       <entry> newline-sensitive matching (see
       <xref linkend="posix-matching-rules">) </entry>
       </row>

       <row>
       <entry> <literal>p</> </entry>
       <entry> partial newline-sensitive matching (see
       <xref linkend="posix-matching-rules">) </entry>
       </row>

       <row>
       <entry> <literal>q</> </entry>
       <entry> rest of RE is a literal (<quote>quoted</>) string, all ordinary
       characters </entry>
       </row>

       <row>
       <entry> <literal>s</> </entry>
3952
       <entry> non-newline-sensitive matching (default) </entry>
3953 3954 3955 3956
       </row>

       <row>
       <entry> <literal>t</> </entry>
3957
       <entry> tight syntax (default; see below) </entry>
3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975
       </row>

       <row>
       <entry> <literal>w</> </entry>
       <entry> inverse partial newline-sensitive (<quote>weird</>) matching
       (see <xref linkend="posix-matching-rules">) </entry>
       </row>

       <row>
       <entry> <literal>x</> </entry>
       <entry> expanded syntax (see below) </entry>
       </row>
      </tbody>
     </tgroup>
    </table>

   <para>
    Embedded options take effect at the <literal>)</> terminating the sequence.
T
Tom Lane 已提交
3976 3977
    They may appear only at the start of an ARE (after the
    <literal>***:</> director if any).
3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
   </para>

   <para>
    In addition to the usual (<firstterm>tight</>) RE syntax, in which all
    characters are significant, there is an <firstterm>expanded</> syntax,
    available by specifying the embedded <literal>x</> option.
    In the expanded syntax,
    white-space characters in the RE are ignored, as are
    all characters between a <literal>#</>
    and the following newline (or the end of the RE).  This
    permits paragraphing and commenting a complex RE.
    There are three exceptions to that basic rule:

    <itemizedlist>
     <listitem>
      <para>
       a white-space character or <literal>#</> preceded by <literal>\</> is
       retained
      </para>
     </listitem>
     <listitem>
      <para>
       white space or <literal>#</> within a bracket expression is retained
      </para>
     </listitem>
     <listitem>
      <para>
4005
       white space and comments cannot appear within multicharacter symbols,
T
Tom Lane 已提交
4006
       such as <literal>(?:</>
4007 4008 4009 4010
      </para>
     </listitem>
    </itemizedlist>

T
Tom Lane 已提交
4011
    For this purpose, white-space characters are blank, tab, newline, and
4012 4013 4014 4015 4016 4017 4018 4019 4020
    any character that belongs to the <replaceable>space</> character class.
   </para>

   <para>
    Finally, in an ARE, outside bracket expressions, the sequence
    <literal>(?#</><replaceable>ttt</><literal>)</>
    (where <replaceable>ttt</> is any text not containing a <literal>)</>)
    is a comment, completely ignored.
    Again, this is not allowed between the characters of
4021
    multicharacter symbols, like <literal>(?:</>.
4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040
    Such comments are more a historical artifact than a useful facility,
    and their use is deprecated; use the expanded syntax instead.
   </para>

   <para>
    <emphasis>None</> of these metasyntax extensions is available if
    an initial <literal>***=</> director
    has specified that the user's input be treated as a literal string
    rather than as an RE.
   </para>
   </sect3>

   <sect3 id="posix-matching-rules">
    <title>Regular Expression Matching Rules</title>

   <para>
    In the event that an RE could match more than one substring of a given
    string, the RE matches the one starting earliest in the string.
    If the RE could match more than one substring starting at that point,
4041 4042 4043
    either the longest possible match or the shortest possible match will
    be taken, depending on whether the RE is <firstterm>greedy</> or
    <firstterm>non-greedy</>.
4044 4045 4046
   </para>

   <para>
4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130
    Whether an RE is greedy or not is determined by the following rules:
    <itemizedlist>
     <listitem>
      <para>
       Most atoms, and all constraints, have no greediness attribute (because
       they cannot match variable amounts of text anyway).
      </para>
     </listitem>
     <listitem>
      <para>
       Adding parentheses around an RE does not change its greediness.
      </para>
     </listitem>
     <listitem>
      <para>
       A quantified atom with a fixed-repetition quantifier
       (<literal>{</><replaceable>m</><literal>}</>
       or
       <literal>{</><replaceable>m</><literal>}?</>)
       has the same greediness (possibly none) as the atom itself.
      </para>
     </listitem>
     <listitem>
      <para>
       A quantified atom with other normal quantifiers (including
       <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}</>
       with <replaceable>m</> equal to <replaceable>n</>)
       is greedy (prefers longest match).
      </para>
     </listitem>
     <listitem>
      <para>
       A quantified atom with a non-greedy quantifier (including
       <literal>{</><replaceable>m</><literal>,</><replaceable>n</><literal>}?</>
       with <replaceable>m</> equal to <replaceable>n</>)
       is non-greedy (prefers shortest match).
      </para>
     </listitem>
     <listitem>
      <para>
       A branch &mdash; that is, an RE that has no top-level
       <literal>|</> operator &mdash; has the same greediness as the first
       quantified atom in it that has a greediness attribute.
      </para>
     </listitem>
     <listitem>
      <para>
       An RE consisting of two or more branches connected by the
       <literal>|</> operator is always greedy.
      </para>
     </listitem>
    </itemizedlist>
   </para>

   <para>
    The above rules associate greediness attributes not only with individual
    quantified atoms, but with branches and entire REs that contain quantified
    atoms.  What that means is that the matching is done in such a way that
    the branch, or whole RE, matches the longest or shortest possible
    substring <emphasis>as a whole</>.  Once the length of the entire match
    is determined, the part of it that matches any particular subexpression
    is determined on the basis of the greediness attribute of that
    subexpression, with subexpressions starting earlier in the RE taking
    priority over ones starting later.
   </para>

   <para>
    An example of what this means:
<screen>
SELECT SUBSTRING('XY1234Z', 'Y*([0-9]{1,3})');
<lineannotation>Result: </lineannotation><computeroutput>123</computeroutput>
SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{1,3})');
<lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
</screen>
    In the first case, the RE as a whole is greedy because <literal>Y*</>
    is greedy.  It can match beginning at the <literal>Y</>, and it matches
    the longest possible string starting there, i.e., <literal>Y123</>.
    The output is the parenthesized part of that, or <literal>123</>.
    In the second case, the RE as a whole is non-greedy because <literal>Y*?</>
    is non-greedy.  It can match beginning at the <literal>Y</>, and it matches
    the shortest possible string starting there, i.e., <literal>Y1</>.
    The subexpression <literal>[0-9]{1,3}</> is greedy but it cannot change
    the decision as to the overall match length; so it is forced to match
    just <literal>1</>.
4131 4132 4133
   </para>

   <para>
4134 4135 4136 4137 4138
    In short, when an RE contains both greedy and non-greedy subexpressions,
    the total match length is either as long as possible or as short as
    possible, according to the attribute assigned to the whole RE.  The
    attributes assigned to the subexpressions only affect how much of that
    match they are allowed to <quote>eat</> relative to each other.
4139 4140 4141 4142
   </para>

   <para>
    The quantifiers <literal>{1,1}</> and <literal>{1,1}?</>
4143
    can be used to force greediness or non-greediness, respectively,
4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168
    on a subexpression or a whole RE.
   </para>

   <para>
    Match lengths are measured in characters, not collating elements.
    An empty string is considered longer than no match at all.
    For example:
    <literal>bb*</>
    matches the three middle characters of <literal>abbbc</>;
    <literal>(week|wee)(night|knights)</>
    matches all ten characters of <literal>weeknights</>;
    when <literal>(.*).*</>
    is matched against <literal>abc</> the parenthesized subexpression
    matches all three characters; and when
    <literal>(a*)*</> is matched against <literal>bc</>
    both the whole RE and the parenthesized
    subexpression match an empty string.
   </para>

   <para>
    If case-independent matching is specified,
    the effect is much as if all case distinctions had vanished from the
    alphabet.
    When an alphabetic that exists in multiple cases appears as an
    ordinary character outside a bracket expression, it is effectively
4169
    transformed into a bracket expression containing both cases,
4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240
    e.g. <literal>x</> becomes <literal>[xX]</>.
    When it appears inside a bracket expression, all case counterparts
    of it are added to the bracket expression, e.g.
    <literal>[x]</> becomes <literal>[xX]</>
    and <literal>[^x]</> becomes <literal>[^xX]</>.
   </para>

   <para>
    If newline-sensitive matching is specified, <literal>.</>
    and bracket expressions using <literal>^</>
    will never match the newline character
    (so that matches will never cross newlines unless the RE
    explicitly arranges it)
    and <literal>^</>and <literal>$</>
    will match the empty string after and before a newline
    respectively, in addition to matching at beginning and end of string
    respectively.
    But the ARE escapes <literal>\A</> and <literal>\Z</>
    continue to match beginning or end of string <emphasis>only</>.
   </para>

   <para>
    If partial newline-sensitive matching is specified,
    this affects <literal>.</> and bracket expressions
    as with newline-sensitive matching, but not <literal>^</>
    and <literal>$</>.
   </para>

   <para>
    If inverse partial newline-sensitive matching is specified,
    this affects <literal>^</> and <literal>$</>
    as with newline-sensitive matching, but not <literal>.</>
    and bracket expressions.
    This isn't very useful but is provided for symmetry.
   </para>
   </sect3>

   <sect3 id="posix-limits-compatibility">
    <title>Limits and Compatibility</title>

   <para>
    No particular limit is imposed on the length of REs in this
    implementation.  However,
    programs intended to be highly portable should not employ REs longer
    than 256 bytes,
    as a POSIX-compliant implementation can refuse to accept such REs.
   </para>

   <para>
    The only feature of AREs that is actually incompatible with
    POSIX EREs is that <literal>\</> does not lose its special
    significance inside bracket expressions.
    All other ARE features use syntax which is illegal or has
    undefined or unspecified effects in POSIX EREs;
    the <literal>***</> syntax of directors likewise is outside the POSIX
    syntax for both BREs and EREs.
   </para>

   <para>
    Many of the ARE extensions are borrowed from Perl, but some have
    been changed to clean them up, and a few Perl extensions are not present.
    Incompatibilities of note include <literal>\b</>, <literal>\B</>,
    the lack of special treatment for a trailing newline,
    the addition of complemented bracket expressions to the things
    affected by newline-sensitive matching,
    the restrictions on parentheses and back references in lookahead
    constraints, and the longest/shortest-match (rather than first-match)
    matching semantics.
   </para>

   <para>
4241
    Two significant incompatibilities exist between AREs and the ERE syntax
4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261
    recognized by pre-7.4 releases of <productname>PostgreSQL</>:

    <itemizedlist>
     <listitem>
      <para>
       In AREs, <literal>\</> followed by an alphanumeric character is either
       an escape or an error, while in previous releases, it was just another
       way of writing the alphanumeric.
       This should not be much of a problem because there was no reason to
       write such a sequence in earlier releases.
      </para>
     </listitem>
     <listitem>
      <para>
       In AREs, <literal>\</> remains a special character within
       <literal>[]</>, so a literal <literal>\</> within a bracket
       expression must be written <literal>\\</>.
      </para>
     </listitem>
    </itemizedlist>
4262 4263 4264

    While these differences are unlikely to create a problem for most
    applications, you can avoid them if necessary by
4265
    setting <varname>regex_flavor</> to <literal>extended</>.
4266 4267 4268 4269 4270
   </para>
   </sect3>

   <sect3 id="posix-basic-regexes">
    <title>Basic Regular Expressions</title>
4271

4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301
   <para>
    BREs differ from EREs in several respects.
    <literal>|</>, <literal>+</>, and <literal>?</>
    are ordinary characters and there is no equivalent
    for their functionality.
    The delimiters for bounds are
    <literal>\{</> and <literal>\}</>,
    with <literal>{</> and <literal>}</>
    by themselves ordinary characters.
    The parentheses for nested subexpressions are
    <literal>\(</> and <literal>\)</>,
    with <literal>(</> and <literal>)</> by themselves ordinary characters.
    <literal>^</> is an ordinary character except at the beginning of the
    RE or the beginning of a parenthesized subexpression,
    <literal>$</> is an ordinary character except at the end of the
    RE or the end of a parenthesized subexpression,
    and <literal>*</> is an ordinary character if it appears at the beginning
    of the RE or the beginning of a parenthesized subexpression
    (after a possible leading <literal>^</>).
    Finally, single-digit back references are available, and
    <literal>\&lt;</> and <literal>\&gt;</>
    are synonyms for
    <literal>[[:&lt;:]]</> and <literal>[[:&gt;:]]</>
    respectively; no other escapes are available.
   </para>
   </sect3>

<!-- end re_syntax.n man page -->

  </sect2>
4302 4303 4304 4305
 </sect1>


  <sect1 id="functions-formatting">
4306
   <title>Data Type Formatting Functions</title>
4307

4308
   <indexterm>
4309 4310 4311
    <primary>formatting</primary>
   </indexterm>

4312
   <indexterm>
P
Peter Eisentraut 已提交
4313 4314
    <primary>to_char</primary>
   </indexterm>
4315 4316 4317 4318 4319 4320 4321 4322 4323
   <indexterm>
    <primary>to_date</primary>
   </indexterm>
   <indexterm>
    <primary>to_timestamp</primary>
   </indexterm>
   <indexterm>
    <primary>to_number</primary>
   </indexterm>
P
Peter Eisentraut 已提交
4324

4325
   <para>
4326
    The <productname>PostgreSQL</productname> formatting functions
4327 4328
    provide a powerful set of tools for converting various data types
    (date/time, integer, floating point, numeric) to formatted strings
4329
    and for converting from formatted strings to specific data types.
4330
    <xref linkend="functions-formatting-table"> lists them.
4331
    These functions all follow a common calling convention: the first
4332
    argument is the value to be formatted and the second argument is a
4333
    template that defines the output or input format.
4334
   </para>
4335 4336 4337 4338 4339 4340 4341
   <para>
    The <function>to_timestamp</function> function can also take a single 
    <type>double precision</type> argument to convert from Unix epoch to 
    <type>timestamp with time zone</type>.
    (<type>Integer</type> Unix epochs are implicitly cast to 
    <type>double precision</type>.)
   </para>
4342

4343
    <table id="functions-formatting-table">
4344 4345 4346 4347
     <title>Formatting Functions</title>
     <tgroup cols="4">
      <thead>
       <row>
4348 4349 4350 4351
        <entry>Function</entry>
        <entry>Return Type</entry>
        <entry>Description</entry>
        <entry>Example</entry>
4352 4353 4354 4355
       </row>
      </thead>
      <tbody>
       <row>
4356 4357 4358 4359
        <entry><literal><function>to_char</function>(<type>timestamp</type>, <type>text</type>)</literal></entry>
        <entry><type>text</type></entry>
        <entry>convert time stamp to string</entry>
        <entry><literal>to_char(current_timestamp, 'HH12:MI:SS')</literal></entry>
4360
       </row>
B
Bruce Momjian 已提交
4361
       <row>
4362 4363 4364 4365
        <entry><literal><function>to_char</function>(<type>interval</type>, <type>text</type>)</literal></entry>
        <entry><type>text</type></entry>
        <entry>convert interval to string</entry>
        <entry><literal>to_char(interval '15h&nbsp;2m&nbsp;12s', 'HH24:MI:SS')</literal></entry>
B
Bruce Momjian 已提交
4366
       </row>
4367
       <row>
4368 4369 4370 4371
        <entry><literal><function>to_char</function>(<type>int</type>, <type>text</type>)</literal></entry>
        <entry><type>text</type></entry>
        <entry>convert integer to string</entry>
        <entry><literal>to_char(125, '999')</literal></entry>
4372 4373
       </row>
       <row>
4374
        <entry><literal><function>to_char</function>(<type>double precision</type>,
4375
        <type>text</type>)</literal></entry>
4376 4377 4378
        <entry><type>text</type></entry>
        <entry>convert real/double precision to string</entry>
        <entry><literal>to_char(125.8::real, '999D9')</literal></entry>
4379 4380
       </row>
       <row>
4381 4382 4383 4384
        <entry><literal><function>to_char</function>(<type>numeric</type>, <type>text</type>)</literal></entry>
        <entry><type>text</type></entry>
        <entry>convert numeric to string</entry>
        <entry><literal>to_char(-125.8, '999D99S')</literal></entry>
4385 4386
       </row>
       <row>
4387 4388 4389 4390
        <entry><literal><function>to_date</function>(<type>text</type>, <type>text</type>)</literal></entry>
        <entry><type>date</type></entry>
        <entry>convert string to date</entry>
        <entry><literal>to_date('05&nbsp;Dec&nbsp;2000', 'DD&nbsp;Mon&nbsp;YYYY')</literal></entry>
4391 4392
       </row>
       <row>
4393 4394 4395 4396
        <entry><literal><function>to_timestamp</function>(<type>text</type>, <type>text</type>)</literal></entry>
        <entry><type>timestamp with time zone</type></entry>
        <entry>convert string to time stamp</entry>
        <entry><literal>to_timestamp('05&nbsp;Dec&nbsp;2000', 'DD&nbsp;Mon&nbsp;YYYY')</literal></entry>
4397
       </row>
4398 4399 4400 4401 4402 4403
       <row>
        <entry><literal><function>to_timestamp</function>(<type>double precision</type>)</literal></entry>
        <entry><type>timestamp with time zone</type></entry>
        <entry>convert UNIX epoch to time stamp</entry>
        <entry><literal>to_timestamp(200120400)</literal></entry>
       </row>
4404
       <row>
4405 4406 4407 4408
        <entry><literal><function>to_number</function>(<type>text</type>, <type>text</type>)</literal></entry>
        <entry><type>numeric</type></entry>
        <entry>convert string to numeric</entry>
        <entry><literal>to_number('12,454.8-', '99G999D9S')</literal></entry>
4409 4410 4411 4412 4413
       </row>
      </tbody>
     </tgroup>
    </table>

4414
   <para>
4415
    In an output template string (for <function>to_char</>), there are certain patterns that are
4416 4417
    recognized and replaced with appropriately-formatted data from the value
    to be formatted.  Any text that is not a template pattern is simply
4418
    copied verbatim.  Similarly, in an input template string (for anything but <function>to_char</>), template patterns
4419 4420 4421 4422
    identify the parts of the input data string to be looked at and the
    values to be found there.
   </para>

4423 4424 4425 4426 4427 4428
  <para>
   <xref linkend="functions-formatting-datetime-table"> shows the
   template patterns available for formatting date and time values.
  </para>

    <table id="functions-formatting-datetime-table">
4429
     <title>Template Patterns for Date/Time Formatting</title>
4430 4431 4432
     <tgroup cols="2">
      <thead>
       <row>
4433 4434
        <entry>Pattern</entry>
        <entry>Description</entry>
4435 4436 4437 4438
       </row>
      </thead>
      <tbody>
       <row>
4439 4440
        <entry><literal>HH</literal></entry>
        <entry>hour of day (01-12)</entry>
4441 4442
       </row>
       <row>
4443 4444
        <entry><literal>HH12</literal></entry>
        <entry>hour of day (01-12)</entry>
4445
       </row>       
4446
       <row>
4447 4448
        <entry><literal>HH24</literal></entry>
        <entry>hour of day (00-23)</entry>
4449
       </row>       
4450
       <row>
4451 4452
        <entry><literal>MI</literal></entry>
        <entry>minute (00-59)</entry>
4453 4454
       </row>   
       <row>
4455 4456
        <entry><literal>SS</literal></entry>
        <entry>second (00-59)</entry>
4457
       </row>
B
Bruce Momjian 已提交
4458
       <row>
4459 4460
        <entry><literal>MS</literal></entry>
        <entry>millisecond (000-999)</entry>
B
Bruce Momjian 已提交
4461 4462
       </row>
       <row>
4463 4464
        <entry><literal>US</literal></entry>
        <entry>microsecond (000000-999999)</entry>
B
Bruce Momjian 已提交
4465
       </row>
4466
       <row>
4467 4468
        <entry><literal>SSSS</literal></entry>
        <entry>seconds past midnight (0-86399)</entry>
4469
       </row>
B
Bruce Momjian 已提交
4470
       <row>
4471 4472 4473
        <entry><literal>AM</literal> or <literal>A.M.</literal> or
        <literal>PM</literal> or <literal>P.M.</literal></entry>
        <entry>meridian indicator (uppercase)</entry>
B
Bruce Momjian 已提交
4474 4475
       </row>
       <row>
4476 4477 4478
        <entry><literal>am</literal> or <literal>a.m.</literal> or
        <literal>pm</literal> or <literal>p.m.</literal></entry>
        <entry>meridian indicator (lowercase)</entry>
B
Bruce Momjian 已提交
4479
       </row>
4480
       <row>
4481 4482
        <entry><literal>Y,YYY</literal></entry>
        <entry>year (4 and more digits) with comma</entry>
4483 4484
       </row>
       <row>
4485 4486
        <entry><literal>YYYY</literal></entry>
        <entry>year (4 and more digits)</entry>
4487 4488
       </row>
       <row>
4489 4490
        <entry><literal>YYY</literal></entry>
        <entry>last 3 digits of year</entry>
4491 4492
       </row>
       <row>
4493 4494
        <entry><literal>YY</literal></entry>
        <entry>last 2 digits of year</entry>
4495 4496
       </row>
       <row>
4497 4498
        <entry><literal>Y</literal></entry>
        <entry>last digit of year</entry>
4499
       </row>
4500
       <row>
4501 4502
        <entry><literal>IYYY</literal></entry>
        <entry>ISO year (4 and more digits)</entry>
4503 4504
       </row>
       <row>
4505 4506
        <entry><literal>IYY</literal></entry>
        <entry>last 3 digits of ISO year</entry>
4507 4508
       </row>
       <row>
4509 4510
        <entry><literal>IY</literal></entry>
        <entry>last 2 digits of ISO year</entry>
4511 4512
       </row>
       <row>
4513 4514
        <entry><literal>I</literal></entry>
        <entry>last digits of ISO year</entry>
4515
       </row>
B
Bruce Momjian 已提交
4516
       <row>
4517 4518 4519
        <entry><literal>BC</literal> or <literal>B.C.</literal> or
        <literal>AD</literal> or <literal>A.D.</literal></entry>
        <entry>era indicator (uppercase)</entry>
B
Bruce Momjian 已提交
4520 4521
       </row>
       <row>
4522 4523 4524
        <entry><literal>bc</literal> or <literal>b.c.</literal> or
        <literal>ad</literal> or <literal>a.d.</literal></entry>
        <entry>era indicator (lowercase)</entry>
B
Bruce Momjian 已提交
4525
       </row>
4526
       <row>
4527 4528
        <entry><literal>MONTH</literal></entry>
        <entry>full uppercase month name (blank-padded to 9 chars)</entry>
4529 4530
       </row>
       <row>
4531 4532
        <entry><literal>Month</literal></entry>
        <entry>full mixed-case month name (blank-padded to 9 chars)</entry>
4533 4534
       </row>
       <row>
4535 4536
        <entry><literal>month</literal></entry>
        <entry>full lowercase month name (blank-padded to 9 chars)</entry>
4537 4538
       </row>
       <row>
4539 4540
        <entry><literal>MON</literal></entry>
        <entry>abbreviated uppercase month name (3 chars)</entry>
4541 4542
       </row>
       <row>
4543 4544
        <entry><literal>Mon</literal></entry>
        <entry>abbreviated mixed-case month name (3 chars)</entry>
4545 4546
       </row>
       <row>
4547 4548
        <entry><literal>mon</literal></entry>
        <entry>abbreviated lowercase month name (3 chars)</entry>
4549 4550
       </row>
       <row>
4551 4552
        <entry><literal>MM</literal></entry>
        <entry>month number (01-12)</entry>
4553 4554
       </row>
       <row>
4555 4556
        <entry><literal>DAY</literal></entry>
        <entry>full uppercase day name (blank-padded to 9 chars)</entry>
4557 4558
       </row>
       <row>
4559 4560
        <entry><literal>Day</literal></entry>
        <entry>full mixed-case day name (blank-padded to 9 chars)</entry>
4561 4562
       </row>
       <row>
4563 4564
        <entry><literal>day</literal></entry>
        <entry>full lowercase day name (blank-padded to 9 chars)</entry>
4565 4566
       </row>
       <row>
4567 4568
        <entry><literal>DY</literal></entry>
        <entry>abbreviated uppercase day name (3 chars)</entry>
4569 4570
       </row>
       <row>
4571 4572
        <entry><literal>Dy</literal></entry>
        <entry>abbreviated mixed-case day name (3 chars)</entry>
4573 4574
       </row>
       <row>
4575 4576
        <entry><literal>dy</literal></entry>
        <entry>abbreviated lowercase day name (3 chars)</entry>
4577 4578
       </row>
       <row>
4579 4580
        <entry><literal>DDD</literal></entry>
        <entry>day of year (001-366)</entry>
4581 4582
       </row>
       <row>
4583 4584
        <entry><literal>DD</literal></entry>
        <entry>day of month (01-31)</entry>
4585 4586
       </row>
       <row>
4587 4588
        <entry><literal>D</literal></entry>
        <entry>day of week (1-7; Sunday is 1)</entry>
4589 4590
       </row>
       <row>
4591 4592
        <entry><literal>W</literal></entry>
        <entry>week of month (1-5) (The first week starts on the first day of the month.)</entry>
4593 4594
       </row> 
       <row>
4595 4596
        <entry><literal>WW</literal></entry>
        <entry>week number of year (1-53) (The first week starts on the first day of the year.)</entry>
4597
       </row>
B
Bruce Momjian 已提交
4598
       <row>
4599 4600
        <entry><literal>IW</literal></entry>
        <entry>ISO week number of year (The first Thursday of the new year is in week 1.)</entry>
B
Bruce Momjian 已提交
4601
       </row>
4602
       <row>
4603 4604
        <entry><literal>CC</literal></entry>
        <entry>century (2 digits)</entry>
4605 4606
       </row>
       <row>
4607 4608
        <entry><literal>J</literal></entry>
        <entry>Julian Day (days since January 1, 4712 BC)</entry>
4609 4610
       </row>
       <row>
4611 4612
        <entry><literal>Q</literal></entry>
        <entry>quarter</entry>
4613 4614
       </row>
       <row>
4615 4616
        <entry><literal>RM</literal></entry>
        <entry>month in Roman numerals (I-XII; I=January) (uppercase)</entry>
B
Bruce Momjian 已提交
4617 4618
       </row>
       <row>
4619 4620
        <entry><literal>rm</literal></entry>
        <entry>month in Roman numerals (i-xii; i=January) (lowercase)</entry>
4621
       </row>
4622
       <row>
4623 4624
        <entry><literal>TZ</literal></entry>
        <entry>time-zone name (uppercase)</entry>
4625 4626
       </row>
       <row>
4627 4628
        <entry><literal>tz</literal></entry>
        <entry>time-zone name (lowercase)</entry>
4629
       </row>
4630 4631 4632 4633 4634
      </tbody>
     </tgroup>
    </table>

   <para>
4635
    Certain modifiers may be applied to any template pattern to alter its
4636 4637 4638
    behavior.  For example, <literal>FMMonth</literal>
    is the <literal>Month</literal> pattern with the
    <literal>FM</literal> modifier.
4639 4640
    <xref linkend="functions-formatting-datetimemod-table"> shows the
    modifier patterns for date/time formatting.
4641 4642
   </para>

4643
    <table id="functions-formatting-datetimemod-table">
4644
     <title>Template Pattern Modifiers for Date/Time Formatting</title>
4645 4646 4647
     <tgroup cols="3">
      <thead>
       <row>
4648 4649 4650
        <entry>Modifier</entry>
        <entry>Description</entry>
        <entry>Example</entry>
4651 4652 4653 4654
       </row>
      </thead>
      <tbody>
       <row>
4655 4656 4657
        <entry><literal>FM</literal> prefix</entry>
        <entry>fill mode (suppress padding blanks and zeroes)</entry>
        <entry><literal>FMMonth</literal></entry>
4658 4659
       </row>
       <row>
4660 4661 4662 4663
        <entry><literal>TH</literal> suffix</entry>
        <entry>uppercase ordinal number suffix</entry>
        <entry><literal>DDTH</literal></entry>
       </row>   
4664
       <row>
4665 4666 4667
        <entry><literal>th</literal> suffix</entry>
        <entry>lowercase ordinal number suffix</entry>
        <entry><literal>DDth</literal></entry>
4668 4669
       </row>
       <row>
4670 4671 4672 4673
        <entry><literal>FX</literal> prefix</entry>
        <entry>fixed format global option (see usage notes)</entry>
        <entry><literal>FX&nbsp;Month&nbsp;DD&nbsp;Day</literal></entry>
       </row>   
4674 4675 4676 4677 4678
       <row>
        <entry><literal>TM</literal> prefix</entry>
        <entry>translation mode (print localized day and month names)</entry>
        <entry><literal>TMMonth</literal></entry>
       </row>       
4679
       <row>
4680 4681 4682
        <entry><literal>SP</literal> suffix</entry>
        <entry>spell mode (not yet implemented)</entry>
        <entry><literal>DDSP</literal></entry>
4683 4684 4685 4686 4687 4688
       </row>       
      </tbody>
     </tgroup>
    </table>

   <para>
T
Tom Lane 已提交
4689
    Usage notes for date/time formatting:
4690 4691

    <itemizedlist>
4692 4693
     <listitem>
      <para>
4694
       <literal>FM</literal> suppresses leading zeroes and trailing blanks
4695 4696 4697 4698 4699
       that would otherwise be added to make the output of a pattern be
       fixed-width.
      </para>
     </listitem>

4700 4701 4702 4703 4704 4705
     <listitem>
      <para>
       <literal>TM</literal> does not include trailing blanks.
      </para>
     </listitem>

4706 4707 4708
     <listitem>
      <para>
       <function>to_timestamp</function> and <function>to_date</function>
4709
       skip multiple blank spaces in the input string if the <literal>FX</literal> option 
4710
       is not used. <literal>FX</literal> must be specified as the first item
4711 4712 4713 4714
       in the template.  For example 
       <literal>to_timestamp('2000&nbsp;&nbsp;&nbsp;&nbsp;JUN', 'YYYY MON')</literal> is correct, but
       <literal>to_timestamp('2000&nbsp;&nbsp;&nbsp;&nbsp;JUN', 'FXYYYY MON')</literal> returns an error,
       because <function>to_timestamp</function> expects one space only.
4715 4716 4717 4718 4719
      </para>
     </listitem>

     <listitem>
      <para>
4720
       Ordinary text is allowed in <function>to_char</function>
4721 4722
       templates and will be output literally.  You can put a substring
       in double quotes to force it to be interpreted as literal text
4723
       even if it contains pattern key words.  For example, in
4724
       <literal>'"Hello Year "YYYY'</literal>, the <literal>YYYY</literal>
4725
       will be replaced by the year data, but the single <literal>Y</literal> in <literal>Year</literal>
4726
       will not be.
4727 4728 4729 4730 4731
      </para>
     </listitem>

     <listitem>
      <para>
4732 4733 4734
       If you want to have a double quote in the output you must
       precede it with a backslash, for example <literal>'\\"YYYY
       Month\\"'</literal>. <!-- "" font-lock sanity :-) -->
4735 4736
       (Two backslashes are necessary because the backslash already
       has a special meaning in a string constant.)
4737 4738
      </para>
     </listitem>
4739 4740 4741

     <listitem>
      <para>
4742 4743
       The <literal>YYYY</literal> conversion from string to <type>timestamp</type> or
       <type>date</type> has a restriction if you use a year with more than 4 digits. You must
P
Peter Eisentraut 已提交
4744
       use some non-digit character or template after <literal>YYYY</literal>,
4745
       otherwise the year is always interpreted as 4 digits. For example
4746
       (with the year 20000):
P
Peter Eisentraut 已提交
4747
       <literal>to_date('200001131', 'YYYYMMDD')</literal> will be 
4748
       interpreted as a 4-digit year; instead use a non-digit 
P
Peter Eisentraut 已提交
4749 4750 4751
       separator after the year, like
       <literal>to_date('20000-1131', 'YYYY-MMDD')</literal> or
       <literal>to_date('20000Nov31', 'YYYYMonDD')</literal>.
4752
      </para>
4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763
     </listitem>

     <listitem>
      <para>
       In conversions from string to <type>timestamp</type> or
       <type>date</type>, the <literal>CC</literal> field is ignored if there
       is a <literal>YYY</literal>, <literal>YYYY</literal> or
       <literal>Y,YYY</literal> field. If <literal>CC</literal> is used with
       <literal>YY</literal> or <literal>Y</literal> then the year is computed
       as <literal>(CC-1)*100+YY</literal>.
      </para>
4764
     </listitem>
B
Bruce Momjian 已提交
4765 4766 4767

     <listitem>
      <para>
4768 4769
       Millisecond (<literal>MS</literal>) and microsecond (<literal>US</literal>)
       values in a conversion from string to <type>timestamp</type> are used as part of the
P
Peter Eisentraut 已提交
4770
       seconds after the decimal point. For example 
B
Bruce Momjian 已提交
4771
       <literal>to_timestamp('12:3', 'SS:MS')</literal> is not 3 milliseconds,
4772
       but 300, because the conversion counts it as 12 + 0.3 seconds.
4773 4774
       This means for the format <literal>SS:MS</literal>, the input values
       <literal>12:3</literal>, <literal>12:30</literal>, and <literal>12:300</literal> specify the
P
Peter Eisentraut 已提交
4775
       same number of milliseconds. To get three milliseconds, one must use
4776
       <literal>12:003</literal>, which the conversion counts as
P
Peter Eisentraut 已提交
4777 4778 4779 4780 4781
       12 + 0.003 = 12.003 seconds.
      </para>

      <para>
       Here is a more 
B
Bruce Momjian 已提交
4782
       complex example: 
4783
       <literal>to_timestamp('15:12:02.020.001230', 'HH:MI:SS.MS.US')</literal>
P
Peter Eisentraut 已提交
4784 4785
       is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds +
       1230 microseconds = 2.021230 seconds. 
B
Bruce Momjian 已提交
4786 4787
      </para>
     </listitem>
4788 4789 4790 4791 4792 4793 4794

     <listitem>
      <para><function>to_char</function>'s day of the week numbering
        (see the 'D' formatting pattern) is different from that of the 
        <function>extract</function> function.
      </para>
     </listitem>
4795 4796 4797 4798 4799 4800 4801 4802

     <listitem>
      <para><function>to_char(interval)</function> formats <literal>HH</> and 
        <literal>HH12</> as hours in a single day, while <literal>HH24</>
        can output hours exceeding a single day, e.g. &gt;24.
      </para>
     </listitem>

4803
    </itemizedlist>
4804
   </para>
4805

4806 4807 4808 4809 4810 4811
  <para>
   <xref linkend="functions-formatting-numeric-table"> shows the
   template patterns available for formatting numeric values.
  </para>

    <table id="functions-formatting-numeric-table">
4812
     <title>Template Patterns for Numeric Formatting</title>
4813 4814 4815
     <tgroup cols="2">
      <thead>
       <row>
4816 4817
        <entry>Pattern</entry>
        <entry>Description</entry>
4818 4819 4820 4821
       </row>
      </thead>
      <tbody>
       <row>
4822 4823
        <entry><literal>9</literal></entry>
        <entry>value with the specified number of digits</entry>
4824 4825
       </row>
       <row>
4826 4827
        <entry><literal>0</literal></entry>
        <entry>value with leading zeros</entry>
4828 4829
       </row>
       <row>
4830 4831
        <entry><literal>.</literal> (period)</entry>
        <entry>decimal point</entry>
4832 4833
       </row>       
       <row>
4834 4835
        <entry><literal>,</literal> (comma)</entry>
        <entry>group (thousand) separator</entry>
4836 4837
       </row>
       <row>
4838 4839
        <entry><literal>PR</literal></entry>
        <entry>negative value in angle brackets</entry>
4840 4841
       </row>
       <row>
4842 4843
        <entry><literal>S</literal></entry>
        <entry>sign anchored to number (uses locale)</entry>
4844 4845
       </row>
       <row>
4846 4847
        <entry><literal>L</literal></entry>
        <entry>currency symbol (uses locale)</entry>
4848 4849
       </row>
       <row>
4850 4851
        <entry><literal>D</literal></entry>
        <entry>decimal point (uses locale)</entry>
4852 4853
       </row>
       <row>
4854 4855
        <entry><literal>G</literal></entry>
        <entry>group separator (uses locale)</entry>
4856 4857
       </row>
       <row>
4858 4859
        <entry><literal>MI</literal></entry>
        <entry>minus sign in specified position (if number &lt; 0)</entry>
4860 4861
       </row>
       <row>
4862 4863
        <entry><literal>PL</literal></entry>
        <entry>plus sign in specified position (if number &gt; 0)</entry>
4864 4865
       </row>
       <row>
4866 4867
        <entry><literal>SG</literal></entry>
        <entry>plus/minus sign in specified position</entry>
4868 4869
       </row>
       <row>
4870 4871
        <entry><literal>RN</literal></entry>
        <entry>roman numeral (input between 1 and 3999)</entry>
4872 4873
       </row>
       <row>
4874 4875
        <entry><literal>TH</literal> or <literal>th</literal></entry>
        <entry>ordinal number suffix</entry>
4876 4877
       </row>
       <row>
4878 4879
        <entry><literal>V</literal></entry>
        <entry>shift specified number of digits (see notes)</entry>
4880 4881
       </row>
       <row>
4882 4883
        <entry><literal>EEEE</literal></entry>
        <entry>scientific notation (not implemented yet)</entry>
4884 4885 4886 4887 4888 4889
       </row>
      </tbody>
     </tgroup>
    </table>

   <para>
T
Tom Lane 已提交
4890
    Usage notes for numeric formatting:
4891 4892 4893 4894

    <itemizedlist>
     <listitem>
      <para>
4895
       A sign formatted using <literal>SG</literal>, <literal>PL</literal>, or
4896
       <literal>MI</literal> is not anchored to
4897
       the number; for example,
4898 4899
       <literal>to_char(-12, 'S9999')</literal> produces <literal>'&nbsp;&nbsp;-12'</literal>,
       but <literal>to_char(-12, 'MI9999')</literal> produces <literal>'-&nbsp;&nbsp;12'</literal>.
4900 4901
       The Oracle implementation does not allow the use of
       <literal>MI</literal> ahead of <literal>9</literal>, but rather
4902
       requires that <literal>9</literal> precede
4903 4904 4905 4906 4907 4908
       <literal>MI</literal>.
      </para>
     </listitem>

     <listitem>
      <para>
4909
       <literal>9</literal> results in a value with the same number of 
4910
       digits as there are <literal>9</literal>s. If a digit is
4911
       not available it outputs a space.
4912 4913 4914 4915 4916
      </para>
     </listitem>

     <listitem>
      <para>
4917
       <literal>TH</literal> does not convert values less than zero
4918
       and does not convert fractional numbers.
4919 4920 4921 4922 4923
      </para>
     </listitem>

     <listitem>
      <para>
4924
       <literal>PL</literal>, <literal>SG</literal>, and
4925
       <literal>TH</literal> are <productname>PostgreSQL</productname>
4926
       extensions. 
4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937
      </para>
     </listitem>

     <listitem>
      <para>
       <literal>V</literal> effectively
       multiplies the input values by
       <literal>10^<replaceable>n</replaceable></literal>, where
       <replaceable>n</replaceable> is the number of digits following
       <literal>V</literal>. 
       <function>to_char</function> does not support the use of
4938 4939
       <literal>V</literal> combined with a decimal point.
       (E.g., <literal>99.9V99</literal> is not allowed.)
4940 4941 4942
      </para>
     </listitem>
    </itemizedlist>
4943
   </para>   
4944

4945 4946 4947 4948 4949 4950
  <para>
   <xref linkend="functions-formatting-examples-table"> shows some
   examples of the use of the <function>to_char</function> function.
  </para>

    <table id="functions-formatting-examples-table">
4951
     <title><function>to_char</function> Examples</title>
4952 4953 4954
     <tgroup cols="2">
      <thead>
       <row>
4955 4956
        <entry>Expression</entry>
        <entry>Result</entry>
4957 4958 4959 4960
       </row>
      </thead>
      <tbody>
       <row>
4961 4962
        <entry><literal>to_char(current_timestamp, 'Day,&nbsp;DD&nbsp;&nbsp;HH12:MI:SS')</literal></entry>
        <entry><literal>'Tuesday&nbsp;&nbsp;,&nbsp;06&nbsp;&nbsp;05:39:18'</literal></entry>
4963
       </row>
4964
       <row>
4965 4966
        <entry><literal>to_char(current_timestamp, 'FMDay,&nbsp;FMDD&nbsp;&nbsp;HH12:MI:SS')</literal></entry>
        <entry><literal>'Tuesday,&nbsp;6&nbsp;&nbsp;05:39:18'</literal></entry>
4967 4968
       </row>          
       <row>
4969
        <entry><literal>to_char(-0.1, '99.99')</literal></entry>
B
Bruce Momjian 已提交
4970
        <entry><literal>'&nbsp;&nbsp;-.10'</literal></entry>
4971 4972
       </row>
       <row>
4973
        <entry><literal>to_char(-0.1, 'FM9.99')</literal></entry>
4974
        <entry><literal>'-.1'</literal></entry>
4975 4976
       </row>
       <row>
4977 4978
        <entry><literal>to_char(0.1, '0.9')</literal></entry>
        <entry><literal>'&nbsp;0.1'</literal></entry>
4979 4980
       </row>
       <row>
4981 4982
        <entry><literal>to_char(12, '9990999.9')</literal></entry>
        <entry><literal>'&nbsp;&nbsp;&nbsp;&nbsp;0012.0'</literal></entry>
4983 4984
       </row>
       <row>
4985
        <entry><literal>to_char(12, 'FM9990999.9')</literal></entry>
B
Bruce Momjian 已提交
4986
        <entry><literal>'0012.'</literal></entry>
4987 4988
       </row>
       <row>
4989 4990
        <entry><literal>to_char(485, '999')</literal></entry>
        <entry><literal>'&nbsp;485'</literal></entry>
4991 4992
       </row>
       <row>
4993
        <entry><literal>to_char(-485, '999')</literal></entry>
4994
        <entry><literal>'-485'</literal></entry>
4995 4996
       </row>
       <row>
4997 4998
        <entry><literal>to_char(485, '9&nbsp;9&nbsp;9')</literal></entry>
        <entry><literal>'&nbsp;4&nbsp;8&nbsp;5'</literal></entry>
4999 5000
       </row>
       <row>
5001 5002
        <entry><literal>to_char(1485, '9,999')</literal></entry>
        <entry><literal>'&nbsp;1,485'</literal></entry>
5003 5004
       </row>
       <row>
5005 5006
        <entry><literal>to_char(1485, '9G999')</literal></entry>
        <entry><literal>'&nbsp;1&nbsp;485'</literal></entry>
5007 5008
       </row>
       <row>
5009
        <entry><literal>to_char(148.5, '999.999')</literal></entry>
B
Bruce Momjian 已提交
5010
        <entry><literal>'&nbsp;148.500'</literal></entry>
5011
       </row>
B
Bruce Momjian 已提交
5012 5013 5014 5015 5016 5017 5018 5019
       <row>
        <entry><literal>to_char(148.5, 'FM999.999')</literal></entry>
        <entry><literal>'148.5'</literal></entry>
       </row>
       <row>
        <entry><literal>to_char(148.5, 'FM999.990')</literal></entry>
        <entry><literal>'148.500'</literal></entry>
       </row>
5020
       <row>
5021
        <entry><literal>to_char(148.5, '999D999')</literal></entry>
5022
        <entry><literal>'&nbsp;148,500'</literal></entry>        
5023 5024
       </row>
       <row>
5025 5026
        <entry><literal>to_char(3148.5, '9G999D999')</literal></entry>
        <entry><literal>'&nbsp;3&nbsp;148,500'</literal></entry>
5027 5028
       </row>
       <row>
5029
        <entry><literal>to_char(-485, '999S')</literal></entry>
5030
        <entry><literal>'485-'</literal></entry>
5031
       </row>
5032
       <row>            
5033
        <entry><literal>to_char(-485, '999MI')</literal></entry>
5034
        <entry><literal>'485-'</literal></entry>        
5035 5036
       </row>
       <row>
5037
        <entry><literal>to_char(485, '999MI')</literal></entry>
5038
        <entry><literal>'485&nbsp;'</literal></entry>           
B
Bruce Momjian 已提交
5039 5040 5041
       </row>
       <row>
        <entry><literal>to_char(485, 'FM999MI')</literal></entry>
5042
        <entry><literal>'485'</literal></entry>         
5043 5044
       </row>
       <row>
5045
        <entry><literal>to_char(485, 'PL999')</literal></entry>
5046
        <entry><literal>'+485'</literal></entry>        
5047
       </row>
5048
       <row>            
5049
        <entry><literal>to_char(485, 'SG999')</literal></entry>
5050
        <entry><literal>'+485'</literal></entry>        
5051 5052
       </row>
       <row>
5053
        <entry><literal>to_char(-485, 'SG999')</literal></entry>
5054
        <entry><literal>'-485'</literal></entry>        
5055 5056
       </row>
       <row>
5057
        <entry><literal>to_char(-485, '9SG99')</literal></entry>
5058
        <entry><literal>'4-85'</literal></entry>        
5059 5060
       </row>
       <row>
5061
        <entry><literal>to_char(-485, '999PR')</literal></entry>
5062
        <entry><literal>'&lt;485&gt;'</literal></entry>         
5063 5064
       </row>
       <row>
5065
        <entry><literal>to_char(485, 'L999')</literal></entry>
5066
        <entry><literal>'DM&nbsp;485</literal></entry>   
5067 5068
       </row>
       <row>
5069
        <entry><literal>to_char(485, 'RN')</literal></entry>            
5070
        <entry><literal>'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CDLXXXV'</literal></entry>
5071 5072
       </row>
       <row>
5073
        <entry><literal>to_char(485, 'FMRN')</literal></entry>  
5074
        <entry><literal>'CDLXXXV'</literal></entry>
5075 5076
       </row>
       <row>
5077
        <entry><literal>to_char(5.2, 'FMRN')</literal></entry>
5078
        <entry><literal>'V'</literal></entry>           
5079 5080
       </row>
       <row>
5081
        <entry><literal>to_char(482, '999th')</literal></entry>
5082
        <entry><literal>'&nbsp;482nd'</literal></entry>                         
5083 5084
       </row>
       <row>
5085 5086
        <entry><literal>to_char(485, '"Good&nbsp;number:"999')</literal></entry>
        <entry><literal>'Good&nbsp;number:&nbsp;485'</literal></entry>
5087 5088
       </row>
       <row>
5089 5090
        <entry><literal>to_char(485.8, '"Pre:"999"&nbsp;Post:"&nbsp;.999')</literal></entry>
        <entry><literal>'Pre:&nbsp;485&nbsp;Post:&nbsp;.800'</literal></entry>
5091 5092
       </row>
       <row>
5093
        <entry><literal>to_char(12, '99V999')</literal></entry>         
5094
        <entry><literal>'&nbsp;12000'</literal></entry>
5095 5096
       </row>
       <row>
5097 5098
        <entry><literal>to_char(12.4, '99V999')</literal></entry>
        <entry><literal>'&nbsp;12400'</literal></entry>
5099
       </row>
5100
       <row>            
5101
        <entry><literal>to_char(12.45, '99V9')</literal></entry>
5102
        <entry><literal>'&nbsp;125'</literal></entry>
5103 5104 5105 5106
       </row>
      </tbody>
     </tgroup>
    </table>
5107

5108 5109 5110
  </sect1>


5111
  <sect1 id="functions-datetime">
5112
   <title>Date/Time Functions and Operators</title>
5113

5114 5115 5116 5117 5118 5119 5120 5121
  <para>
   <xref linkend="functions-datetime-table"> shows the available
   functions for date/time value processing, with details appearing in
   the following subsections.  <xref
   linkend="operators-datetime-table"> illustrates the behaviors of
   the basic arithmetic operators (<literal>+</literal>,
   <literal>*</literal>, etc.).  For formatting functions, refer to
   <xref linkend="functions-formatting">.  You should be familiar with
5122 5123
   the background information on date/time data types from <xref
   linkend="datatype-datetime">.
5124 5125 5126
  </para>

  <para>
5127 5128 5129
   All the functions and operators described below that take <type>time</type> or <type>timestamp</type>
   inputs actually come in two variants: one that takes <type>time with time zone</type> or <type>timestamp
   with time zone</type>, and one that takes <type>time without time zone</type> or <type>timestamp without time zone</type>.
5130 5131 5132 5133
   For brevity, these variants are not shown separately.  Also, the
   <literal>+</> and <literal>*</> operators come in commutative pairs (for
   example both date + integer and integer + date); we show only one of each
   such pair.
5134
  </para>
5135 5136 5137 5138

    <table id="operators-datetime-table">
     <title>Date/Time Operators</title>

5139
     <tgroup cols="3">
5140 5141
      <thead>
       <row>
5142
        <entry>Operator</entry>
5143 5144 5145 5146 5147 5148 5149
        <entry>Example</entry>
        <entry>Result</entry>
       </row>
      </thead>

      <tbody>
       <row>
5150
        <entry> <literal>+</literal> </entry>
5151 5152
        <entry><literal>date '2001-09-28' + integer '7'</literal></entry>
        <entry><literal>date '2001-10-05'</literal></entry>
5153 5154 5155
       </row>

       <row>
5156
        <entry> <literal>+</literal> </entry>
5157
        <entry><literal>date '2001-09-28' + interval '1 hour'</literal></entry>
5158
        <entry><literal>timestamp '2001-09-28 01:00:00'</literal></entry>
5159 5160
       </row>

5161 5162 5163
       <row>
        <entry> <literal>+</literal> </entry>
        <entry><literal>date '2001-09-28' + time '03:00'</literal></entry>
5164
        <entry><literal>timestamp '2001-09-28 03:00:00'</literal></entry>
5165 5166 5167 5168 5169
       </row>

       <row>
        <entry> <literal>+</literal> </entry>
        <entry><literal>interval '1 day' + interval '1 hour'</literal></entry>
5170
        <entry><literal>interval '1 day 01:00:00'</literal></entry>
5171 5172 5173 5174 5175
       </row>

       <row>
        <entry> <literal>+</literal> </entry>
        <entry><literal>timestamp '2001-09-28 01:00' + interval '23 hours'</literal></entry>
5176
        <entry><literal>timestamp '2001-09-29 00:00:00'</literal></entry>
5177 5178
       </row>

5179
       <row>
5180
        <entry> <literal>+</literal> </entry>
5181
        <entry><literal>time '01:00' + interval '3 hours'</literal></entry>
5182
        <entry><literal>time '04:00:00'</literal></entry>
5183 5184 5185
       </row>

       <row>
5186
        <entry> <literal>-</literal> </entry>
5187
        <entry><literal>- interval '23 hours'</literal></entry>
5188
        <entry><literal>interval '-23:00:00'</literal></entry>
5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200
       </row>

       <row>
        <entry> <literal>-</literal> </entry>
        <entry><literal>date '2001-10-01' - date '2001-09-28'</literal></entry>
        <entry><literal>integer '3'</literal></entry>
       </row>

       <row>
        <entry> <literal>-</literal> </entry>
        <entry><literal>date '2001-10-01' - integer '7'</literal></entry>
        <entry><literal>date '2001-09-24'</literal></entry>
5201 5202 5203
       </row>

       <row>
5204
        <entry> <literal>-</literal> </entry>
5205
        <entry><literal>date '2001-09-28' - interval '1 hour'</literal></entry>
5206
        <entry><literal>timestamp '2001-09-27 23:00:00'</literal></entry>
5207 5208
       </row>

5209 5210 5211
       <row>
        <entry> <literal>-</literal> </entry>
        <entry><literal>time '05:00' - time '03:00'</literal></entry>
5212
        <entry><literal>interval '02:00:00'</literal></entry>
5213 5214
       </row>

5215
       <row>
5216
        <entry> <literal>-</literal> </entry>
5217
        <entry><literal>time '05:00' - interval '2 hours'</literal></entry>
5218
        <entry><literal>time '03:00:00'</literal></entry>
5219 5220
       </row>

5221 5222 5223
       <row>
        <entry> <literal>-</literal> </entry>
        <entry><literal>timestamp '2001-09-28 23:00' - interval '23 hours'</literal></entry>
5224
        <entry><literal>timestamp '2001-09-28 00:00:00'</literal></entry>
5225 5226 5227 5228 5229
       </row>

       <row>
        <entry> <literal>-</literal> </entry>
        <entry><literal>interval '1 day' - interval '1 hour'</literal></entry>
5230
        <entry><literal>interval '1 day -01:00:00'</literal></entry>
5231 5232 5233 5234 5235
       </row>

       <row>
        <entry> <literal>-</literal> </entry>
        <entry><literal>timestamp '2001-09-29 03:00' - timestamp '2001-09-27 12:00'</literal></entry>
5236
        <entry><literal>interval '1 day 15:00:00'</literal></entry>
5237 5238
       </row>

5239 5240
       <row>
        <entry> <literal>*</literal> </entry>
5241 5242 5243 5244
        <entry><literal>900 * interval '1 second'</literal></entry>
        <entry><literal>interval '00:15:00'</literal></entry>
       </row>

5245 5246 5247 5248 5249 5250
       <row>
        <entry> <literal>*</literal> </entry>
        <entry><literal>21 * interval '1 day'</literal></entry>
        <entry><literal>interval '21 days'</literal></entry>
       </row>

5251 5252 5253 5254
       <row>
        <entry> <literal>*</literal> </entry>
        <entry><literal>double precision '3.5' * interval '1 hour'</literal></entry>
        <entry><literal>interval '03:30:00'</literal></entry>
5255 5256 5257 5258
       </row>

       <row>
        <entry> <literal>/</literal> </entry>
5259
        <entry><literal>interval '1 hour' / double precision '1.5'</literal></entry>
5260
        <entry><literal>interval '00:40:00'</literal></entry>
5261 5262 5263 5264 5265
       </row>
      </tbody>
     </tgroup>
    </table>

5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308
   <indexterm>
    <primary>age</primary>
   </indexterm>
   <indexterm>
    <primary>current_date</primary>
   </indexterm>
   <indexterm>
    <primary>current_time</primary>
   </indexterm>
   <indexterm>
    <primary>current_timestamp</primary>
   </indexterm>
   <indexterm>
    <primary>date_part</primary>
   </indexterm>
   <indexterm>
    <primary>date_trunc</primary>
   </indexterm>
   <indexterm>
    <primary>extract</primary>
   </indexterm>
   <indexterm>
    <primary>isfinite</primary>
   </indexterm>
   <indexterm>
    <primary>justify_hours</primary>
   </indexterm>
   <indexterm>
    <primary>justify_days</primary>
   </indexterm>
   <indexterm>
    <primary>localtime</primary>
   </indexterm>
   <indexterm>
    <primary>localtimestamp</primary>
   </indexterm>
   <indexterm>
    <primary>now</primary>
   </indexterm>
   <indexterm>
    <primary>timeofday</primary>
   </indexterm>

5309
    <table id="functions-datetime-table">
5310
     <title>Date/Time Functions</title>
5311
     <tgroup cols="5">
5312 5313
      <thead>
       <row>
5314 5315 5316 5317 5318
        <entry>Function</entry>
        <entry>Return Type</entry>
        <entry>Description</entry>
        <entry>Example</entry>
        <entry>Result</entry>
5319 5320
       </row>
      </thead>
5321

5322 5323
      <tbody>
       <row>
5324 5325 5326 5327 5328 5329
        <entry><literal><function>age</function>(<type>timestamp</type>, <type>timestamp</type>)</literal></entry>
        <entry><type>interval</type></entry>
        <entry>Subtract arguments, producing a <quote>symbolic</> result that
        uses years and months</entry>
        <entry><literal>age(timestamp '2001-04-10', timestamp '1957-06-13')</literal></entry>
        <entry><literal>43 years 9 mons 27 days</literal></entry>
5330
       </row>
5331

5332
       <row>
5333 5334 5335 5336 5337
        <entry><literal><function>age</function>(<type>timestamp</type>)</literal></entry>
        <entry><type>interval</type></entry>
        <entry>Subtract from <function>current_date</function></entry>
        <entry><literal>age(timestamp '1957-06-13')</literal></entry>
        <entry><literal>43 years 8 mons 3 days</literal></entry>
5338 5339 5340
       </row>

       <row>
5341 5342 5343 5344 5345 5346
        <entry><literal><function>current_date</function></literal></entry>
        <entry><type>date</type></entry>
        <entry>Today's date; see <xref linkend="functions-datetime-current">
        </entry>
        <entry></entry>
        <entry></entry>
5347
       </row>
5348 5349

       <row>
5350
        <entry><literal><function>current_time</function></literal></entry>
5351
        <entry><type>time with time zone</type></entry>
5352
        <entry>Time of day; see <xref linkend="functions-datetime-current">
5353 5354 5355
        </entry>
        <entry></entry>
        <entry></entry>
5356 5357
       </row>

5358
       <row>
5359 5360 5361 5362 5363 5364
        <entry><literal><function>current_timestamp</function></literal></entry>
        <entry><type>timestamp with time zone</type></entry>
        <entry>Date and time; see <xref linkend="functions-datetime-current">
        </entry>
        <entry></entry>
        <entry></entry>
5365 5366 5367
       </row>

       <row>
5368 5369 5370 5371
        <entry><literal><function>date_part</function>(<type>text</type>, <type>timestamp</type>)</literal></entry>
        <entry><type>double precision</type></entry>
        <entry>Get subfield (equivalent to
         <function>extract</function>); see <xref linkend="functions-datetime-extract">
5372
        </entry>
5373 5374
        <entry><literal>date_part('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
        <entry><literal>20</literal></entry>
5375
       </row>
5376

5377
       <row>
5378 5379 5380 5381
        <entry><literal><function>date_part</function>(<type>text</type>, <type>interval</type>)</literal></entry>
        <entry><type>double precision</type></entry>
        <entry>Get subfield (equivalent to
         <function>extract</function>); see <xref linkend="functions-datetime-extract">
5382
        </entry>
5383 5384
        <entry><literal>date_part('month', interval '2 years 3 months')</literal></entry>
        <entry><literal>3</literal></entry>
5385
       </row>
5386

5387
       <row>
5388 5389
        <entry><literal><function>date_trunc</function>(<type>text</type>, <type>timestamp</type>)</literal></entry>
        <entry><type>timestamp</type></entry>
B
Bruce Momjian 已提交
5390
        <entry>Truncate to specified precision; see also <xref linkend="functions-datetime-trunc">
5391
        </entry>
5392 5393
        <entry><literal>date_trunc('hour', timestamp '2001-02-16 20:38:40')</literal></entry>
        <entry><literal>2001-02-16 20:00:00</literal></entry>
5394
       </row>
5395

5396
       <row>
5397
        <entry><literal><function>extract</function>(<parameter>field</parameter> from
5398
         <type>timestamp</type>)</literal></entry>
5399 5400
        <entry><type>double precision</type></entry>
        <entry>Get subfield; see <xref linkend="functions-datetime-extract">
5401
        </entry>
5402 5403
        <entry><literal>extract(hour from timestamp '2001-02-16 20:38:40')</literal></entry>
        <entry><literal>20</literal></entry>
5404
       </row>
5405 5406

       <row>
5407
        <entry><literal><function>extract</function>(<parameter>field</parameter> from
5408
         <type>interval</type>)</literal></entry>
5409 5410
        <entry><type>double precision</type></entry>
        <entry>Get subfield; see <xref linkend="functions-datetime-extract">
5411
        </entry>
5412 5413
        <entry><literal>extract(month from interval '2 years 3 months')</literal></entry>
        <entry><literal>3</literal></entry>
5414 5415
       </row>

5416
       <row>
5417 5418 5419 5420 5421
        <entry><literal><function>isfinite</function>(<type>timestamp</type>)</literal></entry>
        <entry><type>boolean</type></entry>
        <entry>Test for finite time stamp (not equal to infinity)</entry>
        <entry><literal>isfinite(timestamp '2001-02-16 21:28:30')</literal></entry>
        <entry><literal>true</literal></entry>
5422
       </row>
5423

5424
       <row>
5425 5426 5427 5428 5429
        <entry><literal><function>isfinite</function>(<type>interval</type>)</literal></entry>
        <entry><type>boolean</type></entry>
        <entry>Test for finite interval</entry>
        <entry><literal>isfinite(interval '4 hours')</literal></entry>
        <entry><literal>true</literal></entry>
5430
       </row>
5431

5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447
       <row>
        <entry><literal><function>justify_hours</function>(<type>interval</type>)</literal></entry>
        <entry><type>interval</type></entry>
        <entry>Adjust interval so 24-hour time periods are represented as days</entry>
        <entry><literal>justify_hours(interval '24 hours')</literal></entry>
        <entry><literal>1 day</literal></entry>
       </row>

       <row>
        <entry><literal><function>justify_days</function>(<type>interval</type>)</literal></entry>
        <entry><type>interval</type></entry>
        <entry>Adjust interval so 30-day time periods are represented as months</entry>
        <entry><literal>justify_days(interval '30 days')</literal></entry>
        <entry><literal>1 month</literal></entry>
       </row>

5448
       <row>
5449
        <entry><literal><function>localtime</function></literal></entry>
5450
        <entry><type>time</type></entry>
5451
        <entry>Time of day; see <xref linkend="functions-datetime-current">
5452 5453 5454 5455 5456 5457
        </entry>
        <entry></entry>
        <entry></entry>
       </row>

       <row>
5458
        <entry><literal><function>localtimestamp</function></literal></entry>
5459
        <entry><type>timestamp</type></entry>
5460
        <entry>Date and time; see <xref linkend="functions-datetime-current">
5461 5462 5463 5464 5465
        </entry>
        <entry></entry>
        <entry></entry>
       </row>

5466
       <row>
5467 5468 5469
        <entry><literal><function>now</function>()</literal></entry>
        <entry><type>timestamp with time zone</type></entry>
        <entry>Current date and time (equivalent to
B
Bruce Momjian 已提交
5470
         <function>current_timestamp</function>); see <xref linkend="functions-datetime-current">
5471 5472 5473
        </entry>
        <entry></entry>
        <entry></entry>
5474
       </row>
5475

5476
       <row>
N
Neil Conway 已提交
5477
        <entry><literal><function>timeofday</function>()</literal></entry>
5478
        <entry><type>text</type></entry>
B
Bruce Momjian 已提交
5479
        <entry>Current date and time; see <xref linkend="functions-datetime-current">
5480 5481 5482
        </entry>
        <entry></entry>
        <entry></entry>
5483 5484
       </row>

5485 5486 5487
      </tbody>
     </tgroup>
    </table>
5488

5489
   <para>
T
Tom Lane 已提交
5490 5491 5492 5493
    If you are using both <function>justify_hours</> and
    <function>justify_days</>, it is best to use <function>justify_hours</>
    first so any additional days will be included in the
    <function>justify_days</> calculation.
5494 5495
   </para>

5496
   <para>
5497
    In addition to these functions, the SQL <literal>OVERLAPS</> operator is
5498 5499
    supported:
<synopsis>
5500 5501
(<replaceable>start1</replaceable>, <replaceable>end1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>end2</replaceable>)
(<replaceable>start1</replaceable>, <replaceable>length1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>length2</replaceable>)
5502 5503 5504
</synopsis>
    This expression yields true when two time periods (defined by their
    endpoints) overlap, false when they do not overlap.  The endpoints
5505 5506
    can be specified as pairs of dates, times, or time stamps; or as
    a date, time, or time stamp followed by an interval.
5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517
   </para>

<screen>
SELECT (DATE '2001-02-16', DATE '2001-12-21') OVERLAPS
       (DATE '2001-10-30', DATE '2002-10-30');
<lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
SELECT (DATE '2001-02-16', INTERVAL '100 days') OVERLAPS
       (DATE '2001-10-30', DATE '2002-10-30');
<lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
</screen>

5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535
  <para>
   When adding an <type>interval</type> value to (or subtracting an 
   <type>interval</type> value from) a <type>timestamp with time zone</type> 
   value, the days component advances (or decrements) the date of the 
   <type>timestamp with time zone</type> by the indicated number of days. 
   Across daylight saving time changes (with the session time zone set to a 
   time zone that recognizes DST), this means <literal>interval '1 day'</literal> 
   does not necessarily equal <literal>interval '24 hours'</literal>. 
   For example, with the session time zone set to <literal>CST7CDT</literal>,
   <literal>timestamp with time zone '2005-04-02 12:00-07' + interval '1 day' </literal>
   will produce <literal>timestamp with time zone '2005-04-03 12:00-06'</literal>, 
   while adding <literal>interval '24 hours'</literal> to the same initial 
   <type>timestamp with time zone</type> produces
   <literal>timestamp with time zone '2005-04-03 13:00-06'</literal>, as there is
   a change in daylight saving time at <literal>2005-04-03 02:00</literal> in time zone 
   <literal>CST7CDT</literal>.
  </para>

5536 5537 5538
  <sect2 id="functions-datetime-extract">
   <title><function>EXTRACT</function>, <function>date_part</function></title>

5539 5540 5541 5542 5543 5544 5545
   <indexterm>
    <primary>date_part</primary>
   </indexterm>
   <indexterm>
    <primary>extract</primary>
   </indexterm>

5546
<synopsis>
5547
EXTRACT(<replaceable>field</replaceable> FROM <replaceable>source</replaceable>)
5548 5549 5550
</synopsis>

   <para>
5551
    The <function>extract</function> function retrieves subfields
T
Tom Lane 已提交
5552 5553 5554 5555
    such as year or hour from date/time values.
    <replaceable>source</replaceable> must be a value expression of
    type <type>timestamp</type>, <type>time</type>, or <type>interval</type>.
    (Expressions of type <type>date</type> will
5556
    be cast to <type>timestamp</type> and can therefore be used as
5557 5558
    well.)  <replaceable>field</replaceable> is an identifier or
    string that selects what field to extract from the source value.
5559 5560
    The <function>extract</function> function returns values of type
    <type>double precision</type>.
5561
    The following are valid field names:
5562 5563 5564 5565

    <!-- alphabetical -->
    <variablelist>
     <varlistentry>
5566
      <term><literal>century</literal></term>
5567 5568
      <listitem>
       <para>
5569
        The century
5570 5571 5572
       </para>

<screen>
5573
SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');
5574
<lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
5575 5576
SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>21</computeroutput>
5577 5578 5579
</screen>

       <para>
5580 5581 5582 5583 5584 5585 5586
        The first century starts at 0001-01-01 00:00:00 AD, although
        they did not know it at the time. This definition applies to all
        Gregorian calendar countries. There is no century number 0,
        you go from -1 to 1.

        If you disagree with this, please write your complaint to:
        Pope, Cathedral Saint-Peter of Roma, Vatican.
5587 5588 5589
       </para>

       <para>
5590 5591 5592
        <productname>PostgreSQL</productname> releases before 8.0 did not
        follow the conventional numbering of centuries, but just returned
        the year field divided by 100.
5593 5594 5595 5596 5597
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
5598
      <term><literal>day</literal></term>
5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611
      <listitem>
       <para>
        The day (of the month) field (1 - 31)
       </para>

<screen>
SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5612
      <term><literal>decade</literal></term>
5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625
      <listitem>
       <para>
        The year field divided by 10
       </para>

<screen>
SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>200</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5626
      <term><literal>dow</literal></term>
5627 5628 5629 5630 5631 5632 5633 5634 5635 5636
      <listitem>
       <para>
        The day of the week (0 - 6; Sunday is 0) (for
        <type>timestamp</type> values only)
       </para>

<screen>
SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>5</computeroutput>
</screen>
5637 5638 5639 5640 5641
       <para>
        Note that <function>extract</function>'s day of the week numbering is 
        different from that of the <function>to_char</function> function.
       </para>

5642 5643 5644 5645
      </listitem>
     </varlistentry>

     <varlistentry>
5646
      <term><literal>doy</literal></term>
5647 5648 5649 5650
      <listitem>
       <para>
        The day of the year (1 - 365/366) (for <type>timestamp</type> values only)
       </para>
5651

5652 5653 5654 5655 5656 5657 5658 5659
<screen>
SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>47</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5660
      <term><literal>epoch</literal></term>
5661 5662 5663
      <listitem>
       <para>
        For <type>date</type> and <type>timestamp</type> values, the
5664
        number of seconds since 1970-01-01 00:00:00-00 (can be negative);
5665
        for <type>interval</type> values, the total number
5666 5667 5668 5669
        of seconds in the interval
       </para>

<screen>
5670 5671
SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-08');
<lineannotation>Result: </lineannotation><computeroutput>982384720</computeroutput>
5672 5673 5674

SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
<lineannotation>Result: </lineannotation><computeroutput>442800</computeroutput>
5675 5676 5677 5678 5679 5680 5681 5682
</screen>

       <para>
        Here is how you can convert an epoch value back to a time
        stamp:
       </para>

<screen>
5683
SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 982384720 * INTERVAL '1 second';
5684 5685 5686 5687 5688
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5689
      <term><literal>hour</literal></term>
5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702
      <listitem>
       <para>
        The hour field (0 - 23)
       </para>

<screen>
SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5703
      <term><literal>microseconds</literal></term>
5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717
      <listitem>
       <para>
        The seconds field, including fractional parts, multiplied by 1
        000 000.  Note that this includes full seconds.
       </para>

<screen>
SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
<lineannotation>Result: </lineannotation><computeroutput>28500000</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5718
      <term><literal>millennium</literal></term>
5719 5720
      <listitem>
       <para>
5721
        The millennium
5722 5723 5724 5725
       </para>

<screen>
SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
5726
<lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
5727 5728 5729
</screen>

       <para>
5730 5731 5732 5733 5734 5735 5736 5737
        Years in the 1900s are in the second millennium.
        The third millennium starts January 1, 2001.
       </para>

       <para>
        <productname>PostgreSQL</productname> releases before 8.0 did not
        follow the conventional numbering of millennia, but just returned
        the year field divided by 1000.
5738 5739 5740 5741 5742
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
5743
      <term><literal>milliseconds</literal></term>
5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757
      <listitem>
       <para>
        The seconds field, including fractional parts, multiplied by
        1000.  Note that this includes full seconds.
       </para>

<screen>
SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
<lineannotation>Result: </lineannotation><computeroutput>28500</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5758
      <term><literal>minute</literal></term>
5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771
      <listitem>
       <para>
        The minutes field (0 - 59)
       </para>

<screen>
SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>38</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5772
      <term><literal>month</literal></term>
5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793
      <listitem>
       <para>
        For <type>timestamp</type> values, the number of the month
        within the year (1 - 12) ; for <type>interval</type> values
        the number of months, modulo 12 (0 - 11)
       </para>

<screen>
SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>

SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
<lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>

SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
<lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5794
      <term><literal>quarter</literal></term>
5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808
      <listitem>
       <para>
        The quarter of the year (1 - 4) that the day is in (for
        <type>timestamp</type> values only)
       </para>

<screen>
SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5809
      <term><literal>second</literal></term>
5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825
      <listitem>
       <para>
        The seconds field, including fractional parts (0 -
        59<footnote><simpara>60 if leap seconds are
        implemented by the operating system</simpara></footnote>)
       </para>

<screen>
SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>

SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
<lineannotation>Result: </lineannotation><computeroutput>28.5</computeroutput>
</screen>
      </listitem>
     </varlistentry>
5826 5827 5828 5829
     <varlistentry>
      <term><literal>timezone</literal></term>
      <listitem>
       <para>
5830
        The time zone offset from UTC, measured in seconds.  Positive values
5831 5832
        correspond to time zones east of UTC, negative values to
        zones west of UTC.
5833 5834 5835 5836 5837 5838 5839 5840
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><literal>timezone_hour</literal></term>
      <listitem>
       <para>
5841
        The hour component of the time zone offset
5842 5843 5844 5845 5846 5847 5848 5849
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><literal>timezone_minute</literal></term>
      <listitem>
       <para>
5850
        The minute component of the time zone offset
5851 5852 5853
       </para>
      </listitem>
     </varlistentry>
5854 5855

     <varlistentry>
5856
      <term><literal>week</literal></term>
5857 5858
      <listitem>
       <para>
5859
        The number of the week of the year that the day is in.  By definition
5860
        (<acronym>ISO</acronym> 8601), the first week of a year
5861
        contains January 4 of that year.  (The <acronym>ISO</acronym>-8601
5862
        week starts on Monday.)  In other words, the first Thursday of
5863
        a year is in week 1 of that year. (for <type>timestamp</type> values only)
5864
       </para>
5865 5866 5867 5868 5869 5870
       <para>
        Because of this, it is possible for early January dates to be part of the 
        52nd or 53rd week of the previous year.  For example, <literal>2005-01-01</>
        is part of the 53rd week of year 2004, and <literal>2006-01-01</> is part of 
        the 52nd week of year 2005.
       </para>
5871 5872 5873 5874 5875 5876 5877 5878 5879

<screen>
SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
</screen>
      </listitem>
     </varlistentry>

     <varlistentry>
5880
      <term><literal>year</literal></term>
5881 5882
      <listitem>
       <para>
5883 5884
        The year field.  Keep in mind there is no <literal>0 AD</>, so subtracting 
        <literal>BC</> years from <literal>AD</> years should be done with care.
5885 5886 5887 5888 5889 5890 5891 5892 5893 5894
       </para>

<screen>
SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>2001</computeroutput>
</screen>
      </listitem>
     </varlistentry>

    </variablelist>
5895 5896 5897
   </para>

   <para>
5898 5899 5900
    The <function>extract</function> function is primarily intended
    for computational processing.  For formatting date/time values for
    display, see <xref linkend="functions-formatting">.
5901
   </para>
5902 5903

   <para>
5904 5905
    The <function>date_part</function> function is modeled on the traditional
    <productname>Ingres</productname> equivalent to the
5906
    <acronym>SQL</acronym>-standard function <function>extract</function>:
5907 5908 5909
<synopsis>
date_part('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
</synopsis>
5910
    Note that here the <replaceable>field</replaceable> parameter needs to
5911
    be a string value, not a name.  The valid field names for
5912 5913 5914 5915 5916 5917 5918 5919
    <function>date_part</function> are the same as for
    <function>extract</function>.
   </para>

<screen>
SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
<lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>

T
Tatsuo Ishii 已提交
5920
SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
5921 5922 5923 5924 5925 5926 5927 5928
<lineannotation>Result: </lineannotation><computeroutput>4</computeroutput>
</screen>

  </sect2>

  <sect2 id="functions-datetime-trunc">
   <title><function>date_trunc</function></title>

5929 5930 5931 5932
   <indexterm>
    <primary>date_trunc</primary>
   </indexterm>

5933 5934 5935 5936 5937 5938 5939 5940 5941 5942
   <para>
    The function <function>date_trunc</function> is conceptually
    similar to the <function>trunc</function> function for numbers.
   </para>

   <para>
<synopsis>
date_trunc('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
</synopsis>
    <replaceable>source</replaceable> is a value expression of type
5943 5944 5945 5946
    <type>timestamp</type> or <type>interval</>.
    (Values of type <type>date</type> and
    <type>time</type> are cast automatically, to <type>timestamp</type> or
    <type>interval</> respectively.)
5947
    <replaceable>field</replaceable> selects to which precision to
5948 5949 5950
    truncate the input value.  The return value is of type
    <type>timestamp</type> or <type>interval</>
    with all fields that are less significant than the
5951 5952 5953 5954 5955 5956
    selected one set to zero (or one, for day and month).
   </para>

   <para>
    Valid values for <replaceable>field</replaceable> are:
    <simplelist>
5957 5958 5959 5960 5961 5962
     <member><literal>microseconds</literal></member>
     <member><literal>milliseconds</literal></member>
     <member><literal>second</literal></member>
     <member><literal>minute</literal></member>
     <member><literal>hour</literal></member>
     <member><literal>day</literal></member>
5963
     <member><literal>week</literal></member>
5964 5965 5966 5967 5968
     <member><literal>month</literal></member>
     <member><literal>year</literal></member>
     <member><literal>decade</literal></member>
     <member><literal>century</literal></member>
     <member><literal>millennium</literal></member>
5969 5970 5971
    </simplelist>
   </para>

5972 5973
   <para>
    Examples:
5974 5975
<screen>
SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
5976
<lineannotation>Result: </lineannotation><computeroutput>2001-02-16 20:00:00</computeroutput>
5977 5978

SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
5979
<lineannotation>Result: </lineannotation><computeroutput>2001-01-01 00:00:00</computeroutput>
5980
</screen>
5981
   </para>
5982 5983
  </sect2>

5984
  <sect2 id="functions-datetime-zoneconvert">
5985
   <title><literal>AT TIME ZONE</literal></title>
5986 5987

   <indexterm>
5988
    <primary>time zone</primary>
5989 5990 5991
    <secondary>conversion</secondary>
   </indexterm>

5992 5993 5994 5995
   <indexterm>
    <primary>AT TIME ZONE</primary>
   </indexterm>

5996
   <para>
5997 5998 5999 6000
    The <literal>AT TIME ZONE</literal> construct allows conversions
    of time stamps to different time zones.  <xref
    linkend="functions-datetime-zoneconvert-table"> shows its
    variants.
6001 6002 6003
   </para>

    <table id="functions-datetime-zoneconvert-table">
6004
     <title><literal>AT TIME ZONE</literal> Variants</title>
6005 6006 6007
     <tgroup cols="3">
      <thead>
       <row>
6008 6009 6010
        <entry>Expression</entry>
        <entry>Return Type</entry>
        <entry>Description</entry>
6011 6012 6013 6014 6015
       </row>
      </thead>

      <tbody>
       <row>
6016 6017 6018 6019
        <entry>
         <literal><type>timestamp without time zone</type> AT TIME ZONE <replaceable>zone</></literal>
        </entry>
        <entry><type>timestamp with time zone</type></entry>
6020
        <entry>Treat given time stamp <emphasis>without time zone</> as located in the specified time zone</entry>
6021 6022 6023
       </row>

       <row>
6024 6025 6026 6027
        <entry>
         <literal><type>timestamp with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
        </entry>
        <entry><type>timestamp without time zone</type></entry>
6028
        <entry>Convert given time stamp <emphasis>with time zone</> to the new time zone</entry>
6029 6030 6031
       </row>

       <row>
6032 6033 6034 6035
        <entry>
         <literal><type>time with time zone</type> AT TIME ZONE <replaceable>zone</></literal>
        </entry>
        <entry><type>time with time zone</type></entry>
6036
        <entry>Convert given time <emphasis>with time zone</> to the new time zone</entry>
6037 6038 6039 6040 6041 6042
       </row>
      </tbody>
     </tgroup>
    </table>

   <para>
6043
    In these expressions, the desired time zone <replaceable>zone</> can be
6044 6045
    specified either as a text string (e.g., <literal>'PST'</literal>)
    or as an interval (e.g., <literal>INTERVAL '-08:00'</literal>).
6046 6047 6048
    In the text case, the available zone names are those shown in either
    <xref linkend="datetime-timezone-set-table"> or
    <xref linkend="datetime-timezone-input-table">.
6049 6050 6051
   </para>

   <para>
6052
    Examples (supposing that the local time zone is <literal>PST8PDT</>):
6053 6054 6055 6056 6057 6058 6059
<screen>
SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'MST';
<lineannotation>Result: </lineannotation><computeroutput>2001-02-16 19:38:40-08</computeroutput>

SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'MST';
<lineannotation>Result: </lineannotation><computeroutput>2001-02-16 18:38:40</computeroutput>
</screen>
6060 6061 6062
    The first example takes a time stamp without time zone and interprets it as MST time
    (UTC-7), which is then converted to PST (UTC-8) for display.  The second example takes 
    a time stamp specified in EST (UTC-5) and converts it to local time in MST (UTC-7).
6063 6064 6065
   </para>

   <para>
6066 6067 6068 6069
    The function <literal><function>timezone</function>(<replaceable>zone</>,
    <replaceable>timestamp</>)</literal> is equivalent to the SQL-conforming construct
    <literal><replaceable>timestamp</> AT TIME ZONE
    <replaceable>zone</></literal>. 
6070 6071 6072
   </para>
  </sect2>

6073 6074 6075
  <sect2 id="functions-datetime-current">
   <title>Current Date/Time</title>

6076 6077 6078 6079 6080 6081 6082 6083 6084 6085
   <indexterm>
    <primary>date</primary>
    <secondary>current</secondary>
   </indexterm>

   <indexterm>
    <primary>time</primary>
    <secondary>current</secondary>
   </indexterm>

6086
   <para>
6087 6088
    The following functions are available to obtain the current date and/or
    time:
6089
<synopsis>
6090
CURRENT_DATE
6091
CURRENT_TIME
6092
CURRENT_TIMESTAMP
6093 6094
CURRENT_TIME (<replaceable>precision</replaceable>)
CURRENT_TIMESTAMP (<replaceable>precision</replaceable>)
6095 6096
LOCALTIME
LOCALTIMESTAMP
6097 6098
LOCALTIME (<replaceable>precision</replaceable>)
LOCALTIMESTAMP (<replaceable>precision</replaceable>)
6099
</synopsis>
6100 6101 6102 6103 6104 6105 6106 6107 6108 6109
    </para>

    <para>
     <function>CURRENT_TIME</function> and
     <function>CURRENT_TIMESTAMP</function> deliver values with time zone;
     <function>LOCALTIME</function> and
     <function>LOCALTIMESTAMP</function> deliver values without time zone.
    </para>

    <para>
6110 6111 6112 6113 6114 6115
     <function>CURRENT_TIME</function>,
     <function>CURRENT_TIMESTAMP</function>,
     <function>LOCALTIME</function>, and
     <function>LOCALTIMESTAMP</function>
     can optionally be given
     a precision parameter, which causes the result to be rounded
6116
     to that many fractional digits in the seconds field.  Without a precision parameter,
6117
     the result is given to the full available precision.
6118 6119
    </para>

6120 6121 6122 6123 6124 6125 6126
    <note>
     <para>
      Prior to <productname>PostgreSQL</productname> 7.2, the precision
      parameters were unimplemented, and the result was always given
      in integer seconds.
     </para>
    </note>
6127

6128 6129 6130
   <para>
    Some examples:
<screen>
6131
SELECT CURRENT_TIME;
6132
<lineannotation>Result: </lineannotation><computeroutput>14:39:53.662522-05</computeroutput>
6133 6134

SELECT CURRENT_DATE;
6135
<lineannotation>Result: </lineannotation><computeroutput>2001-12-23</computeroutput>
6136 6137

SELECT CURRENT_TIMESTAMP;
6138
<lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522-05</computeroutput>
6139 6140

SELECT CURRENT_TIMESTAMP(2);
6141
<lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.66-05</computeroutput>
6142 6143

SELECT LOCALTIMESTAMP;
6144
<lineannotation>Result: </lineannotation><computeroutput>2001-12-23 14:39:53.662522</computeroutput>
6145
</screen>
6146
   </para>
6147 6148 6149

   <para>
    The function <function>now()</function> is the traditional
6150
    <productname>PostgreSQL</productname> equivalent to
6151
    <function>CURRENT_TIMESTAMP</function>.
6152 6153 6154
   </para>

   <para>
6155
    It is important to know that
6156 6157
    <function>CURRENT_TIMESTAMP</function> and related functions return
    the start time of the current transaction; their values do not
6158 6159 6160 6161
    change during the transaction. This is considered a feature:
    the intent is to allow a single transaction to have a consistent
    notion of the <quote>current</quote> time, so that multiple
    modifications within the same transaction bear the same
6162
    time stamp.
6163 6164
   </para>

B
Bruce Momjian 已提交
6165
   <note>
6166 6167
    <para>
     Other database systems may advance these values more
B
Bruce Momjian 已提交
6168 6169
     frequently.
    </para>
6170 6171
   </note>

6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183
   <para>
    There is also the function <function>timeofday()</function> which
    returns the wall-clock time and advances during transactions.  For
    historical reasons <function>timeofday()</function> returns a
    <type>text</type> string rather than a <type>timestamp</type>
    value:
<screen>
SELECT timeofday();
<lineannotation>Result: </lineannotation><computeroutput>Sat Feb 17 19:07:32.000126 2001 EST</computeroutput>
</screen>
   </para>

6184
   <para>
6185
    All the date/time data types also accept the special literal value
6186
    <literal>now</literal> to specify the current date and time.  Thus,
6187
    the following three all return the same result:
6188 6189 6190
<programlisting>
SELECT CURRENT_TIMESTAMP;
SELECT now();
6191
SELECT TIMESTAMP 'now';  -- incorrect for use with DEFAULT
6192
</programlisting>
6193 6194
   </para>

T
Tom Lane 已提交
6195
    <tip>
6196
     <para>
6197 6198
      You do not want to use the third form when specifying a <literal>DEFAULT</>
      clause while creating a table.  The system will convert <literal>now</literal>
6199
      to a <type>timestamp</type> as soon as the constant is parsed, so that when
6200
      the default value is needed,
6201 6202
      the time of the table creation would be used!  The first two
      forms will not be evaluated until the default value is used,
6203 6204
      because they are function calls.  Thus they will give the desired
      behavior of defaulting to the time of row insertion.
6205
     </para>
T
Tom Lane 已提交
6206
    </tip>
6207
  </sect2>
6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257

  <sect2 id="functions-datetime-delay">
   <title>Delaying Execution</title>

   <indexterm>
    <primary>pg_sleep</primary>
   </indexterm>
   <indexterm>
    <primary>sleep</primary>
   </indexterm>
   <indexterm>
    <primary>delay</primary>
   </indexterm>

   <para>
    The following function is available to delay execution of the server
    process:
<synopsis>
pg_sleep(<replaceable>seconds</replaceable>)
</synopsis>

    <function>pg_sleep</function> makes the current session's process
    sleep until <replaceable>seconds</replaceable> seconds have
    elapsed.  <replaceable>seconds</replaceable> is a value of type
    <type>double precision</>, so fractional-second delays can be specified.
    For example:

<programlisting>
SELECT pg_sleep(1.5);
</programlisting>
   </para>

   <note>
     <para>
      The effective resolution of the sleep interval is platform-specific;
      0.01 seconds is a common value.  The sleep delay will be at least as long
      as specified. It may be longer depending on factors such as server load.
     </para>
   </note>

   <warning>
     <para>
      Make sure that your session does not hold more locks than necessary
      when calling <function>pg_sleep</function>.  Otherwise other sessions
      might have to wait for your sleeping process, slowing down the entire
      system.
     </para>
   </warning>
  </sect2>

6258
 </sect1>
6259 6260 6261

  
 <sect1 id="functions-geometry">
6262
  <title>Geometric Functions and Operators</title>
6263 6264

   <para>
6265 6266 6267
    The geometric types <type>point</type>, <type>box</type>,
    <type>lseg</type>, <type>line</type>, <type>path</type>,
    <type>polygon</type>, and <type>circle</type> have a large set of
6268 6269 6270 6271
    native support functions and operators, shown in <xref
    linkend="functions-geometry-op-table">, <xref
    linkend="functions-geometry-func-table">, and <xref
    linkend="functions-geometry-conv-table">.
6272 6273
   </para>

6274 6275 6276 6277 6278
   <caution>
    <para>
     Note that the <quote>same as</> operator, <literal>~=</>, represents
     the usual notion of equality for the <type>point</type>,
     <type>box</type>, <type>polygon</type>, and <type>circle</type> types.
6279 6280
     Some of these types also have an <literal>=</> operator, but
     <literal>=</> compares
6281 6282 6283 6284 6285
     for equal <emphasis>areas</> only.  The other scalar comparison operators
     (<literal>&lt;=</> and so on) likewise compare areas for these types.
    </para>
   </caution>

6286
   <table id="functions-geometry-op-table">
6287 6288 6289 6290
     <title>Geometric Operators</title>
     <tgroup cols="3">
      <thead>
       <row>
6291 6292 6293
        <entry>Operator</entry>
        <entry>Description</entry>
        <entry>Example</entry>
6294 6295 6296 6297
       </row>
      </thead>
      <tbody>
       <row>
6298 6299 6300
        <entry> <literal>+</literal> </entry>
        <entry>Translation</entry>
        <entry><literal>box '((0,0),(1,1))' + point '(2.0,0)'</literal></entry>
6301 6302
       </row>
       <row>
6303 6304 6305
        <entry> <literal>-</literal> </entry>
        <entry>Translation</entry>
        <entry><literal>box '((0,0),(1,1))' - point '(2.0,0)'</literal></entry>
6306 6307
       </row>
       <row>
6308 6309 6310
        <entry> <literal>*</literal> </entry>
        <entry>Scaling/rotation</entry>
        <entry><literal>box '((0,0),(1,1))' * point '(2.0,0)'</literal></entry>
6311 6312
       </row>
       <row>
6313 6314 6315
        <entry> <literal>/</literal> </entry>
        <entry>Scaling/rotation</entry>
        <entry><literal>box '((0,0),(2,2))' / point '(2.0,0)'</literal></entry>
6316 6317
       </row>
       <row>
6318 6319 6320
        <entry> <literal>#</literal> </entry>
        <entry>Point or box of intersection</entry>
        <entry><literal>'((1,-1),(-1,1))' # '((1,1),(-1,-1))'</literal></entry>
6321 6322
       </row>
       <row>
6323 6324 6325
        <entry> <literal>#</literal> </entry>
        <entry>Number of points in path or polygon</entry>
        <entry><literal># '((1,0),(0,1),(-1,0))'</literal></entry>
6326
       </row>
6327
       <row>
6328 6329 6330
        <entry> <literal>@-@</literal> </entry>
        <entry>Length or circumference</entry>
        <entry><literal>@-@ path '((0,0),(1,0))'</literal></entry>
6331 6332
       </row>
       <row>
6333 6334 6335
        <entry> <literal>@@</literal> </entry>
        <entry>Center</entry>
        <entry><literal>@@ circle '((0,0),10)'</literal></entry>
6336
       </row>
6337
       <row>
6338 6339 6340
        <entry> <literal>##</literal> </entry>
        <entry>Closest point to first operand on second operand</entry>
        <entry><literal>point '(0,0)' ## lseg '((2,0),(0,2))'</literal></entry>
6341
       </row>
6342
       <row>
6343 6344 6345
        <entry> <literal>&lt;-&gt;</literal> </entry>
        <entry>Distance between</entry>
        <entry><literal>circle '((0,0),1)' &lt;-&gt; circle '((5,0),1)'</literal></entry>
6346
       </row>
6347
       <row>
6348 6349 6350
        <entry> <literal>&amp;&amp;</literal> </entry>
        <entry>Overlaps?</entry>
        <entry><literal>box '((0,0),(1,1))' &amp;&amp; box '((0,0),(2,2))'</literal></entry>
6351
       </row>
6352 6353 6354 6355 6356 6357 6358 6359 6360 6361
       <row>
        <entry> <literal>&lt;&lt;</literal> </entry>
        <entry>Is strictly left of?</entry>
        <entry><literal>circle '((0,0),1)' &lt;&lt; circle '((5,0),1)'</literal></entry>
       </row>
       <row>
        <entry> <literal>&gt;&gt;</literal> </entry>
        <entry>Is strictly right of?</entry>
        <entry><literal>circle '((5,0),1)' &gt;&gt; circle '((0,0),1)'</literal></entry>
       </row>
6362
       <row>
6363 6364 6365
        <entry> <literal>&amp;&lt;</literal> </entry>
        <entry>Does not extend to the right of?</entry>
        <entry><literal>box '((0,0),(1,1))' &amp;&lt; box '((0,0),(2,2))'</literal></entry>
6366 6367
       </row>
       <row>
6368 6369 6370
        <entry> <literal>&amp;&gt;</literal> </entry>
        <entry>Does not extend to the left of?</entry>
        <entry><literal>box '((0,0),(3,3))' &amp;&gt; box '((0,0),(2,2))'</literal></entry>
6371 6372
       </row>
       <row>
6373 6374 6375
        <entry> <literal>&lt;&lt;|</literal> </entry>
        <entry>Is strictly below?</entry>
        <entry><literal>box '((0,0),(3,3))' &lt;&lt;| box '((3,4),(5,5))'</literal></entry>
6376 6377
       </row>
       <row>
6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390
        <entry> <literal>|&gt;&gt;</literal> </entry>
        <entry>Is strictly above?</entry>
        <entry><literal>box '((3,4),(5,5))' |&gt;&gt; box '((0,0),(3,3))'</literal></entry>
       </row>
       <row>
        <entry> <literal>&amp;&lt;|</literal> </entry>
        <entry>Does not extend above?</entry>
        <entry><literal>box '((0,0),(1,1))' &amp;&lt;| box '((0,0),(2,2))'</literal></entry>
       </row>
       <row>
        <entry> <literal>|&amp;&gt;</literal> </entry>
        <entry>Does not extend below?</entry>
        <entry><literal>box '((0,0),(3,3))' |&amp;&gt; box '((0,0),(2,2))'</literal></entry>
6391
       </row>
6392
       <row>
6393
        <entry> <literal>&lt;^</literal> </entry>
6394
        <entry>Is below (allows touching)?</entry>
6395
        <entry><literal>circle '((0,0),1)' &lt;^ circle '((0,5),1)'</literal></entry>
6396
       </row>
6397
       <row>
6398
        <entry> <literal>&gt;^</literal> </entry>
6399
        <entry>Is above (allows touching)?</entry>
6400
        <entry><literal>circle '((0,5),1)' &gt;^ circle '((0,0),1)'</literal></entry>
6401 6402
       </row>
       <row>
6403 6404 6405
        <entry> <literal>?#</literal> </entry>
        <entry>Intersects?</entry>
        <entry><literal>lseg '((-1,0),(1,0))' ?# box '((-2,-2),(2,2))'</literal></entry>
6406 6407
       </row>
       <row>
6408 6409 6410
        <entry> <literal>?-</literal> </entry>
        <entry>Is horizontal?</entry>
        <entry><literal>?- lseg '((-1,0),(1,0))'</literal></entry>
6411 6412
       </row>
       <row>
6413 6414 6415
        <entry> <literal>?-</literal> </entry>
        <entry>Are horizontally aligned?</entry>
        <entry><literal>point '(1,0)' ?- point '(0,0)'</literal></entry>
6416 6417
       </row>
       <row>
6418 6419 6420
        <entry> <literal>?|</literal> </entry>
        <entry>Is vertical?</entry>
        <entry><literal>?| lseg '((-1,0),(1,0))'</literal></entry>
6421 6422
       </row>
       <row>
6423 6424 6425
        <entry> <literal>?|</literal> </entry>
        <entry>Are vertically aligned?</entry>
        <entry><literal>point '(0,1)' ?| point '(0,0)'</literal></entry>
6426
       </row>
6427
       <row>
6428 6429 6430
        <entry> <literal>?-|</literal> </entry>
        <entry>Is perpendicular?</entry>
        <entry><literal>lseg '((0,0),(0,1))' ?-| lseg '((0,0),(1,0))'</literal></entry>
6431
       </row>
6432
       <row>
6433 6434 6435
        <entry> <literal>?||</literal> </entry>
        <entry>Are parallel?</entry>
        <entry><literal>lseg '((-1,0),(1,0))' ?|| lseg '((-1,2),(1,2))'</literal></entry>
6436 6437
       </row>
       <row>
6438 6439 6440
        <entry> <literal>~</literal> </entry>
        <entry>Contains?</entry>
        <entry><literal>circle '((0,0),2)' ~ point '(1,1)'</literal></entry>
6441 6442
       </row>
       <row>
6443 6444 6445
        <entry> <literal>@</literal> </entry>
        <entry>Contained in or on?</entry>
        <entry><literal>point '(1,1)' @ circle '((0,0),2)'</literal></entry>
6446 6447
       </row>
       <row>
6448 6449 6450
        <entry> <literal>~=</literal> </entry>
        <entry>Same as?</entry>
        <entry><literal>polygon '((0,0),(1,1))' ~= polygon '((1,1),(0,0))'</literal></entry>
6451 6452 6453 6454
       </row>
      </tbody>
     </tgroup>
   </table>
6455

6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491
   <indexterm>
    <primary>area</primary>
   </indexterm>
   <indexterm>
    <primary>center</primary>
   </indexterm>
   <indexterm>
    <primary>diameter</primary>
   </indexterm>
   <indexterm>
    <primary>height</primary>
   </indexterm>
   <indexterm>
    <primary>isclosed</primary>
   </indexterm>
   <indexterm>
    <primary>isopen</primary>
   </indexterm>
   <indexterm>
    <primary>length</primary>
   </indexterm>
   <indexterm>
    <primary>npoints</primary>
   </indexterm>
   <indexterm>
    <primary>pclose</primary>
   </indexterm>
   <indexterm>
    <primary>popen</primary>
   </indexterm>
   <indexterm>
    <primary>radius</primary>
   </indexterm>
   <indexterm>
    <primary>width</primary>
   </indexterm>
6492 6493

   <table id="functions-geometry-func-table">
T
Thomas G. Lockhart 已提交
6494 6495 6496 6497
     <title>Geometric Functions</title>
     <tgroup cols="4">
      <thead>
       <row>
6498 6499 6500 6501
        <entry>Function</entry>
        <entry>Return Type</entry>
        <entry>Description</entry>
        <entry>Example</entry>
T
Thomas G. Lockhart 已提交
6502 6503 6504 6505
       </row>
      </thead>
      <tbody>
       <row>
6506 6507 6508 6509
        <entry><literal><function>area</function>(<replaceable>object</>)</literal></entry>
        <entry><type>double precision</type></entry>
        <entry>area</entry>
        <entry><literal>area(box '((0,0),(1,1))')</literal></entry>
T
Thomas G. Lockhart 已提交
6510 6511
       </row>
       <row>
6512 6513 6514 6515
        <entry><literal><function>center</function>(<replaceable>object</>)</literal></entry>
        <entry><type>point</type></entry>
        <entry>center</entry>
        <entry><literal>center(box '((0,0),(1,2))')</literal></entry>
T
Thomas G. Lockhart 已提交
6516 6517
       </row>
       <row>
6518 6519 6520 6521
        <entry><literal><function>diameter</function>(<type>circle</>)</literal></entry>
        <entry><type>double precision</type></entry>
        <entry>diameter of circle</entry>
        <entry><literal>diameter(circle '((0,0),2.0)')</literal></entry>
T
Thomas G. Lockhart 已提交
6522 6523
       </row>
       <row>
6524 6525 6526 6527
        <entry><literal><function>height</function>(<type>box</>)</literal></entry>
        <entry><type>double precision</type></entry>
        <entry>vertical size of box</entry>
        <entry><literal>height(box '((0,0),(1,1))')</literal></entry>
T
Thomas G. Lockhart 已提交
6528 6529
       </row>
       <row>
6530 6531 6532 6533
        <entry><literal><function>isclosed</function>(<type>path</>)</literal></entry>
        <entry><type>boolean</type></entry>
        <entry>a closed path?</entry>
        <entry><literal>isclosed(path '((0,0),(1,1),(2,0))')</literal></entry>
T
Thomas G. Lockhart 已提交
6534 6535
       </row>
       <row>
6536 6537 6538 6539
        <entry><literal><function>isopen</function>(<type>path</>)</literal></entry>
        <entry><type>boolean</type></entry>
        <entry>an open path?</entry>
        <entry><literal>isopen(path '[(0,0),(1,1),(2,0)]')</literal></entry>
T
Thomas G. Lockhart 已提交
6540 6541
       </row>
       <row>
6542 6543 6544 6545
        <entry><literal><function>length</function>(<replaceable>object</>)</literal></entry>
        <entry><type>double precision</type></entry>
        <entry>length</entry>
        <entry><literal>length(path '((-1,0),(1,0))')</literal></entry>
T
Thomas G. Lockhart 已提交
6546
       </row>
6547
       <row>
6548
        <entry><literal><function>npoints</function>(<type>path</>)</literal></entry>
6549
        <entry><type>int</type></entry>
6550 6551
        <entry>number of points</entry>
        <entry><literal>npoints(path '[(0,0),(1,1),(2,0)]')</literal></entry>
6552 6553
       </row>
       <row>
6554
        <entry><literal><function>npoints</function>(<type>polygon</>)</literal></entry>
6555
        <entry><type>int</type></entry>
6556 6557
        <entry>number of points</entry>
        <entry><literal>npoints(polygon '((1,1),(0,0))')</literal></entry>
6558
       </row>
T
Thomas G. Lockhart 已提交
6559
       <row>
6560 6561 6562 6563
        <entry><literal><function>pclose</function>(<type>path</>)</literal></entry>
        <entry><type>path</type></entry>
        <entry>convert path to closed</entry>
        <entry><literal>pclose(path '[(0,0),(1,1),(2,0)]')</literal></entry>
T
Thomas G. Lockhart 已提交
6564
       </row>
6565 6566
<![IGNORE[
<!-- Not defined by this name. Implements the intersection operator '#' -->
T
Thomas G. Lockhart 已提交
6567
       <row>
6568 6569 6570 6571
        <entry><literal><function>point</function>(<type>lseg</>, <type>lseg</>)</literal></entry>
        <entry><type>point</type></entry>
        <entry>intersection</entry>
        <entry><literal>point(lseg '((-1,0),(1,0))',lseg '((-2,-2),(2,2))')</literal></entry>
T
Thomas G. Lockhart 已提交
6572
       </row>
6573
]]>
T
Thomas G. Lockhart 已提交
6574
       <row>
6575 6576 6577 6578
        <entry><literal><function>popen</function>(<type>path</>)</literal></entry>
        <entry><type>path</type></entry>
        <entry>convert path to open</entry>
        <entry><literal>popen(path '((0,0),(1,1),(2,0))')</literal></entry>
T
Thomas G. Lockhart 已提交
6579 6580
       </row>
       <row>
6581 6582 6583 6584
        <entry><literal><function>radius</function>(<type>circle</type>)</literal></entry>
        <entry><type>double precision</type></entry>
        <entry>radius of circle</entry>
        <entry><literal>radius(circle '((0,0),2.0)')</literal></entry>
T
Thomas G. Lockhart 已提交
6585 6586
       </row>
       <row>
6587 6588 6589 6590
        <entry><literal><function>width</function>(<type>box</>)</literal></entry>
        <entry><type>double precision</type></entry>
        <entry>horizontal size of box</entry>
        <entry><literal>width(box '((0,0),(1,1))')</literal></entry>
T
Thomas G. Lockhart 已提交
6591 6592 6593
       </row>
      </tbody>
     </tgroup>
6594
   </table>
6595

6596
   <table id="functions-geometry-conv-table">
T
Thomas G. Lockhart 已提交
6597 6598 6599 6600
     <title>Geometric Type Conversion Functions</title>
     <tgroup cols="4">
      <thead>
       <row>
6601 6602 6603 6604
        <entry>Function</entry>
        <entry>Return Type</entry>
        <entry>Description</entry>
        <entry>Example</entry>
T
Thomas G. Lockhart 已提交
6605 6606 6607 6608
       </row>
      </thead>
      <tbody>
       <row>
6609 6610 6611 6612
        <entry><literal><function>box</function>(<type>circle</type>)</literal></entry>
        <entry><type>box</type></entry>
        <entry>circle to box</entry>
        <entry><literal>box(circle '((0,0),2.0)')</literal></entry>
T
Thomas G. Lockhart 已提交
6613 6614
       </row>
       <row>
6615 6616 6617 6618
        <entry><literal><function>box</function>(<type>point</type>, <type>point</type>)</literal></entry>
        <entry><type>box</type></entry>
        <entry>points to box</entry>
        <entry><literal>box(point '(0,0)', point '(1,1)')</literal></entry>
T
Thomas G. Lockhart 已提交
6619 6620
       </row>
       <row>
6621 6622 6623 6624
        <entry><literal><function>box</function>(<type>polygon</type>)</literal></entry>
        <entry><type>box</type></entry>
        <entry>polygon to box</entry>
        <entry><literal>box(polygon '((0,0),(1,1),(2,0))')</literal></entry>
T
Thomas G. Lockhart 已提交
6625 6626
       </row>
       <row>
6627 6628 6629 6630
        <entry><literal><function>circle</function>(<type>box</type>)</literal></entry>
        <entry><type>circle</type></entry>
        <entry>box to circle</entry>
        <entry><literal>circle(box '((0,0),(1,1))')</literal></entry>
T
Thomas G. Lockhart 已提交
6631 6632
       </row>
       <row>
6633 6634
        <entry><literal><function>circle</function>(<type>point</type>, <type>double precision</type>)</literal></entry>
        <entry><type>circle</type></entry>
6635
        <entry>center and radius to circle</entry>
6636
        <entry><literal>circle(point '(0,0)', 2.0)</literal></entry>
T
Thomas G. Lockhart 已提交
6637
       </row>
6638 6639 6640 6641 6642 6643
       <row>
        <entry><literal><function>circle</function>(<type>polygon</type>)</literal></entry>
        <entry><type>circle</type></entry>
        <entry>polygon to circle</entry>
        <entry><literal>circle(polygon '((0,0),(1,1),(2,0))')</literal></entry>
       </row>
T
Thomas G. Lockhart 已提交
6644
       <row>
6645 6646 6647 6648
        <entry><literal><function>lseg</function>(<type>box</type>)</literal></entry>
        <entry><type>lseg</type></entry>
        <entry>box diagonal to line segment</entry>
        <entry><literal>lseg(box '((-1,0),(1,0))')</literal></entry>
T
Thomas G. Lockhart 已提交
6649 6650
       </row>
       <row>
6651 6652 6653 6654
        <entry><literal><function>lseg</function>(<type>point</type>, <type>point</type>)</literal></entry>
        <entry><type>lseg</type></entry>
        <entry>points to line segment</entry>
        <entry><literal>lseg(point '(-1,0)', point '(1,0)')</literal></entry>
T
Thomas G. Lockhart 已提交
6655 6656
       </row>
       <row>
6657 6658 6659 6660
        <entry><literal><function>path</function>(<type>polygon</type>)</literal></entry>
        <entry><type>point</type></entry>
        <entry>polygon to path</entry>
        <entry><literal>path(polygon '((0,0),(1,1),(2,0))')</literal></entry>
T
Thomas G. Lockhart 已提交
6661
       </row>
6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674
       <row>
        <entry><literal><function>point</function>(<type>double
         precision</type>, <type>double precision</type>)</literal></entry>
        <entry><type>point</type></entry>
        <entry>construct point</entry>
        <entry><literal>point(23.4, -44.5)</literal></entry>
       </row>
       <row>
        <entry><literal><function>point</function>(<type>box</type>)</literal></entry>
        <entry><type>point</type></entry>
        <entry>center of box</entry>
        <entry><literal>point(box '((-1,0),(1,0))')</literal></entry>
       </row>
T
Thomas G. Lockhart 已提交
6675
       <row>
6676 6677 6678 6679
        <entry><literal><function>point</function>(<type>circle</type>)</literal></entry>
        <entry><type>point</type></entry>
        <entry>center of circle</entry>
        <entry><literal>point(circle '((0,0),2.0)')</literal></entry>
T
Thomas G. Lockhart 已提交
6680
       </row>
6681 6682 6683
       <row>
        <entry><literal><function>point</function>(<type>lseg</type>)</literal></entry>
        <entry><type>point</type></entry>
6684
        <entry>center of line segment</entry>
6685 6686
        <entry><literal>point(lseg '((-1,0),(1,0))')</literal></entry>
       </row>
T
Thomas G. Lockhart 已提交
6687
       <row>
6688 6689 6690 6691
        <entry><literal><function>point</function>(<type>polygon</type>)</literal></entry>
        <entry><type>point</type></entry>
        <entry>center of polygon</entry>
        <entry><literal>point(polygon '((0,0),(1,1),(2,0))')</literal></entry>
T
Thomas G. Lockhart 已提交
6692 6693
       </row>
       <row>
6694 6695 6696 6697
        <entry><literal><function>polygon</function>(<type>box</type>)</literal></entry>
        <entry><type>polygon</type></entry>
        <entry>box to 4-point polygon</entry>
        <entry><literal>polygon(box '((0,0),(1,1))')</literal></entry>
T
Thomas G. Lockhart 已提交
6698 6699
       </row>
       <row>
6700 6701 6702 6703
        <entry><literal><function>polygon</function>(<type>circle</type>)</literal></entry>
        <entry><type>polygon</type></entry>
        <entry>circle to 12-point polygon</entry>
        <entry><literal>polygon(circle '((0,0),2.0)')</literal></entry>
T
Thomas G. Lockhart 已提交
6704 6705
       </row>
       <row>
6706 6707 6708 6709
        <entry><literal><function>polygon</function>(<replaceable class="parameter">npts</replaceable>, <type>circle</type>)</literal></entry>
        <entry><type>polygon</type></entry>
        <entry>circle to <replaceable class="parameter">npts</replaceable>-point polygon</entry>
        <entry><literal>polygon(12, circle '((0,0),2.0)')</literal></entry>
T
Thomas G. Lockhart 已提交
6710 6711
       </row>
       <row>
6712 6713 6714 6715
        <entry><literal><function>polygon</function>(<type>path</type>)</literal></entry>
        <entry><type>polygon</type></entry>
        <entry>path to polygon</entry>
        <entry><literal>polygon(path '((0,0),(1,1),(2,0))')</literal></entry>
T
Thomas G. Lockhart 已提交
6716 6717 6718
       </row>
      </tbody>
     </tgroup>
6719 6720
   </table>

6721 6722
    <para>
     It is possible to access the two component numbers of a <type>point</>
6723
     as though it were an array with indices 0 and 1.  For example, if
6724
     <literal>t.p</> is a <type>point</> column then
6725
     <literal>SELECT p[0] FROM t</> retrieves the X coordinate and
6726
     <literal>UPDATE t SET p[1] = ...</> changes the Y coordinate.
6727 6728
     In the same way, a value of type <type>box</> or <type>lseg</> may be treated
     as an array of two <type>point</> values.
6729 6730
    </para>

6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746
    <para>
     The <function>area</function> function works for the types
     <type>box</type>, <type>circle</type>, and <type>path</type>.
     The <function>area</function> function only works on the
     <type>path</type> data type if the points in the
     <type>path</type> are non-intersecting.  For example, the
     <type>path</type>
     <literal>'((0,0),(0,1),(2,1),(2,2),(1,2),(1,0),(0,0))'::PATH</literal>
     won't work, however, the following visually identical
     <type>path</type>
     <literal>'((0,0),(0,1),(1,1),(1,2),(2,2),(2,1),(1,1),(1,0),(0,0))'::PATH</literal>
     will work.  If the concept of an intersecting versus
     non-intersecting <type>path</type> is confusing, draw both of the
     above <type>path</type>s side by side on a piece of graph paper.
    </para>

6747
  </sect1>
6748

6749

6750
 <sect1 id="functions-net">
6751
  <title>Network Address Functions and Operators</title>
6752

6753 6754
  <para>
   <xref linkend="cidr-inet-operators-table"> shows the operators
6755
   available for the <type>cidr</type> and <type>inet</type> types.
6756
   The operators <literal>&lt;&lt;</literal>,
6757 6758
   <literal>&lt;&lt;=</literal>, <literal>&gt;&gt;</literal>, and
   <literal>&gt;&gt;=</literal> test for subnet inclusion.  They
6759 6760 6761 6762
   consider only the network parts of the two addresses, ignoring any
   host part, and determine whether one network part is identical to
   or a subnet of the other.
  </para>
6763

6764
    <table id="cidr-inet-operators-table">
6765 6766 6767 6768
     <title><type>cidr</type> and <type>inet</type> Operators</title>
     <tgroup cols="3">
      <thead>
       <row>
6769 6770 6771
        <entry>Operator</entry>
        <entry>Description</entry>
        <entry>Example</entry>
6772 6773 6774 6775
       </row>
      </thead>
      <tbody>
       <row>
6776 6777 6778
        <entry> <literal>&lt;</literal> </entry>
        <entry>is less than</entry>
        <entry><literal>inet '192.168.1.5' &lt; inet '192.168.1.6'</literal></entry>
6779 6780
       </row>
       <row>
6781 6782 6783
        <entry> <literal>&lt;=</literal> </entry>
        <entry>is less than or equal</entry>
        <entry><literal>inet '192.168.1.5' &lt;= inet '192.168.1.5'</literal></entry>
6784 6785
       </row>
       <row>
6786 6787 6788
        <entry> <literal>=</literal> </entry>
        <entry>equals</entry>
        <entry><literal>inet '192.168.1.5' = inet '192.168.1.5'</literal></entry>
6789 6790
       </row>
       <row>
6791 6792 6793
        <entry> <literal>&gt;=</literal> </entry>
        <entry>is greater or equal</entry>
        <entry><literal>inet '192.168.1.5' &gt;= inet '192.168.1.5'</literal></entry>
6794 6795
       </row>
       <row>
6796 6797 6798
        <entry> <literal>&gt;</literal> </entry>
        <entry>is greater than</entry>
        <entry><literal>inet '192.168.1.5' &gt; inet '192.168.1.4'</literal></entry>
6799 6800
       </row>
       <row>
6801 6802 6803
        <entry> <literal>&lt;&gt;</literal> </entry>
        <entry>is not equal</entry>
        <entry><literal>inet '192.168.1.5' &lt;&gt; inet '192.168.1.4'</literal></entry>
6804 6805
       </row>
       <row>
6806 6807 6808
        <entry> <literal>&lt;&lt;</literal> </entry>
        <entry>is contained within</entry>
        <entry><literal>inet '192.168.1.5' &lt;&lt; inet '192.168.1/24'</literal></entry>
6809 6810
       </row>
       <row>
6811 6812 6813
        <entry> <literal>&lt;&lt;=</literal> </entry>
        <entry>is contained within or equals</entry>
        <entry><literal>inet '192.168.1/24' &lt;&lt;= inet '192.168.1/24'</literal></entry>
6814 6815
       </row>
       <row>
6816 6817 6818
        <entry> <literal>&gt;&gt;</literal> </entry>
        <entry>contains</entry>
        <entry><literal>inet '192.168.1/24' &gt;&gt; inet '192.168.1.5'</literal></entry>
6819 6820
       </row>
       <row>
6821 6822 6823
        <entry> <literal>&gt;&gt;=</literal> </entry>
        <entry>contains or equals</entry>
        <entry><literal>inet '192.168.1/24' &gt;&gt;= inet '192.168.1/24'</literal></entry>
6824
       </row>
6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854
       <row>
        <entry> <literal>~</literal> </entry>
        <entry>bitwise NOT</entry>
        <entry><literal>~ inet '192.168.1.6'</literal></entry>
       </row>
       <row>
        <entry> <literal>&amp;</literal> </entry>
        <entry>bitwise AND</entry>
        <entry><literal>inet '192.168.1.6' &amp; inet '0.0.0.255'</literal></entry>
       </row>
       <row>
        <entry> <literal>|</literal> </entry>
        <entry>bitwise OR</entry>
        <entry><literal>inet '192.168.1.6' | inet '0.0.0.255'</literal></entry>
       </row>
       <row>
        <entry> <literal>+</literal> </entry>
        <entry>addition</entry>
        <entry><literal>inet '192.168.1.6' + 25</literal></entry>
       </row>
       <row>
        <entry> <literal>-</literal> </entry>
        <entry>subtraction</entry>
        <entry><literal>inet '192.168.1.43' - 36</literal></entry>
       </row>
       <row>
        <entry> <literal>-</literal> </entry>
        <entry>subtraction</entry>
        <entry><literal>inet '192.168.1.43' - inet '192.168.1.19'</literal></entry>
       </row>
6855 6856 6857
      </tbody>
     </tgroup>
    </table>
6858

6859 6860
  <para>
   <xref linkend="cidr-inet-functions-table"> shows the functions
6861 6862 6863
   available for use with the <type>cidr</type> and <type>inet</type>
   types.  The <function>host</function>,
   <function>text</function>, and <function>abbrev</function>
6864
   functions are primarily intended to offer alternative display
6865
   formats.
6866
  </para>
6867

6868
    <table id="cidr-inet-functions-table">
6869
     <title><type>cidr</type> and <type>inet</type> Functions</title>
6870
     <tgroup cols="5">
T
Thomas G. Lockhart 已提交
6871 6872
      <thead>
       <row>
6873 6874 6875 6876 6877
        <entry>Function</entry>
        <entry>Return Type</entry>
        <entry>Description</entry>
        <entry>Example</entry>
        <entry>Result</entry>
T
Thomas G. Lockhart 已提交
6878 6879 6880 6881
       </row>
      </thead>
      <tbody>
       <row>
6882 6883 6884 6885 6886
        <entry><literal><function>broadcast</function>(<type>inet</type>)</literal></entry>
        <entry><type>inet</type></entry>
        <entry>broadcast address for network</entry>
        <entry><literal>broadcast('192.168.1.5/24')</literal></entry>
        <entry><literal>192.168.1.255/24</literal></entry>
T
Thomas G. Lockhart 已提交
6887 6888
       </row>
       <row>
6889 6890 6891 6892 6893
        <entry><literal><function>host</function>(<type>inet</type>)</literal></entry>
        <entry><type>text</type></entry>
        <entry>extract IP address as text</entry>
        <entry><literal>host('192.168.1.5/24')</literal></entry>
        <entry><literal>192.168.1.5</literal></entry>
T
Thomas G. Lockhart 已提交
6894 6895
       </row>
       <row>
6896
        <entry><literal><function>masklen</function>(<type>inet</type>)</literal></entry>
6897
        <entry><type>int</type></entry>
6898 6899 6900
        <entry>extract netmask length</entry>
        <entry><literal>masklen('192.168.1.5/24')</literal></entry>
        <entry><literal>24</literal></entry>
T
Thomas G. Lockhart 已提交
6901
       </row>
B
Bruce Momjian 已提交
6902
       <row>
6903
        <entry><literal><function>set_masklen</function>(<type>inet</type>, <type>int</type>)</literal></entry>
6904 6905 6906 6907
        <entry><type>inet</type></entry>
        <entry>set netmask length for <type>inet</type> value</entry>
        <entry><literal>set_masklen('192.168.1.5/24', 16)</literal></entry>
        <entry><literal>192.168.1.5/16</literal></entry>
B
Bruce Momjian 已提交
6908
       </row>
6909 6910 6911 6912 6913 6914 6915
       <row>
        <entry><literal><function>set_masklen</function>(<type>cidr</type>, <type>int</type>)</literal></entry>
        <entry><type>cidr</type></entry>
        <entry>set netmask length for <type>cidr</type> value</entry>
        <entry><literal>set_masklen('192.168.1.0/24'::cidr, 16)</literal></entry>
        <entry><literal>192.168.0.0/16</literal></entry>
       </row>
T
Thomas G. Lockhart 已提交
6916
       <row>
6917 6918 6919 6920 6921
        <entry><literal><function>netmask</function>(<type>inet</type>)</literal></entry>
        <entry><type>inet</type></entry>
        <entry>construct netmask for network</entry>
        <entry><literal>netmask('192.168.1.5/24')</literal></entry>
        <entry><literal>255.255.255.0</literal></entry>
6922
       </row>
B
Bruce Momjian 已提交
6923
       <row>
6924 6925 6926 6927 6928
        <entry><literal><function>hostmask</function>(<type>inet</type>)</literal></entry>
        <entry><type>inet</type></entry>
        <entry>construct host mask for network</entry>
        <entry><literal>hostmask('192.168.23.20/30')</literal></entry>
        <entry><literal>0.0.0.3</literal></entry>
B
Bruce Momjian 已提交
6929
       </row>
6930
       <row>
6931 6932 6933 6934 6935
        <entry><literal><function>network</function>(<type>inet</type>)</literal></entry>
        <entry><type>cidr</type></entry>
        <entry>extract network part of address</entry>
        <entry><literal>network('192.168.1.5/24')</literal></entry>
        <entry><literal>192.168.1.0/24</literal></entry>
6936 6937
       </row>
       <row>
6938 6939 6940 6941 6942
        <entry><literal><function>text</function>(<type>inet</type>)</literal></entry>
        <entry><type>text</type></entry>
        <entry>extract IP address and netmask length as text</entry>
        <entry><literal>text(inet '192.168.1.5')</literal></entry>
        <entry><literal>192.168.1.5/32</literal></entry>
6943
       </row>
6944
       <row>
6945 6946 6947
        <entry><literal><function>abbrev</function>(<type>inet</type>)</literal></entry>
        <entry><type>text</type></entry>
        <entry>abbreviated display format as text</entry>
6948 6949 6950 6951 6952 6953 6954
        <entry><literal>abbrev(inet '10.1.0.0/16')</literal></entry>
        <entry><literal>10.1.0.0/16</literal></entry>
       </row>
       <row>
        <entry><literal><function>abbrev</function>(<type>cidr</type>)</literal></entry>
        <entry><type>text</type></entry>
        <entry>abbreviated display format as text</entry>
6955 6956
        <entry><literal>abbrev(cidr '10.1.0.0/16')</literal></entry>
        <entry><literal>10.1/16</literal></entry>
6957
       </row>
6958 6959
       <row>
    <entry><literal><function>family</function>(<type>inet</type>)</literal></entry>
6960
    <entry><type>int</type></entry>
6961 6962 6963 6964
    <entry>extract family of address; <literal>4</literal> for IPv4,
    <literal>6</literal> for IPv6</entry>
    <entry><literal>family('::1')</literal></entry>
    <entry><literal>6</literal></entry>
6965
       </row>
6966 6967 6968 6969
      </tbody>
     </tgroup>
    </table>

6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985
  <para>
   Any <type>cidr</> value can be cast to <type>inet</> implicitly
   or explicitly; therefore, the functions shown above as operating on
   <type>inet</> also work on <type>cidr</> values.  (Where there are
   separate functions for <type>inet</> and <type>cidr</>, it is because
   the behavior should be different for the two cases.)
   Also, it is permitted to cast an <type>inet</> value to <type>cidr</>.
   When this is done, any bits to the right of the netmask are silently zeroed
   to create a valid <type>cidr</> value.
   In addition,
   you can cast a text value to <type>inet</> or <type>cidr</>
   using normal casting syntax: for example,
   <literal>inet(<replaceable>expression</>)</literal> or
   <literal><replaceable>colname</>::cidr</literal>.
  </para>

6986 6987
  <para>
   <xref linkend="macaddr-functions-table"> shows the functions
6988 6989 6990
   available for use with the <type>macaddr</type> type.  The function
   <literal><function>trunc</function>(<type>macaddr</type>)</literal> returns a MAC
   address with the last 3 bytes set to zero.  This can be used to
6991 6992 6993 6994 6995
   associate the remaining prefix with a manufacturer.  The directory
   <filename>contrib/mac</filename> in the source distribution
   contains some utilities to create and maintain such an association
   table.
  </para>
6996

6997
    <table id="macaddr-functions-table">
6998
     <title><type>macaddr</type> Functions</title>
6999 7000 7001
     <tgroup cols="5">
      <thead>
       <row>
7002 7003 7004 7005 7006
        <entry>Function</entry>
        <entry>Return Type</entry>
        <entry>Description</entry>
        <entry>Example</entry>
        <entry>Result</entry>
T
Thomas G. Lockhart 已提交
7007
       </row>
7008 7009
      </thead>
      <tbody>
7010
       <row>
7011 7012 7013 7014 7015
        <entry><literal><function>trunc</function>(<type>macaddr</type>)</literal></entry>
        <entry><type>macaddr</type></entry>
        <entry>set last 3 bytes to zero</entry>
        <entry><literal>trunc(macaddr '12:34:56:78:90:ab')</literal></entry>
        <entry><literal>12:34:56:00:00:00</literal></entry>
7016
       </row>
T
Thomas G. Lockhart 已提交
7017 7018 7019
      </tbody>
     </tgroup>
    </table>
7020

7021
   <para>
7022 7023
    The <type>macaddr</type> type also supports the standard relational
    operators (<literal>&gt;</literal>, <literal>&lt;=</literal>, etc.) for
7024 7025 7026
    lexicographical ordering.
   </para>

T
Thomas G. Lockhart 已提交
7027
  </sect1>
7028

7029

7030
 <sect1 id="functions-sequence">
7031
  <title>Sequence Manipulation Functions</title>
7032 7033

  <indexterm>
P
Peter Eisentraut 已提交
7034
   <primary>sequence</primary>
7035 7036 7037 7038 7039 7040 7041
  </indexterm>
  <indexterm>
   <primary>nextval</primary>
  </indexterm>
  <indexterm>
   <primary>currval</primary>
  </indexterm>
7042 7043 7044
  <indexterm>
   <primary>lastval</primary>
  </indexterm>
7045 7046 7047 7048
  <indexterm>
   <primary>setval</primary>
  </indexterm>

7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061
  <para>
   This section describes <productname>PostgreSQL</productname>'s functions
   for operating on <firstterm>sequence objects</firstterm>.
   Sequence objects (also called sequence generators or
   just sequences) are special single-row tables created with
   <command>CREATE SEQUENCE</command>.  A sequence object is usually used to
   generate unique identifiers for rows of a table.  The sequence functions,
   listed in <xref linkend="functions-sequence-table">,
   provide simple, multiuser-safe methods for obtaining successive
   sequence values from sequence objects.
  </para>

   <table id="functions-sequence-table">
7062
    <title>Sequence Functions</title>
7063 7064
    <tgroup cols="3">
     <thead>
7065
      <row><entry>Function</entry> <entry>Return Type</entry> <entry>Description</entry></row>
7066 7067 7068 7069
     </thead>

     <tbody>
      <row>
7070
        <entry><literal><function>nextval</function>(<type>regclass</type>)</literal></entry>
7071 7072
        <entry><type>bigint</type></entry>
        <entry>Advance sequence and return new value</entry>
7073 7074
      </row>
      <row>
7075
        <entry><literal><function>currval</function>(<type>regclass</type>)</literal></entry>
7076
        <entry><type>bigint</type></entry>
7077 7078 7079 7080 7081 7082
        <entry>Return value most recently obtained with
        <function>nextval</function> for specified sequence</entry>
      </row>
      <row>
        <entry><literal><function>lastval</function>()</literal></entry>
        <entry><type>bigint</type></entry>
7083
        <entry>Return value most recently obtained with <function>nextval</function></entry>
7084 7085
      </row>
      <row>
7086
        <entry><literal><function>setval</function>(<type>regclass</type>, <type>bigint</type>)</literal></entry>
7087 7088
        <entry><type>bigint</type></entry>
        <entry>Set sequence's current value</entry>
7089 7090
      </row>
      <row>
7091
        <entry><literal><function>setval</function>(<type>regclass</type>, <type>bigint</type>, <type>boolean</type>)</literal></entry>
7092 7093
        <entry><type>bigint</type></entry>
        <entry>Set sequence's current value and <literal>is_called</literal> flag</entry>
7094 7095 7096 7097 7098 7099
      </row>
     </tbody>
    </tgroup>
   </table>

  <para>
7100 7101 7102
   The sequence to be operated on by a sequence-function call is specified by
   a <type>regclass</> argument, which is just the OID of the sequence in the
   <structname>pg_class</> system catalog.  You do not have to look up the
7103
   OID by hand, however, since the <type>regclass</> data type's input
7104 7105
   converter will do the work for you.  Just write the sequence name enclosed
   in single quotes, so that it looks like a literal constant.  To
7106
   achieve some compatibility with the handling of ordinary
7107 7108
   <acronym>SQL</acronym> names, the string will be converted to lowercase
   unless it contains double quotes around the sequence name.  Thus
7109
<programlisting>
7110 7111 7112
nextval('foo')      <lineannotation>operates on sequence <literal>foo</literal></>
nextval('FOO')      <lineannotation>operates on sequence <literal>foo</literal></>
nextval('"Foo"')    <lineannotation>operates on sequence <literal>Foo</literal></>
7113 7114 7115
</programlisting>
   The sequence name can be schema-qualified if necessary:
<programlisting>
7116 7117 7118
nextval('myschema.foo')     <lineannotation>operates on <literal>myschema.foo</literal></>
nextval('"myschema".foo')   <lineannotation>same as above</lineannotation>
nextval('foo')              <lineannotation>searches search path for <literal>foo</literal></>
7119
</programlisting>
7120 7121
   See <xref linkend="datatype-oid"> for more information about
   <type>regclass</>.
7122 7123
  </para>

7124 7125 7126 7127 7128
  <note>
   <para>
    Before <productname>PostgreSQL</productname> 8.1, the arguments of the
    sequence functions were of type <type>text</>, not <type>regclass</>, and
    the above-described conversion from a text string to an OID value would
7129
    happen at run time during each call.  For backwards compatibility, this
7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142
    facility still exists, but internally it is now handled as an implicit
    coercion from <type>text</> to <type>regclass</> before the function is
    invoked.
   </para>

   <para>
    When you write the argument of a sequence function as an unadorned
    literal string, it becomes a constant of type <type>regclass</>.
    Since this is really just an OID, it will track the originally
    identified sequence despite later renaming, schema reassignment,
    etc.  This <quote>early binding</> behavior is usually desirable for
    sequence references in column defaults and views.  But sometimes you will
    want <quote>late binding</> where the sequence reference is resolved
7143
    at run time.  To get late-binding behavior, force the constant to be
7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159
    stored as a <type>text</> constant instead of <type>regclass</>:
<programlisting>
nextval('foo'::text)      <lineannotation><literal>foo</literal> is looked up at runtime</>
</programlisting>
    Note that late binding was the only behavior supported in
    <productname>PostgreSQL</productname> releases before 8.1, so you
    may need to do this to preserve the semantics of old applications.
   </para>

   <para>
    Of course, the argument of a sequence function can be an expression
    as well as a constant.  If it is a text expression then the implicit
    coercion will result in a run-time lookup.
   </para>
  </note>

7160 7161 7162 7163 7164
  <para>
   The available sequence functions are:

    <variablelist>
     <varlistentry>
7165
      <term><function>nextval</function></term>
7166 7167 7168
      <listitem>
       <para>
        Advance the sequence object to its next value and return that
7169 7170 7171
        value.  This is done atomically: even if multiple sessions
        execute <function>nextval</function> concurrently, each will safely receive
        a distinct sequence value.
7172 7173 7174 7175 7176
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
7177
      <term><function>currval</function></term>
7178 7179
      <listitem>
       <para>
7180
        Return the value most recently obtained by <function>nextval</function>
7181 7182 7183 7184 7185 7186
        for this sequence in the current session.  (An error is
        reported if <function>nextval</function> has never been called for this
        sequence in this session.)  Notice that because this is returning
        a session-local value, it gives a predictable answer whether or not
        other sessions have executed <function>nextval</function> since the
        current session did.
7187 7188 7189 7190
       </para>
      </listitem>
     </varlistentry>

7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206
     <varlistentry>
      <term><function>lastval</function></term>
      <listitem>
       <para>
        Return the value most recently returned by
        <function>nextval</> in the current session. This function is
        identical to <function>currval</function>, except that instead
        of taking the sequence name as an argument it fetches the
        value of the last sequence that <function>nextval</function>
        was used on in the current session. It is an error to call
        <function>lastval</function> if <function>nextval</function>
        has not yet been called in the current session.
       </para>
      </listitem>
     </varlistentry>

7207
     <varlistentry>
7208
      <term><function>setval</function></term>
7209 7210 7211
      <listitem>
       <para>
        Reset the sequence object's counter value.  The two-parameter
7212 7213 7214 7215 7216 7217 7218 7219 7220
        form sets the sequence's <literal>last_value</literal> field to the specified
        value and sets its <literal>is_called</literal> field to <literal>true</literal>,
        meaning that the next <function>nextval</function> will advance the sequence
        before returning a value.  In the three-parameter form,
        <literal>is_called</literal> may be set either <literal>true</literal> or
        <literal>false</literal>.  If it's set to <literal>false</literal>,
        the next <function>nextval</function> will return exactly the specified
        value, and sequence advancement commences with the following
        <function>nextval</function>.  For example,
7221 7222

<screen>
7223
SELECT setval('foo', 42);           <lineannotation>Next <function>nextval</> will return 43</lineannotation>
7224
SELECT setval('foo', 42, true);     <lineannotation>Same as above</lineannotation>
7225
SELECT setval('foo', 42, false);    <lineannotation>Next <function>nextval</> will return 42</lineannotation>
7226 7227
</screen>

7228
        The result returned by <function>setval</function> is just the value of its
7229
        second argument.
7230 7231 7232 7233 7234 7235
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
  </para>

7236 7237 7238 7239 7240 7241 7242 7243
  <para>
   If a sequence object has been created with default parameters,
   <function>nextval</function> calls on it will return successive values
   beginning with 1.  Other behaviors can be obtained by using
   special parameters in the <xref linkend="sql-createsequence" endterm="sql-createsequence-title"> command;
   see its command reference page for more information.
  </para>

7244 7245 7246
  <important>
   <para>
    To avoid blocking of concurrent transactions that obtain numbers from the
7247
    same sequence, a <function>nextval</function> operation is never rolled back;
7248
    that is, once a value has been fetched it is considered used, even if the
7249
    transaction that did the <function>nextval</function> later aborts.  This means
7250
    that aborted transactions may leave unused <quote>holes</quote> in the
7251
    sequence of assigned values.  <function>setval</function> operations are never
7252 7253 7254 7255 7256 7257 7258
    rolled back, either.
   </para>
  </important>

 </sect1>


7259 7260 7261
 <sect1 id="functions-conditional">
  <title>Conditional Expressions</title>

7262
  <indexterm>
P
Peter Eisentraut 已提交
7263
   <primary>CASE</primary>
7264 7265 7266
  </indexterm>

  <indexterm>
P
Peter Eisentraut 已提交
7267
   <primary>conditional expression</primary>
7268 7269
  </indexterm>

7270
  <para>
7271
   This section describes the <acronym>SQL</acronym>-compliant conditional expressions
7272
   available in <productname>PostgreSQL</productname>.
7273 7274 7275 7276 7277 7278 7279 7280 7281 7282
  </para>

  <tip>
   <para>
    If your needs go beyond the capabilities of these conditional
    expressions you might want to consider writing a stored procedure
    in a more expressive programming language.
   </para>
  </tip>

7283
  <sect2>
7284 7285 7286 7287 7288 7289
   <title><literal>CASE</></title>

  <para>
   The <acronym>SQL</acronym> <token>CASE</token> expression is a
   generic conditional expression, similar to if/else statements in
   other languages:
7290 7291 7292 7293 7294 7295 7296 7297

<synopsis>
CASE WHEN <replaceable>condition</replaceable> THEN <replaceable>result</replaceable>
     <optional>WHEN ...</optional>
     <optional>ELSE <replaceable>result</replaceable></optional>
END
</synopsis>

7298
   <token>CASE</token> clauses can be used wherever
7299
   an expression is valid.  <replaceable>condition</replaceable> is an
7300
   expression that returns a <type>boolean</type> result.  If the result is true
7301 7302
   then the value of the <token>CASE</token> expression is the
   <replaceable>result</replaceable> that follows the condition.  If the result is false any
7303 7304 7305 7306 7307
   subsequent <token>WHEN</token> clauses are searched in the same
   manner.  If no <token>WHEN</token>
   <replaceable>condition</replaceable> is true then the value of the
   case expression is the <replaceable>result</replaceable> in the
   <token>ELSE</token> clause.  If the <token>ELSE</token> clause is
P
Peter Eisentraut 已提交
7308
   omitted and no condition matches, the result is null.
7309 7310 7311 7312 7313
  </para>

   <para>
    An example:
<screen>
7314 7315
SELECT * FROM test;

7316 7317 7318 7319 7320
 a
---
 1
 2
 3
7321 7322 7323 7324 7325 7326 7327 7328 7329


SELECT a,
       CASE WHEN a=1 THEN 'one'
            WHEN a=2 THEN 'two'
            ELSE 'other'
       END
    FROM test;

7330 7331 7332 7333 7334 7335 7336 7337 7338
 a | case
---+-------
 1 | one
 2 | two
 3 | other
</screen>
   </para>

  <para>
7339
   The data types of all the <replaceable>result</replaceable>
7340
   expressions must be convertible to a single output type.
7341
   See <xref linkend="typeconv-union-case"> for more detail.
7342 7343
  </para>

7344 7345 7346 7347
  <para>
   The following <quote>simple</quote> <token>CASE</token> expression is a
   specialized variant of the general form above:

7348 7349 7350 7351 7352 7353 7354 7355
<synopsis>
CASE <replaceable>expression</replaceable>
    WHEN <replaceable>value</replaceable> THEN <replaceable>result</replaceable>
    <optional>WHEN ...</optional>
    <optional>ELSE <replaceable>result</replaceable></optional>
END
</synopsis>

7356
   The
7357
   <replaceable>expression</replaceable> is computed and compared to
7358
   all the <replaceable>value</replaceable> specifications in the
7359 7360
   <token>WHEN</token> clauses until one is found that is equal.  If
   no match is found, the <replaceable>result</replaceable> in the
P
Peter Eisentraut 已提交
7361
   <token>ELSE</token> clause (or a null value) is returned.  This is similar
7362 7363 7364 7365 7366 7367 7368
   to the <function>switch</function> statement in C.
  </para>

   <para>
    The example above can be written using the simple
    <token>CASE</token> syntax:
<screen>
7369 7370 7371 7372 7373 7374 7375
SELECT a,
       CASE a WHEN 1 THEN 'one'
              WHEN 2 THEN 'two'
              ELSE 'other'
       END
    FROM test;

7376 7377 7378 7379 7380 7381
 a | case
---+-------
 1 | one
 2 | two
 3 | other
</screen>
7382 7383 7384 7385 7386 7387 7388 7389 7390 7391
   </para>

   <para>
    A <token>CASE</token> expression does not evaluate any subexpressions
    that are not needed to determine the result.  For example, this is a
    possible way of avoiding a division-by-zero failure:
<programlisting>
SELECT ... WHERE CASE WHEN x &lt;&gt; 0 THEN y/x &gt; 1.5 ELSE false END;
</programlisting>
   </para>
7392
  </sect2>
7393

7394
  <sect2>
7395
   <title><literal>COALESCE</></title>
7396

P
Peter Eisentraut 已提交
7397 7398 7399 7400
  <indexterm>
   <primary>COALESCE</primary>
  </indexterm>

7401 7402 7403 7404 7405 7406 7407 7408
  <indexterm>
   <primary>NVL</primary>
  </indexterm>

  <indexterm>
   <primary>IFNULL</primary>
  </indexterm>

7409
<synopsis>
7410
<function>COALESCE</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
7411 7412 7413 7414
</synopsis>

  <para>
   The <function>COALESCE</function> function returns the first of its
7415
   arguments that is not null.  Null is returned only if all arguments
7416 7417
   are null.  It is often used to substitute a default value for 
   null values when data is retrieved for display, for example:
7418 7419 7420 7421
<programlisting>
SELECT COALESCE(description, short_description, '(none)') ...
</programlisting>
  </para>
7422 7423 7424 7425 7426

   <para>
    Like a <token>CASE</token> expression, <function>COALESCE</function> will
    not evaluate arguments that are not needed to determine the result;
    that is, arguments to the right of the first non-null argument are
7427 7428 7429
    not evaluated.  This SQL-standard function provides capabilities similar
    to <function>NVL</> and <function>IFNULL</>, which are used in some other
    database systems.
7430
   </para>
7431
  </sect2>
7432

7433
  <sect2>
7434
   <title><literal>NULLIF</></title>
7435

7436
  <indexterm>
7437
   <primary>NULLIF</primary>
7438 7439
  </indexterm>

7440
<synopsis>
7441
<function>NULLIF</function>(<replaceable>value1</replaceable>, <replaceable>value2</replaceable>)
7442 7443 7444
</synopsis>

  <para>
7445 7446 7447 7448 7449
   The <function>NULLIF</function> function returns a null value if
   <replaceable>value1</replaceable> and <replaceable>value2</replaceable>
   are equal;  otherwise it returns <replaceable>value1</replaceable>.
   This can be used to perform the inverse operation of the
   <function>COALESCE</function> example given above:
7450 7451 7452 7453
<programlisting>
SELECT NULLIF(value, '(none)') ...
</programlisting>
  </para>
7454 7455 7456 7457
  <para>
   If <replaceable>value1</replaceable> is <literal>(none)</>, return a null,
   otherwise return <replaceable>value1</replaceable>.
  </para>
7458

7459
  </sect2>
7460

7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492
  <sect2>
   <title><literal>GREATEST</literal> and <literal>LEAST</literal></title>

  <indexterm>
   <primary>GREATEST</primary>
  </indexterm>
  <indexterm>
   <primary>LEAST</primary>
  </indexterm>

<synopsis>
<function>GREATEST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
</synopsis>
<synopsis>
<function>LEAST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
</synopsis>

   <para>
    The <function>GREATEST</> and <function>LEAST</> functions select the
    largest or smallest value from a list of any number of expressions.
    The expressions must all be convertible to a common data type, which
    will be the type of the result
    (see <xref linkend="typeconv-union-case"> for details).  NULL values
    in the list are ignored.  The result will be NULL only if all the
    expressions evaluate to NULL.
   </para>

   <para>
    Note that <function>GREATEST</> and <function>LEAST</> are not in
    the SQL standard, but are a common extension.
   </para>
  </sect2>
7493 7494 7495
 </sect1>


7496 7497
 <sect1 id="functions-array">
  <title>Array Functions and Operators</title>
7498

7499
  <para>
7500 7501
   <xref linkend="array-operators-table"> shows the operators
   available for <type>array</type> types.
7502 7503
  </para>

7504 7505 7506 7507 7508
    <table id="array-operators-table">
     <title><type>array</type> Operators</title>
     <tgroup cols="4">
      <thead>
       <row>
7509 7510 7511 7512
        <entry>Operator</entry>
        <entry>Description</entry>
        <entry>Example</entry>
        <entry>Result</entry>
7513 7514 7515 7516
       </row>
      </thead>
      <tbody>
       <row>
7517 7518 7519 7520
        <entry> <literal>=</literal> </entry>
        <entry>equal</entry>
        <entry><literal>ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3]</literal></entry>
        <entry><literal>t</literal></entry>
7521
       </row>
7522

7523
       <row>
7524 7525 7526 7527
        <entry> <literal>&lt;&gt;</literal> </entry>
        <entry>not equal</entry>
        <entry><literal>ARRAY[1,2,3] &lt;&gt; ARRAY[1,2,4]</literal></entry>
        <entry><literal>t</literal></entry>
7528
       </row>
7529

7530
       <row>
7531 7532 7533 7534
        <entry> <literal>&lt;</literal> </entry>
        <entry>less than</entry>
        <entry><literal>ARRAY[1,2,3] &lt; ARRAY[1,2,4]</literal></entry>
        <entry><literal>t</literal></entry>
7535
       </row>
7536

7537
       <row>
7538 7539 7540 7541
        <entry> <literal>&gt;</literal> </entry>
        <entry>greater than</entry>
        <entry><literal>ARRAY[1,4,3] &gt; ARRAY[1,2,4]</literal></entry>
        <entry><literal>t</literal></entry>
7542
       </row>
7543

7544
       <row>
7545 7546 7547 7548
        <entry> <literal>&lt;=</literal> </entry>
        <entry>less than or equal</entry>
        <entry><literal>ARRAY[1,2,3] &lt;= ARRAY[1,2,3]</literal></entry>
        <entry><literal>t</literal></entry>
7549
       </row>
7550

7551
       <row>
7552 7553 7554 7555
        <entry> <literal>&gt;=</literal> </entry>
        <entry>greater than or equal</entry>
        <entry><literal>ARRAY[1,4,3] &gt;= ARRAY[1,4,3]</literal></entry>
        <entry><literal>t</literal></entry>
7556
       </row>
7557

7558
       <row>
7559 7560 7561 7562
        <entry> <literal>||</literal> </entry>
        <entry>array-to-array concatenation</entry>
        <entry><literal>ARRAY[1,2,3] || ARRAY[4,5,6]</literal></entry>
        <entry><literal>{1,2,3,4,5,6}</literal></entry>
7563
       </row>
7564

7565
       <row>
7566 7567 7568 7569
        <entry> <literal>||</literal> </entry>
        <entry>array-to-array concatenation</entry>
        <entry><literal>ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9]]</literal></entry>
        <entry><literal>{{1,2,3},{4,5,6},{7,8,9}}</literal></entry>
7570
       </row>
7571

7572
       <row>
7573 7574 7575 7576
        <entry> <literal>||</literal> </entry>
        <entry>element-to-array concatenation</entry>
        <entry><literal>3 || ARRAY[4,5,6]</literal></entry>
        <entry><literal>{3,4,5,6}</literal></entry>
7577
       </row>
7578

7579
       <row>
7580 7581 7582 7583
        <entry> <literal>||</literal> </entry>
        <entry>array-to-element concatenation</entry>
        <entry><literal>ARRAY[4,5,6] || 7</literal></entry>
        <entry><literal>{4,5,6,7}</literal></entry>
7584 7585 7586 7587
       </row>
      </tbody>
     </tgroup>
    </table>
7588

7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601
  <para>
   Array comparisons compare the array contents element-by-element,
   using the default btree comparison function for the element data type.
   In multidimensional arrays the elements are visited in row-major order
   (last subscript varies most rapidly).
   If the contents of two arrays are equal but the dimensionality is
   different, the first difference in the dimensionality information
   determines the sort order.  (This is a change from versions of
   <productname>PostgreSQL</> prior to 8.2: older versions would claim
   that two arrays with the same contents were equal, even if the
   number of dimensions or subscript ranges were different.)
  </para>

7602
  <para>
7603 7604
   See <xref linkend="arrays"> for more details about array operator
   behavior.
7605 7606
  </para>

7607 7608 7609
  <para>
   <xref linkend="array-functions-table"> shows the functions
   available for use with array types. See <xref linkend="arrays">
T
Tom Lane 已提交
7610
   for more discussion and examples of the use of these functions.
7611
  </para>
7612

7613 7614 7615 7616 7617
    <table id="array-functions-table">
     <title><type>array</type> Functions</title>
     <tgroup cols="5">
      <thead>
       <row>
7618 7619 7620 7621 7622
        <entry>Function</entry>
        <entry>Return Type</entry>
        <entry>Description</entry>
        <entry>Example</entry>
        <entry>Result</entry>
7623 7624 7625 7626
       </row>
      </thead>
      <tbody>
       <row>
7627
        <entry>
7628 7629 7630 7631 7632
     <literal>
      <function>array_cat</function>
      (<type>anyarray</type>, <type>anyarray</type>)
     </literal>
    </entry>
7633 7634 7635 7636
        <entry><type>anyarray</type></entry>
        <entry>concatenate two arrays</entry>
        <entry><literal>array_cat(ARRAY[1,2,3], ARRAY[4,5])</literal></entry>
        <entry><literal>{1,2,3,4,5}</literal></entry>
7637 7638
       </row>
       <row>
7639
        <entry>
7640 7641 7642 7643 7644
     <literal>
      <function>array_append</function>
      (<type>anyarray</type>, <type>anyelement</type>)
     </literal>
    </entry>
7645 7646 7647 7648
        <entry><type>anyarray</type></entry>
        <entry>append an element to the end of an array</entry>
        <entry><literal>array_append(ARRAY[1,2], 3)</literal></entry>
        <entry><literal>{1,2,3}</literal></entry>
7649 7650
       </row>
       <row>
7651
        <entry>
7652 7653 7654 7655 7656
     <literal>
      <function>array_prepend</function>
      (<type>anyelement</type>, <type>anyarray</type>)
     </literal>
    </entry>
7657 7658 7659 7660
        <entry><type>anyarray</type></entry>
        <entry>append an element to the beginning of an array</entry>
        <entry><literal>array_prepend(1, ARRAY[2,3])</literal></entry>
        <entry><literal>{1,2,3}</literal></entry>
7661 7662
       </row>
       <row>
7663
        <entry>
7664 7665 7666 7667 7668
     <literal>
      <function>array_dims</function>
      (<type>anyarray</type>)
     </literal>
    </entry>
7669 7670
        <entry><type>text</type></entry>
        <entry>returns a text representation of array's dimensions</entry>
7671
        <entry><literal>array_dims(ARRAY[[1,2,3], [4,5,6]])</literal></entry>
7672
        <entry><literal>[1:2][1:3]</literal></entry>
7673 7674
       </row>
       <row>
7675
        <entry>
7676 7677
     <literal>
      <function>array_lower</function>
7678
      (<type>anyarray</type>, <type>int</type>)
7679 7680
     </literal>
    </entry>
7681
        <entry><type>int</type></entry>
7682
        <entry>returns lower bound of the requested array dimension</entry>
7683
        <entry><literal>array_lower('[0:2]={1,2,3}'::int[], 1)</literal></entry>
7684
        <entry><literal>0</literal></entry>
7685 7686
       </row>
       <row>
7687
        <entry>
7688 7689
     <literal>
      <function>array_upper</function>
7690
      (<type>anyarray</type>, <type>int</type>)
7691 7692
     </literal>
    </entry>
7693
        <entry><type>int</type></entry>
7694 7695 7696
        <entry>returns upper bound of the requested array dimension</entry>
        <entry><literal>array_upper(ARRAY[1,2,3,4], 1)</literal></entry>
        <entry><literal>4</literal></entry>
7697 7698
       </row>
       <row>
7699
        <entry>
7700 7701 7702 7703 7704
     <literal>
      <function>array_to_string</function>
      (<type>anyarray</type>, <type>text</type>)
     </literal>
    </entry>
7705 7706
        <entry><type>text</type></entry>
        <entry>concatenates array elements using provided delimiter</entry>
7707
        <entry><literal>array_to_string(ARRAY[1, 2, 3], '~^~')</literal></entry>
7708
        <entry><literal>1~^~2~^~3</literal></entry>
7709 7710
       </row>
       <row>
7711
        <entry>
7712 7713 7714 7715 7716
     <literal>
      <function>string_to_array</function>
      (<type>text</type>, <type>text</type>)
     </literal>
    </entry>
7717 7718
        <entry><type>text[]</type></entry>
        <entry>splits string into array elements using provided delimiter</entry>
7719
        <entry><literal>string_to_array('xx~^~yy~^~zz', '~^~')</literal></entry>
7720
        <entry><literal>{xx,yy,zz}</literal></entry>
7721 7722 7723 7724 7725
       </row>
      </tbody>
     </tgroup>
    </table>
  </sect1>
7726

7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766
 <sect1 id="functions-aggregate">
  <title>Aggregate Functions</title>

  <indexterm zone="functions-aggregate">
   <primary>aggregate function</primary>
   <secondary>built-in</secondary>
  </indexterm>

  <para>
   <firstterm>Aggregate functions</firstterm> compute a single result
   value from a set of input values.  <xref
   linkend="functions-aggregate-table"> shows the built-in aggregate
   functions.  The special syntax considerations for aggregate
   functions are explained in <xref linkend="syntax-aggregates">.
   Consult <xref linkend="tutorial-agg"> for additional introductory
   information.
  </para>

  <table id="functions-aggregate-table">
   <title>Aggregate Functions</title>

   <tgroup cols="4">
    <thead>
     <row>
      <entry>Function</entry>
      <entry>Argument Type</entry>
      <entry>Return Type</entry>
      <entry>Description</entry>
     </row>
    </thead>

    <tbody>
     <row>
      <entry>
       <indexterm>
        <primary>average</primary>
       </indexterm>
       <function>avg(<replaceable class="parameter">expression</replaceable>)</function>
      </entry>
      <entry>
7767
       <type>smallint</type>, <type>int</type>,
7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786
       <type>bigint</type>, <type>real</type>, <type>double
       precision</type>, <type>numeric</type>, or <type>interval</type>
      </entry>
      <entry>
       <type>numeric</type> for any integer type argument,
       <type>double precision</type> for a floating-point argument,
       otherwise the same as the argument data type
      </entry>
      <entry>the average (arithmetic mean) of all input values</entry>
     </row>

     <row>
      <entry>
       <indexterm>
        <primary>bit_and</primary>
       </indexterm>
       <function>bit_and(<replaceable class="parameter">expression</replaceable>)</function>
      </entry>
      <entry>
7787
       <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803
       <type>bit</type>
      </entry>
      <entry>
        same as argument data type
      </entry>
      <entry>the bitwise AND of all non-null input values, or null if none</entry>
     </row>

     <row>
      <entry>
       <indexterm>
        <primary>bit_or</primary>
       </indexterm>
       <function>bit_or(<replaceable class="parameter">expression</replaceable>)</function>
      </entry>
      <entry>
7804
       <type>smallint</type>, <type>int</type>, <type>bigint</type>, or
7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860
       <type>bit</type>
      </entry>
      <entry>
        same as argument data type
      </entry>
      <entry>the bitwise OR of all non-null input values, or null if none</entry>
     </row>

     <row>
      <entry>
       <indexterm>
        <primary>bool_and</primary>
       </indexterm>
       <function>bool_and(<replaceable class="parameter">expression</replaceable>)</function>
      </entry>
      <entry>
       <type>bool</type>
      </entry>
      <entry>
       <type>bool</type>
      </entry>
      <entry>true if all input values are true, otherwise false</entry>
     </row>

     <row>
      <entry>
       <indexterm>
        <primary>bool_or</primary>
       </indexterm>
       <function>bool_or(<replaceable class="parameter">expression</replaceable>)</function>
      </entry>
      <entry>
       <type>bool</type>
      </entry>
      <entry>
       <type>bool</type>
      </entry>
      <entry>true if at least one input value is true, otherwise false</entry>
     </row>

     <row>
      <entry><function>count(*)</function></entry>
      <entry></entry>
      <entry><type>bigint</type></entry>
      <entry>number of input values</entry>
     </row>

     <row>
      <entry><function>count(<replaceable class="parameter">expression</replaceable>)</function></entry>
      <entry>any</entry>
      <entry><type>bigint</type></entry>
      <entry>
       number of input values for which the value of <replaceable
       class="parameter">expression</replaceable> is not null
      </entry>
     </row>
7861

7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876
     <row>
      <entry>
       <indexterm>
        <primary>every</primary>
       </indexterm>
       <function>every(<replaceable class="parameter">expression</replaceable>)</function>
      </entry>
      <entry>
       <type>bool</type>
      </entry>
      <entry>
       <type>bool</type>
      </entry>
      <entry>equivalent to <function>bool_and</function></entry>
     </row>
7877

7878 7879
     <row>
      <entry><function>max(<replaceable class="parameter">expression</replaceable>)</function></entry>
7880
      <entry>any array, numeric, string, or date/time type</entry>
7881 7882 7883 7884 7885 7886 7887
      <entry>same as argument type</entry>
      <entry>
       maximum value of <replaceable
       class="parameter">expression</replaceable> across all input
       values
      </entry>
     </row>
7888

7889 7890
     <row>
      <entry><function>min(<replaceable class="parameter">expression</replaceable>)</function></entry>
7891
      <entry>any array, numeric, string, or date/time type</entry>
7892 7893 7894 7895 7896 7897 7898
      <entry>same as argument type</entry>
      <entry>
       minimum value of <replaceable
       class="parameter">expression</replaceable> across all input
       values
      </entry>
     </row>
7899

7900 7901 7902 7903 7904 7905 7906 7907
     <row>
      <entry>
       <indexterm>
        <primary>standard deviation</primary>
       </indexterm>
       <function>stddev(<replaceable class="parameter">expression</replaceable>)</function>
      </entry>
      <entry>
7908
       <type>smallint</type>, <type>int</type>,
7909 7910 7911 7912 7913 7914 7915 7916 7917
       <type>bigint</type>, <type>real</type>, <type>double
       precision</type>, or <type>numeric</type>
      </entry>
      <entry>
       <type>double precision</type> for floating-point arguments,
       otherwise <type>numeric</type>
      </entry>
      <entry>sample standard deviation of the input values</entry>
     </row>
7918

7919 7920 7921
     <row>
      <entry><function>sum(<replaceable class="parameter">expression</replaceable>)</function></entry>
      <entry>
7922
       <type>smallint</type>, <type>int</type>,
7923 7924 7925 7926 7927 7928
       <type>bigint</type>, <type>real</type>, <type>double
       precision</type>, <type>numeric</type>, or
       <type>interval</type>
      </entry>
      <entry>
       <type>bigint</type> for <type>smallint</type> or
7929
       <type>int</type> arguments, <type>numeric</type> for
7930 7931 7932 7933 7934 7935
       <type>bigint</type> arguments, <type>double precision</type>
       for floating-point arguments, otherwise the same as the
       argument data type
      </entry>
      <entry>sum of <replaceable class="parameter">expression</replaceable> across all input values</entry>
     </row>
7936

7937 7938 7939 7940 7941 7942 7943 7944
     <row>
      <entry>
       <indexterm>
        <primary>variance</primary>
       </indexterm>
       <function>variance</function>(<replaceable class="parameter">expression</replaceable>)
      </entry>
      <entry>
7945
       <type>smallint</type>, <type>int</type>,
7946 7947 7948 7949 7950 7951 7952 7953 7954
       <type>bigint</type>, <type>real</type>, <type>double
       precision</type>, or <type>numeric</type>
      </entry>
      <entry>
       <type>double precision</type> for floating-point arguments,
       otherwise <type>numeric</type>
      </entry>
      <entry>sample variance of the input values (square of the sample standard deviation)</entry>
     </row>
7955

7956 7957 7958
    </tbody>
   </tgroup>
  </table>
P
Peter Eisentraut 已提交
7959

7960
  <para>
7961 7962 7963
   It should be noted that except for <function>count</function>,
   these functions return a null value when no rows are selected.  In
   particular, <function>sum</function> of no rows returns null, not
T
Tom Lane 已提交
7964
   zero as one might expect.  The <function>coalesce</function> function may be
7965
   used to substitute zero for null when necessary.
7966 7967
  </para>

7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989
  <note>
    <indexterm>
      <primary>ANY</primary>
    </indexterm>
    <indexterm>
      <primary>SOME</primary>
    </indexterm>
    <para>
      Boolean aggregates <function>bool_and</function> and 
      <function>bool_or</function> correspond to standard SQL aggregates
      <function>every</function> and <function>any</function> or
      <function>some</function>. 
      As for <function>any</function> and <function>some</function>, 
      it seems that there is an ambiguity built into the standard syntax:
<programlisting>
SELECT b1 = ANY((SELECT b2 FROM t2 ...)) FROM t1 ...;
</programlisting>
      Here <function>ANY</function> can be considered both as leading
      to a subquery or as an aggregate if the select expression returns 1 row.
      Thus the standard name cannot be given to these aggregates.
    </para>
  </note>
7990

7991
  <note>
7992
   <para>
7993
    Users accustomed to working with other SQL database management
7994 7995 7996
    systems may be surprised by the performance of the
    <function>count</function> aggregate when it is applied to the
    entire table. A query like:
7997
<programlisting>
7998
SELECT count(*) FROM sometable;
7999
</programlisting>
8000
    will be executed by <productname>PostgreSQL</productname> using a
8001
    sequential scan of the entire table.
8002
   </para>
8003 8004
  </note>
 </sect1>
8005

B
Bruce Momjian 已提交
8006

8007 8008
 <sect1 id="functions-subquery">
  <title>Subquery Expressions</title>
8009

8010 8011 8012
  <indexterm>
   <primary>EXISTS</primary>
  </indexterm>
8013

8014 8015 8016
  <indexterm>
   <primary>IN</primary>
  </indexterm>
8017

8018 8019 8020
  <indexterm>
   <primary>NOT IN</primary>
  </indexterm>
8021

8022 8023 8024
  <indexterm>
   <primary>ANY</primary>
  </indexterm>
8025

8026 8027 8028
  <indexterm>
   <primary>ALL</primary>
  </indexterm>
8029

8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048
  <indexterm>
   <primary>SOME</primary>
  </indexterm>

  <indexterm>
   <primary>subquery</primary>
  </indexterm>

  <para>
   This section describes the <acronym>SQL</acronym>-compliant subquery
   expressions available in <productname>PostgreSQL</productname>.
   All of the expression forms documented in this section return
   Boolean (true/false) results.
  </para>

  <sect2>
   <title><literal>EXISTS</literal></title>

<synopsis>
8049
EXISTS (<replaceable>subquery</replaceable>)
8050 8051 8052 8053 8054 8055 8056 8057 8058 8059
</synopsis>

  <para>
   The argument of <token>EXISTS</token> is an arbitrary <command>SELECT</> statement,
   or <firstterm>subquery</firstterm>.  The
   subquery is evaluated to determine whether it returns any rows.
   If it returns at least one row, the result of <token>EXISTS</token> is
   <quote>true</>; if the subquery returns no rows, the result of <token>EXISTS</token> 
   is <quote>false</>.
  </para>
8060

8061 8062 8063 8064
  <para>
   The subquery can refer to variables from the surrounding query,
   which will act as constants during any one evaluation of the subquery.
  </para>
8065

8066 8067 8068 8069 8070 8071 8072
  <para>
   The subquery will generally only be executed far enough to determine
   whether at least one row is returned, not all the way to completion.
   It is unwise to write a subquery that has any side effects (such as
   calling sequence functions); whether the side effects occur or not
   may be difficult to predict.
  </para>
8073

8074 8075 8076 8077 8078 8079 8080 8081
  <para>
   Since the result depends only on whether any rows are returned,
   and not on the contents of those rows, the output list of the
   subquery is normally uninteresting.  A common coding convention is
   to write all <literal>EXISTS</> tests in the form
   <literal>EXISTS(SELECT 1 WHERE ...)</literal>.  There are exceptions to
   this rule however, such as subqueries that use <token>INTERSECT</token>.
  </para>
8082

8083 8084 8085 8086 8087 8088 8089 8090 8091 8092
  <para>
   This simple example is like an inner join on <literal>col2</>, but
   it produces at most one output row for each <literal>tab1</> row,
   even if there are multiple matching <literal>tab2</> rows:
<screen>
SELECT col1 FROM tab1
    WHERE EXISTS(SELECT 1 FROM tab2 WHERE col2 = tab1.col2);
</screen>
  </para>
  </sect2>
8093

8094 8095
  <sect2>
   <title><literal>IN</literal></title>
8096

8097 8098 8099
<synopsis>
<replaceable>expression</replaceable> IN (<replaceable>subquery</replaceable>)
</synopsis>
8100

8101 8102 8103 8104 8105 8106 8107 8108
  <para>
   The right-hand side is a parenthesized
   subquery, which must return exactly one column.  The left-hand expression
   is evaluated and compared to each row of the subquery result.
   The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
   The result is <quote>false</> if no equal row is found (including the special
   case where the subquery returns no rows).
  </para>
8109

8110 8111 8112 8113 8114 8115 8116
  <para>
   Note that if the left-hand expression yields null, or if there are
   no equal right-hand values and at least one right-hand row yields
   null, the result of the <token>IN</token> construct will be null, not false.
   This is in accordance with SQL's normal rules for Boolean combinations
   of null values.
  </para>
8117

8118 8119 8120 8121 8122 8123 8124 8125
  <para>
   As with <token>EXISTS</token>, it's unwise to assume that the subquery will
   be evaluated completely.
  </para>

<synopsis>
<replaceable>row_constructor</replaceable> IN (<replaceable>subquery</replaceable>)
</synopsis>
J
Joe Conway 已提交
8126

8127
  <para>
8128 8129 8130 8131 8132 8133 8134 8135 8136
   The left-hand side of this form of <token>IN</token> is a row constructor,
   as described in <xref linkend="sql-syntax-row-constructors">.
   The right-hand side is a parenthesized
   subquery, which must return exactly as many columns as there are
   expressions in the left-hand row.  The left-hand expressions are
   evaluated and compared row-wise to each row of the subquery result.
   The result of <token>IN</token> is <quote>true</> if any equal subquery row is found.
   The result is <quote>false</> if no equal row is found (including the special
   case where the subquery returns no rows).
8137 8138
  </para>

8139 8140 8141 8142 8143 8144
  <para>
   As usual, null values in the rows are combined per
   the normal rules of SQL Boolean expressions.  Two rows are considered
   equal if all their corresponding members are non-null and equal; the rows
   are unequal if any corresponding members are non-null and unequal;
   otherwise the result of that row comparison is unknown (null).
8145 8146
   If all the per-row results are either unequal or null, with at least one
   null, then the result of <token>IN</token> is null.
8147 8148
  </para>
  </sect2>
8149

8150
  <sect2>
8151
   <title><literal>NOT IN</literal></title>
8152 8153 8154 8155

<synopsis>
<replaceable>expression</replaceable> NOT IN (<replaceable>subquery</replaceable>)
</synopsis>
8156

8157
  <para>
8158 8159 8160 8161 8162 8163
   The right-hand side is a parenthesized
   subquery, which must return exactly one column.  The left-hand expression
   is evaluated and compared to each row of the subquery result.
   The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
   are found (including the special case where the subquery returns no rows).
   The result is <quote>false</> if any equal row is found.
8164 8165 8166
  </para>

  <para>
8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192
   Note that if the left-hand expression yields null, or if there are
   no equal right-hand values and at least one right-hand row yields
   null, the result of the <token>NOT IN</token> construct will be null, not true.
   This is in accordance with SQL's normal rules for Boolean combinations
   of null values.
  </para>

  <para>
   As with <token>EXISTS</token>, it's unwise to assume that the subquery will
   be evaluated completely.
  </para>

<synopsis>
<replaceable>row_constructor</replaceable> NOT IN (<replaceable>subquery</replaceable>)
</synopsis>

  <para>
   The left-hand side of this form of <token>NOT IN</token> is a row constructor,
   as described in <xref linkend="sql-syntax-row-constructors">.
   The right-hand side is a parenthesized
   subquery, which must return exactly as many columns as there are
   expressions in the left-hand row.  The left-hand expressions are
   evaluated and compared row-wise to each row of the subquery result.
   The result of <token>NOT IN</token> is <quote>true</> if only unequal subquery rows
   are found (including the special case where the subquery returns no rows).
   The result is <quote>false</> if any equal row is found.
8193 8194
  </para>

J
Joe Conway 已提交
8195
  <para>
8196 8197 8198 8199 8200
   As usual, null values in the rows are combined per
   the normal rules of SQL Boolean expressions.  Two rows are considered
   equal if all their corresponding members are non-null and equal; the rows
   are unequal if any corresponding members are non-null and unequal;
   otherwise the result of that row comparison is unknown (null).
8201 8202
   If all the per-row results are either unequal or null, with at least one
   null, then the result of <token>NOT IN</token> is null.
J
Joe Conway 已提交
8203
  </para>
8204
  </sect2>
J
Joe Conway 已提交
8205

8206 8207
  <sect2>
   <title><literal>ANY</literal>/<literal>SOME</literal></title>
8208

8209 8210 8211 8212
<synopsis>
<replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>subquery</replaceable>)
<replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>subquery</replaceable>)
</synopsis>
8213

8214 8215 8216 8217 8218 8219 8220 8221 8222 8223
  <para>
   The right-hand side is a parenthesized
   subquery, which must return exactly one column.  The left-hand expression
   is evaluated and compared to each row of the subquery result using the
   given <replaceable>operator</replaceable>, which must yield a Boolean
   result.
   The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
   The result is <quote>false</> if no true result is found (including the special
   case where the subquery returns no rows).
  </para>
P
Peter Eisentraut 已提交
8224

8225 8226 8227 8228
  <para>
   <token>SOME</token> is a synonym for <token>ANY</token>.
   <token>IN</token> is equivalent to <literal>= ANY</literal>.
  </para>
8229

8230 8231 8232 8233 8234 8235 8236
  <para>
   Note that if there are no successes and at least one right-hand row yields
   null for the operator's result, the result of the <token>ANY</token> construct
   will be null, not false.
   This is in accordance with SQL's normal rules for Boolean combinations
   of null values.
  </para>
8237

8238 8239 8240 8241
  <para>
   As with <token>EXISTS</token>, it's unwise to assume that the subquery will
   be evaluated completely.
  </para>
8242

8243 8244 8245 8246
<synopsis>
<replaceable>row_constructor</replaceable> <replaceable>operator</> ANY (<replaceable>subquery</replaceable>)
<replaceable>row_constructor</replaceable> <replaceable>operator</> SOME (<replaceable>subquery</replaceable>)
</synopsis>
8247

8248 8249 8250 8251 8252 8253 8254
  <para>
   The left-hand side of this form of <token>ANY</token> is a row constructor,
   as described in <xref linkend="sql-syntax-row-constructors">.
   The right-hand side is a parenthesized
   subquery, which must return exactly as many columns as there are
   expressions in the left-hand row.  The left-hand expressions are
   evaluated and compared row-wise to each row of the subquery result,
8255 8256 8257 8258 8259 8260 8261 8262
   using the given <replaceable>operator</replaceable>.
   The result of <token>ANY</token> is <quote>true</> if the comparison
   returns true for any subquery row.
   The result is <quote>false</> if the comparison returns false for every
   subquery row (including the special case where the subquery returns no
   rows).
   The result is NULL if the comparison does not return true for any row,
   and it returns NULL for at least one row.
8263
  </para>
8264

8265
  <para>
8266 8267
   See <xref linkend="row-wise-comparison"> for details about the meaning
   of a row-wise comparison.
8268 8269
  </para>
  </sect2>
8270

8271 8272
  <sect2>
   <title><literal>ALL</literal></title>
8273

8274 8275 8276
<synopsis>
<replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
</synopsis>
8277

8278 8279 8280 8281 8282 8283 8284 8285 8286
  <para>
   The right-hand side is a parenthesized
   subquery, which must return exactly one column.  The left-hand expression
   is evaluated and compared to each row of the subquery result using the
   given <replaceable>operator</replaceable>, which must yield a Boolean
   result.
   The result of <token>ALL</token> is <quote>true</> if all rows yield true
   (including the special case where the subquery returns no rows).
   The result is <quote>false</> if any false result is found.
8287 8288
   The result is NULL if the comparison does not return false for any row,
   and it returns NULL for at least one row.
8289
  </para>
8290

8291 8292 8293
  <para>
   <token>NOT IN</token> is equivalent to <literal>&lt;&gt; ALL</literal>.
  </para>
8294

8295 8296 8297 8298
  <para>
   As with <token>EXISTS</token>, it's unwise to assume that the subquery will
   be evaluated completely.
  </para>
8299

8300 8301 8302
<synopsis>
<replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
</synopsis>
8303 8304

  <para>
8305 8306 8307 8308 8309 8310
   The left-hand side of this form of <token>ALL</token> is a row constructor,
   as described in <xref linkend="sql-syntax-row-constructors">.
   The right-hand side is a parenthesized
   subquery, which must return exactly as many columns as there are
   expressions in the left-hand row.  The left-hand expressions are
   evaluated and compared row-wise to each row of the subquery result,
8311 8312 8313
   using the given <replaceable>operator</replaceable>.
   The result of <token>ALL</token> is <quote>true</> if the comparison
   returns true for all subquery rows (including the special
8314
   case where the subquery returns no rows).
8315 8316 8317 8318
   The result is <quote>false</> if the comparison returns false for any
   subquery row.
   The result is NULL if the comparison does not return false for any
   subquery row, and it returns NULL for at least one row.
8319 8320
  </para>

8321
  <para>
8322 8323
   See <xref linkend="row-wise-comparison"> for details about the meaning
   of a row-wise comparison.
8324 8325 8326 8327 8328 8329
  </para>
  </sect2>

  <sect2>
   <title>Row-wise Comparison</title>

8330
   <indexterm zone="functions-subquery">
8331
    <primary>comparison</primary>
8332
    <secondary>subquery result row</secondary>
8333 8334 8335 8336 8337
   </indexterm>

<synopsis>
<replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> (<replaceable>subquery</replaceable>)
</synopsis>
8338

8339 8340 8341 8342 8343 8344 8345 8346 8347
  <para>
   The left-hand side is a row constructor,
   as described in <xref linkend="sql-syntax-row-constructors">.
   The right-hand side is a parenthesized subquery, which must return exactly
   as many columns as there are expressions in the left-hand row. Furthermore,
   the subquery cannot return more than one row.  (If it returns zero rows,
   the result is taken to be null.)  The left-hand side is evaluated and
   compared row-wise to the single subquery result row.
  </para>
8348

8349
  <para>
8350 8351
   See <xref linkend="row-wise-comparison"> for details about the meaning
   of a row-wise comparison.
8352 8353 8354
  </para>
  </sect2>
 </sect1>
8355 8356


8357 8358
 <sect1 id="functions-comparisons">
  <title>Row and Array Comparisons</title>
8359

8360 8361 8362
  <indexterm>
   <primary>IN</primary>
  </indexterm>
8363

8364 8365 8366
  <indexterm>
   <primary>NOT IN</primary>
  </indexterm>
8367

8368 8369 8370
  <indexterm>
   <primary>ANY</primary>
  </indexterm>
8371

8372 8373 8374
  <indexterm>
   <primary>ALL</primary>
  </indexterm>
8375

8376 8377 8378
  <indexterm>
   <primary>SOME</primary>
  </indexterm>
8379

8380 8381 8382 8383
  <indexterm>
   <primary>row-wise comparison</primary>
  </indexterm>

8384 8385 8386 8387 8388 8389 8390 8391 8392
  <indexterm>
   <primary>comparison</primary>
   <secondary>row-wise</secondary>
  </indexterm>

  <indexterm>
   <primary>IS DISTINCT FROM</primary>
  </indexterm>

8393 8394 8395 8396
  <indexterm>
   <primary>IS NOT DISTINCT FROM</primary>
  </indexterm>

8397 8398 8399 8400 8401 8402 8403 8404
  <indexterm>
   <primary>IS NULL</primary>
  </indexterm>

  <indexterm>
   <primary>IS NOT NULL</primary>
  </indexterm>

8405
  <para>
8406 8407 8408 8409 8410 8411 8412 8413 8414
   This section describes several specialized constructs for making
   multiple comparisons between groups of values.  These forms are
   syntactically related to the subquery forms of the previous section,
   but do not involve subqueries.
   The forms involving array subexpressions are
   <productname>PostgreSQL</productname> extensions; the rest are
   <acronym>SQL</acronym>-compliant.
   All of the expression forms documented in this section return
   Boolean (true/false) results.
8415 8416
  </para>

8417 8418
  <sect2>
   <title><literal>IN</literal></title>
8419

8420
<synopsis>
8421
<replaceable>expression</replaceable> IN (<replaceable>value</replaceable> <optional>, ...</optional>)
8422 8423 8424 8425 8426 8427 8428
</synopsis>

  <para>
   The right-hand side is a parenthesized list
   of scalar expressions.  The result is <quote>true</> if the left-hand expression's
   result is equal to any of the right-hand expressions.  This is a shorthand
   notation for
8429

8430 8431 8432 8433 8434 8435 8436 8437
<synopsis>
<replaceable>expression</replaceable> = <replaceable>value1</replaceable>
OR
<replaceable>expression</replaceable> = <replaceable>value2</replaceable>
OR
...
</synopsis>
  </para>
8438

8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451
  <para>
   Note that if the left-hand expression yields null, or if there are
   no equal right-hand values and at least one right-hand expression yields
   null, the result of the <token>IN</token> construct will be null, not false.
   This is in accordance with SQL's normal rules for Boolean combinations
   of null values.
  </para>
  </sect2>

  <sect2>
   <title><literal>NOT IN</literal></title>

<synopsis>
8452
<replaceable>expression</replaceable> NOT IN (<replaceable>value</replaceable> <optional>, ...</optional>)
8453
</synopsis>
P
Peter Eisentraut 已提交
8454

8455
  <para>
8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467
   The right-hand side is a parenthesized list
   of scalar expressions.  The result is <quote>true</quote> if the left-hand expression's
   result is unequal to all of the right-hand expressions.  This is a shorthand
   notation for

<synopsis>
<replaceable>expression</replaceable> &lt;&gt; <replaceable>value1</replaceable>
AND
<replaceable>expression</replaceable> &lt;&gt; <replaceable>value2</replaceable>
AND
...
</synopsis>
8468
  </para>
8469

8470 8471 8472 8473 8474 8475 8476 8477
  <para>
   Note that if the left-hand expression yields null, or if there are
   no equal right-hand values and at least one right-hand expression yields
   null, the result of the <token>NOT IN</token> construct will be null, not true
   as one might naively expect.
   This is in accordance with SQL's normal rules for Boolean combinations
   of null values.
  </para>
8478

8479 8480 8481 8482 8483 8484 8485 8486 8487
  <tip>
  <para>
   <literal>x NOT IN y</literal> is equivalent to <literal>NOT (x IN y)</literal> in all
   cases.  However, null values are much more likely to trip up the novice when
   working with <token>NOT IN</token> than when working with <token>IN</token>.
   It's best to express your condition positively if possible.
  </para>
  </tip>
  </sect2>
8488

8489 8490
  <sect2>
   <title><literal>ANY</literal>/<literal>SOME</literal> (array)</title>
8491

8492 8493 8494 8495
<synopsis>
<replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>array expression</replaceable>)
<replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>array expression</replaceable>)
</synopsis>
B
Bruce Momjian 已提交
8496

8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507
  <para>
   The right-hand side is a parenthesized expression, which must yield an
   array value.
   The left-hand expression
   is evaluated and compared to each element of the array using the
   given <replaceable>operator</replaceable>, which must yield a Boolean
   result.
   The result of <token>ANY</token> is <quote>true</> if any true result is obtained.
   The result is <quote>false</> if no true result is found (including the special
   case where the array has zero elements).
  </para>
B
Bruce Momjian 已提交
8508

8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520
  <para>
   If the array expression yields a null array, the result of
   <token>ANY</token> will be null.  If the left-hand expression yields null,
   the result of <token>ANY</token> is ordinarily null (though a non-strict
   comparison operator could possibly yield a different result).
   Also, if the right-hand array contains any null elements and no true
   comparison result is obtained, the result of <token>ANY</token>
   will be null, not false (again, assuming a strict comparison operator).
   This is in accordance with SQL's normal rules for Boolean combinations
   of null values.
  </para>

8521 8522 8523 8524
  <para>
   <token>SOME</token> is a synonym for <token>ANY</token>.
  </para>
  </sect2>
B
Bruce Momjian 已提交
8525

8526 8527
  <sect2>
   <title><literal>ALL</literal> (array)</title>
B
Bruce Momjian 已提交
8528

8529 8530 8531
<synopsis>
<replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>array expression</replaceable>)
</synopsis>
8532

8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543
  <para>
   The right-hand side is a parenthesized expression, which must yield an
   array value.
   The left-hand expression
   is evaluated and compared to each element of the array using the
   given <replaceable>operator</replaceable>, which must yield a Boolean
   result.
   The result of <token>ALL</token> is <quote>true</> if all comparisons yield true
   (including the special case where the array has zero elements).
   The result is <quote>false</> if any false result is found.
  </para>
8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555

  <para>
   If the array expression yields a null array, the result of
   <token>ALL</token> will be null.  If the left-hand expression yields null,
   the result of <token>ALL</token> is ordinarily null (though a non-strict
   comparison operator could possibly yield a different result).
   Also, if the right-hand array contains any null elements and no false
   comparison result is obtained, the result of <token>ALL</token>
   will be null, not true (again, assuming a strict comparison operator).
   This is in accordance with SQL's normal rules for Boolean combinations
   of null values.
  </para>
8556 8557
  </sect2>

8558
  <sect2 id="row-wise-comparison">
8559 8560 8561 8562 8563 8564 8565 8566 8567 8568
   <title>Row-wise Comparison</title>

<synopsis>
<replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> <replaceable>row_constructor</replaceable>
</synopsis>

  <para>
   Each side is a row constructor,
   as described in <xref linkend="sql-syntax-row-constructors">.
   The two row values must have the same number of fields.
8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580
   Each side is evaluated and they are compared row-wise.  Row comparisons
   are allowed when the <replaceable>operator</replaceable> is
   <literal>=</>,
   <literal>&lt;&gt;</>,
   <literal>&lt;</>,
   <literal>&lt;=</>,
   <literal>&gt;</> or
   <literal>&gt;=</>,
   or has semantics similar to one of these.  (To be specific, an operator
   can be a row comparison operator if it is a member of a btree operator
   class, or is the negator of the <literal>=</> member of a btree operator
   class.)
8581 8582 8583
  </para>

  <para>
8584 8585
   The <literal>=</> and <literal>&lt;&gt;</> cases work slightly differently
   from the others.  Two rows are considered
8586 8587 8588 8589 8590
   equal if all their corresponding members are non-null and equal; the rows
   are unequal if any corresponding members are non-null and unequal;
   otherwise the result of the row comparison is unknown (null).
  </para>

8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614
  <para>
   For the <literal>&lt;</>, <literal>&lt;=</>, <literal>&gt;</> and
   <literal>&gt;=</> cases, the row elements are compared left-to-right,
   stopping as soon as an unequal or null pair of elements is found.
   If either of this pair of elements is null, the result of the
   row comparison is unknown (null); otherwise comparison of this pair
   of elements determines the result.  For example,
   <literal>ROW(1,2,NULL) &lt; ROW(1,3,0)</>
   yields true, not null, because the third pair of elements are not
   considered.
  </para>

  <note>
   <para>
    Prior to <productname>PostgreSQL</productname> 8.2, the
    <literal>&lt;</>, <literal>&lt;=</>, <literal>&gt;</> and <literal>&gt;=</>
    cases were not handled per SQL specification.  A comparison like
    <literal>ROW(a,b) &lt; ROW(c,d)</>
    was implemented as
    <literal>a &lt; c AND b &lt; d</>
    whereas the correct behavior is equivalent to
    <literal>a &lt; c OR (a = c AND b &lt; d)</>.
   </para>
  </note>
8615

8616 8617 8618 8619 8620 8621 8622 8623
<synopsis>
<replaceable>row_constructor</replaceable> IS DISTINCT FROM <replaceable>row_constructor</replaceable>
</synopsis>

  <para>
   This construct is similar to a <literal>&lt;&gt;</literal> row comparison,
   but it does not yield null for null inputs.  Instead, any null value is
   considered unequal to (distinct from) any non-null value, and any two
8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635
   nulls are considered equal (not distinct).  Thus the result will always
   be either true or false, never null.
  </para>

<synopsis>
<replaceable>row_constructor</replaceable> IS NOT DISTINCT FROM <replaceable>row_constructor</replaceable>
</synopsis>

  <para>
   This construct is similar to a <literal>=</literal> row comparison,
   but it does not yield null for null inputs.  Instead, any null value is
   considered unequal to (distinct from) any non-null value, and any two
8636 8637 8638 8639 8640 8641 8642 8643
   nulls are considered equal (not distinct).  Thus the result will always
   be either true or false, never null.
  </para>

<synopsis>
<replaceable>row_constructor</replaceable> IS NULL
<replaceable>row_constructor</replaceable> IS NOT NULL
</synopsis>
8644

8645 8646 8647 8648
  <para>
   These constructs test a row value for null or not null.  A row value
   is considered not null if it has at least one field that is not null.
  </para>
B
Bruce Momjian 已提交
8649

8650 8651
  </sect2>
 </sect1>
8652

8653 8654 8655 8656 8657 8658 8659 8660
 <sect1 id="functions-srf">
  <title>Set Returning Functions</title>

  <indexterm zone="functions-srf">
   <primary>set returning functions</primary>
   <secondary>functions</secondary>
  </indexterm>

8661 8662 8663 8664
  <indexterm>
   <primary>generate_series</primary>
  </indexterm>

8665 8666 8667 8668 8669
  <para>
   This section describes functions that possibly return more than one row.
   Currently the only functions in this class are series generating functions,
   as detailed in <xref linkend="functions-srf-series">.
  </para>
8670

8671 8672 8673 8674
  <table id="functions-srf-series">
   <title>Series Generating Functions</title>
   <tgroup cols="4">
    <thead>
8675
     <row>
8676 8677 8678 8679
      <entry>Function</entry>
      <entry>Argument Type</entry>
      <entry>Return Type</entry>
      <entry>Description</entry>
8680
     </row>
8681
    </thead>
8682

8683
    <tbody>
8684
     <row>
8685 8686 8687
      <entry><literal><function>generate_series</function>(<parameter>start</parameter>, <parameter>stop</parameter>)</literal></entry>
      <entry><type>int</type> or <type>bigint</type></entry>
      <entry><type>setof int</type> or <type>setof bigint</type> (same as argument type)</entry>
8688
      <entry>
8689
       Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
8690
       with a step size of one
8691 8692 8693 8694
      </entry>
     </row>

     <row>
8695 8696 8697
      <entry><literal><function>generate_series</function>(<parameter>start</parameter>, <parameter>stop</parameter>, <parameter>step</parameter>)</literal></entry>
      <entry><type>int</type> or <type>bigint</type></entry>
      <entry><type>setof int</type> or <type>setof bigint</type> (same as argument type)</entry>
8698
      <entry>
8699
       Generate a series of values, from <parameter>start</parameter> to <parameter>stop</parameter>
8700
       with a step size of <parameter>step</parameter>
8701 8702 8703 8704 8705 8706
      </entry>
     </row>

    </tbody>
   </tgroup>
  </table>
8707

8708
  <para>
8709 8710 8711 8712 8713 8714
   When <parameter>step</parameter> is positive, zero rows are returned if
   <parameter>start</parameter> is greater than <parameter>stop</parameter>.
   Conversely, when <parameter>step</parameter> is negative, zero rows are
   returned if <parameter>start</parameter> is less than <parameter>stop</parameter>.
   Zero rows are also returned for <literal>NULL</literal> inputs. It is an error
   for <parameter>step</parameter> to be zero. Some examples follow:
B
Bruce Momjian 已提交
8715
<programlisting>
8716 8717 8718 8719 8720 8721 8722
select * from generate_series(2,4);
 generate_series
-----------------
               2
               3
               4
(3 rows)
B
Bruce Momjian 已提交
8723

8724 8725 8726 8727 8728 8729 8730
select * from generate_series(5,1,-2);
 generate_series
-----------------
               5
               3
               1
(3 rows)
8731

8732 8733 8734 8735
select * from generate_series(4,3);
 generate_series
-----------------
(0 rows)
8736

8737 8738 8739 8740 8741 8742 8743
select current_date + s.a as dates from generate_series(0,14,7) as s(a);
   dates
------------
 2004-02-05
 2004-02-12
 2004-02-19
(3 rows)
8744
</programlisting>
8745
  </para>
8746
 </sect1>
8747

8748 8749
 <sect1 id="functions-info">
  <title>System Information Functions</title>
8750

8751 8752 8753 8754
  <para>
   <xref linkend="functions-info-session-table"> shows several
   functions that extract session and system information.
  </para>
8755

8756 8757 8758 8759 8760 8761
   <table id="functions-info-session-table">
    <title>Session Information Functions</title>
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
     </thead>
8762

8763 8764
     <tbody>
      <row>
N
Neil Conway 已提交
8765
       <entry><literal><function>current_database</function>()</literal></entry>
8766 8767 8768
       <entry><type>name</type></entry>
       <entry>name of current database</entry>
      </row>
8769

8770
      <row>
N
Neil Conway 已提交
8771
       <entry><literal><function>current_schema</function>()</literal></entry>
8772 8773 8774
       <entry><type>name</type></entry>
       <entry>name of current schema</entry>
      </row>
8775

8776
      <row>
N
Neil Conway 已提交
8777
       <entry><literal><function>current_schemas</function>(<type>boolean</type>)</literal></entry>
8778 8779 8780
       <entry><type>name[]</type></entry>
       <entry>names of schemas in search path optionally including implicit schemas</entry>
      </row>
8781

8782
      <row>
N
Neil Conway 已提交
8783
       <entry><literal><function>current_user</function></literal></entry>
8784 8785 8786
       <entry><type>name</type></entry>
       <entry>user name of current execution context</entry>
      </row>
8787

8788
      <row>
N
Neil Conway 已提交
8789
       <entry><literal><function>inet_client_addr</function>()</literal></entry>
8790 8791 8792
       <entry><type>inet</type></entry>
       <entry>address of the remote connection</entry>
      </row>
8793

8794
      <row>
N
Neil Conway 已提交
8795
       <entry><literal><function>inet_client_port</function>()</literal></entry>
8796
       <entry><type>int</type></entry>
8797 8798
       <entry>port of the remote connection</entry>
      </row>
8799

8800
      <row>
N
Neil Conway 已提交
8801
       <entry><literal><function>inet_server_addr</function>()</literal></entry>
8802 8803 8804
       <entry><type>inet</type></entry>
       <entry>address of the local connection</entry>
      </row>
8805

8806
      <row>
N
Neil Conway 已提交
8807
       <entry><literal><function>inet_server_port</function>()</literal></entry>
8808
       <entry><type>int</type></entry>
8809 8810
       <entry>port of the local connection</entry>
      </row>
8811

8812
      <row>
N
Neil Conway 已提交
8813
       <entry><literal><function>session_user</function></literal></entry>
8814 8815 8816
       <entry><type>name</type></entry>
       <entry>session user name</entry>
      </row>
8817

8818
      <row>
N
Neil Conway 已提交
8819
       <entry><literal><function>pg_postmaster_start_time</function>()</literal></entry>
8820 8821 8822 8823
       <entry><type>timestamp with time zone</type></entry>
       <entry><command>postmaster</> start time</entry>
      </row>

8824
      <row>
N
Neil Conway 已提交
8825
       <entry><literal><function>user</function></literal></entry>
8826 8827 8828
       <entry><type>name</type></entry>
       <entry>equivalent to <function>current_user</function></entry>
      </row>
8829

8830
      <row>
N
Neil Conway 已提交
8831
       <entry><literal><function>version</function>()</literal></entry>
8832
       <entry><type>text</type></entry>
N
Neil Conway 已提交
8833
       <entry><productname>PostgreSQL</> version information</entry>
8834 8835 8836 8837
      </row>
     </tbody>
    </tgroup>
   </table>
8838

8839 8840 8841 8842
   <indexterm zone="functions-info">
    <primary>user</primary>
    <secondary>current</secondary>
   </indexterm>
8843

8844 8845 8846 8847
   <indexterm zone="functions-info">
    <primary>schema</primary>
    <secondary>current</secondary>
   </indexterm>
8848

8849 8850 8851 8852
   <indexterm zone="functions-info">
    <primary>search path</primary>
    <secondary>current</secondary>
   </indexterm>
8853

8854
   <para>
T
Tom Lane 已提交
8855 8856
    The <function>session_user</function> is normally the user who initiated
    the current database connection; but superusers can change this setting
8857
    with <xref linkend="sql-set-session-authorization" endterm="sql-set-session-authorization-title">.
T
Tom Lane 已提交
8858
    The <function>current_user</function> is the user identifier
8859
    that is applicable for permission checking. Normally, it is equal
8860 8861 8862
    to the session user, but it can be changed with
    <xref linkend="sql-set-role" endterm="sql-set-role-title">.
    It also changes during the execution of
8863 8864 8865 8866
    functions with the attribute <literal>SECURITY DEFINER</literal>.
    In Unix parlance, the session user is the <quote>real user</quote> and
    the current user is the <quote>effective user</quote>.
   </para>
8867

8868 8869 8870 8871 8872 8873 8874
   <note>
    <para>
     <function>current_user</function>, <function>session_user</function>, and
     <function>user</function> have special syntactic status in <acronym>SQL</acronym>:
     they must be called without trailing parentheses.
    </para>
   </note>
8875

8876 8877 8878 8879 8880 8881 8882 8883 8884 8885
   <para>
    <function>current_schema</function> returns the name of the schema that is
    at the front of the search path (or a null value if the search path is
    empty).  This is the schema that will be used for any tables or
    other named objects that are created without specifying a target schema.
    <function>current_schemas(boolean)</function> returns an array of the names of all
    schemas presently in the search path.  The Boolean option determines whether or not
    implicitly included system schemas such as <literal>pg_catalog</> are included in the search 
    path returned.
   </para>
8886

8887 8888 8889 8890 8891 8892 8893 8894
   <note>
    <para>
     The search path may be altered at run time.  The command is:
<programlisting>
SET search_path TO <replaceable>schema</> <optional>, <replaceable>schema</>, ...</optional>
</programlisting>
    </para>
   </note>
8895

8896 8897 8898
   <indexterm zone="functions-info">
    <primary>inet_client_addr</primary>
   </indexterm>
8899

8900 8901 8902
   <indexterm zone="functions-info">
    <primary>inet_client_port</primary>
   </indexterm>
8903

8904 8905 8906
   <indexterm zone="functions-info">
    <primary>inet_server_addr</primary>
   </indexterm>
8907

8908 8909 8910
   <indexterm zone="functions-info">
    <primary>inet_server_port</primary>
   </indexterm>
8911

8912 8913 8914 8915 8916 8917 8918
   <para>
     <function>inet_client_addr</function> returns the IP address of the
     current client, and <function>inet_client_port</function> returns the
     port number.
     <function>inet_server_addr</function> returns the IP address on which
     the server accepted the current connection, and
     <function>inet_server_port</function> returns the port number.
T
Tom Lane 已提交
8919 8920
     All these functions return NULL if the current connection is via a
     Unix-domain socket.
8921
   </para>
8922

8923 8924 8925 8926 8927
   <indexterm zone="functions-info">
    <primary>pg_postmaster_start_time</primary>
   </indexterm>

   <para>
8928 8929 8930
     <function>pg_postmaster_start_time</function> returns the
     <type>timestamp with time zone</type> when the
     <command>postmaster</> started.
8931 8932
   </para>

8933 8934 8935
   <indexterm zone="functions-info">
    <primary>version</primary>
   </indexterm>
8936

8937
   <para>
N
Neil Conway 已提交
8938
    <function>version</function> returns a string describing the
8939 8940
    <productname>PostgreSQL</productname> server's version.
   </para>
8941

8942 8943 8944 8945
  <indexterm>
   <primary>privilege</primary>
   <secondary>querying</secondary>
  </indexterm>
8946 8947

  <para>
8948 8949 8950 8951
   <xref linkend="functions-info-access-table"> lists functions that
   allow the user to query object access privileges programmatically.
   See <xref linkend="ddl-priv"> for more information about
   privileges.
8952 8953
  </para>

8954 8955 8956 8957 8958 8959
   <table id="functions-info-access-table">
    <title>Access Privilege Inquiry Functions</title>
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
     </thead>
8960

8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021
     <tbody>
      <row>
       <entry><literal><function>has_table_privilege</function>(<parameter>user</parameter>,
                                  <parameter>table</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does user have privilege for table</entry>
      </row>
      <row>
       <entry><literal><function>has_table_privilege</function>(<parameter>table</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does current user have privilege for table</entry>
      </row>
      <row>
       <entry><literal><function>has_database_privilege</function>(<parameter>user</parameter>,
                                  <parameter>database</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does user have privilege for database</entry>
      </row>
      <row>
       <entry><literal><function>has_database_privilege</function>(<parameter>database</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does current user have privilege for database</entry>
      </row>
      <row>
       <entry><literal><function>has_function_privilege</function>(<parameter>user</parameter>,
                                  <parameter>function</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does user have privilege for function</entry>
      </row>
      <row>
       <entry><literal><function>has_function_privilege</function>(<parameter>function</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does current user have privilege for function</entry>
      </row>
      <row>
       <entry><literal><function>has_language_privilege</function>(<parameter>user</parameter>,
                                  <parameter>language</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does user have privilege for language</entry>
      </row>
      <row>
       <entry><literal><function>has_language_privilege</function>(<parameter>language</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does current user have privilege for language</entry>
      </row>
9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036
      <row>
       <entry><literal><function>pg_has_role</function>(<parameter>user</parameter>,
                                  <parameter>role</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does user have privilege for role</entry>
      </row>
      <row>
       <entry><literal><function>pg_has_role</function>(<parameter>role</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does current user have privilege for role</entry>
      </row>
9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069
      <row>
       <entry><literal><function>has_schema_privilege</function>(<parameter>user</parameter>,
                                  <parameter>schema</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does user have privilege for schema</entry>
      </row>
      <row>
       <entry><literal><function>has_schema_privilege</function>(<parameter>schema</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does current user have privilege for schema</entry>
      </row>
      <row>
       <entry><literal><function>has_tablespace_privilege</function>(<parameter>user</parameter>,
                                  <parameter>tablespace</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does user have privilege for tablespace</entry>
      </row>
      <row>
       <entry><literal><function>has_tablespace_privilege</function>(<parameter>tablespace</parameter>,
                                  <parameter>privilege</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>does current user have privilege for tablespace</entry>
      </row>
     </tbody>
    </tgroup>
   </table>
9070

9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082
   <indexterm zone="functions-info">
    <primary>has_table_privilege</primary>
   </indexterm>
   <indexterm zone="functions-info">
    <primary>has_database_privilege</primary>
   </indexterm>
   <indexterm zone="functions-info">
    <primary>has_function_privilege</primary>
   </indexterm>
   <indexterm zone="functions-info">
    <primary>has_language_privilege</primary>
   </indexterm>
9083 9084 9085
   <indexterm zone="functions-info">
    <primary>pg_has_role</primary>
   </indexterm>
9086 9087 9088 9089 9090 9091
   <indexterm zone="functions-info">
    <primary>has_schema_privilege</primary>
   </indexterm>
   <indexterm zone="functions-info">
    <primary>has_tablespace_privilege</primary>
   </indexterm>
9092

9093 9094 9095
   <para>
    <function>has_table_privilege</function> checks whether a user
    can access a table in a particular way.  The user can be
9096 9097
    specified by name or by OID
    (<literal>pg_authid.oid</literal>), or if the argument is
9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113
    omitted
    <function>current_user</function> is assumed.  The table can be specified
    by name or by OID.  (Thus, there are actually six variants of
    <function>has_table_privilege</function>, which can be distinguished by
    the number and types of their arguments.)  When specifying by name,
    the name can be schema-qualified if necessary.
    The desired access privilege type
    is specified by a text string, which must evaluate to one of the
    values <literal>SELECT</literal>, <literal>INSERT</literal>, <literal>UPDATE</literal>,
    <literal>DELETE</literal>, <literal>RULE</literal>, <literal>REFERENCES</literal>, or
    <literal>TRIGGER</literal>.  (Case of the string is not significant, however.)
    An example is:
<programlisting>
SELECT has_table_privilege('myschema.mytable', 'select');
</programlisting>
   </para>
9114

9115 9116 9117 9118 9119 9120 9121 9122 9123 9124
   <para>
    <function>has_database_privilege</function> checks whether a user
    can access a database in a particular way.  The possibilities for its
    arguments are analogous to <function>has_table_privilege</function>.
    The desired access privilege type must evaluate to
    <literal>CREATE</literal>,
    <literal>TEMPORARY</literal>, or
    <literal>TEMP</literal> (which is equivalent to
    <literal>TEMPORARY</literal>).
   </para>
9125

9126 9127 9128 9129 9130
   <para>
    <function>has_function_privilege</function> checks whether a user
    can access a function in a particular way.  The possibilities for its
    arguments are analogous to <function>has_table_privilege</function>.
    When specifying a function by a text string rather than by OID,
9131 9132
    the allowed input is the same as for the <type>regprocedure</> data type
    (see <xref linkend="datatype-oid">).
9133 9134 9135 9136 9137 9138 9139
    The desired access privilege type must evaluate to
    <literal>EXECUTE</literal>.
    An example is:
<programlisting>
SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');
</programlisting>
   </para>
9140

9141 9142 9143 9144 9145 9146 9147 9148
   <para>
    <function>has_language_privilege</function> checks whether a user
    can access a procedural language in a particular way.  The possibilities
    for its arguments are analogous to <function>has_table_privilege</function>.
    The desired access privilege type must evaluate to
    <literal>USAGE</literal>.
   </para>

9149 9150 9151 9152 9153
   <para>
    <function>pg_has_role</function> checks whether a user
    can access a role in a particular way.  The possibilities for its
    arguments are analogous to <function>has_table_privilege</function>.
    The desired access privilege type must evaluate to
9154 9155 9156 9157 9158 9159
    <literal>MEMBER</literal> or
    <literal>USAGE</literal>.
    <literal>MEMBER</literal> denotes direct or indirect membership in
    the role (that is, the right to do <literal>SET ROLE</>), while
    <literal>USAGE</literal> denotes whether the privileges of the role
    are immediately available without doing <literal>SET ROLE</>.
9160 9161
   </para>

9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177
   <para>
    <function>has_schema_privilege</function> checks whether a user
    can access a schema in a particular way.  The possibilities for its
    arguments are analogous to <function>has_table_privilege</function>.
    The desired access privilege type must evaluate to
    <literal>CREATE</literal> or
    <literal>USAGE</literal>.
   </para>

   <para>
    <function>has_tablespace_privilege</function> checks whether a user
    can access a tablespace in a particular way.  The possibilities for its
    arguments are analogous to <function>has_table_privilege</function>.
    The desired access privilege type must evaluate to
    <literal>CREATE</literal>.
   </para>
9178 9179

  <para>
T
Tom Lane 已提交
9180
   To test whether a user holds a grant option on the privilege,
9181 9182
   append <literal> WITH GRANT OPTION</literal> to the privilege key
   word; for example <literal>'UPDATE WITH GRANT OPTION'</literal>.
9183 9184 9185
  </para>

  <para>
9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196
   <xref linkend="functions-info-schema-table"> shows functions that
   determine whether a certain object is <firstterm>visible</> in the
   current schema search path.  A table is said to be visible if its
   containing schema is in the search path and no table of the same
   name appears earlier in the search path.  This is equivalent to the
   statement that the table can be referenced by name without explicit
   schema qualification.  For example, to list the names of all
   visible tables:
<programlisting>
SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
</programlisting>
9197 9198
  </para>

9199 9200 9201 9202 9203 9204
   <table id="functions-info-schema-table">
    <title>Schema Visibility Inquiry Functions</title>
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
     </thead>
9205

9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245
     <tbody>
      <row>
       <entry><literal><function>pg_table_is_visible</function>(<parameter>table_oid</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>is table visible in search path</entry>
      </row>
      <row>
       <entry><literal><function>pg_type_is_visible</function>(<parameter>type_oid</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>is type (or domain) visible in search path</entry>
      </row>
      <row>
       <entry><literal><function>pg_function_is_visible</function>(<parameter>function_oid</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>is function visible in search path</entry>
      </row>
      <row>
       <entry><literal><function>pg_operator_is_visible</function>(<parameter>operator_oid</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>is operator visible in search path</entry>
      </row>
      <row>
       <entry><literal><function>pg_opclass_is_visible</function>(<parameter>opclass_oid</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>is operator class visible in search path</entry>
      </row>
      <row>
       <entry><literal><function>pg_conversion_is_visible</function>(<parameter>conversion_oid</parameter>)</literal>
       </entry>
       <entry><type>boolean</type></entry>
       <entry>is conversion visible in search path</entry>
      </row>
     </tbody>
    </tgroup>
   </table>
9246

9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264
   <indexterm zone="functions-info">
    <primary>pg_table_is_visible</primary>
   </indexterm>
   <indexterm zone="functions-info">
    <primary>pg_type_is_visible</primary>
   </indexterm>
   <indexterm zone="functions-info">
    <primary>pg_function_is_visible</primary>
   </indexterm>
   <indexterm zone="functions-info">
    <primary>pg_operator_is_visible</primary>
   </indexterm>
   <indexterm zone="functions-info">
    <primary>pg_opclass_is_visible</primary>
   </indexterm>
   <indexterm zone="functions-info">
    <primary>pg_conversion_is_visible</primary>
   </indexterm>
9265

9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280
   <para>
   <function>pg_table_is_visible</function> performs the check for
   tables (or views, or any other kind of <literal>pg_class</> entry).
   <function>pg_type_is_visible</function>,
   <function>pg_function_is_visible</function>,
   <function>pg_operator_is_visible</function>,
   <function>pg_opclass_is_visible</function>, and
   <function>pg_conversion_is_visible</function> perform the same sort of
   visibility check for types (and domains), functions, operators, operator classes
   and conversions, respectively.  For functions and operators, an object in
   the search path is visible if there is no object of the same name
   <emphasis>and argument data type(s)</> earlier in the path.  For
   operator classes, both name and associated index access method are
   considered.
   </para>
9281

9282 9283 9284 9285 9286 9287 9288 9289 9290
   <para>
    All these functions require object OIDs to identify the object to be
    checked.  If you want to test an object by name, it is convenient to use
    the OID alias types (<type>regclass</>, <type>regtype</>,
    <type>regprocedure</>, or <type>regoperator</>), for example
<programlisting>
SELECT pg_type_is_visible('myschema.widget'::regtype);
</programlisting>
    Note that it would not make much sense to test an unqualified name in
9291
    this way &mdash; if the name can be recognized at all, it must be visible.
9292
   </para>
9293

9294 9295 9296 9297
   <indexterm zone="functions-info">
    <primary>format_type</primary>
   </indexterm>

9298 9299 9300
   <indexterm zone="functions-info">
    <primary>pg_get_viewdef</primary>
   </indexterm>
9301

9302 9303 9304
   <indexterm zone="functions-info">
    <primary>pg_get_ruledef</primary>
   </indexterm>
9305

9306 9307 9308
   <indexterm zone="functions-info">
    <primary>pg_get_indexdef</primary>
   </indexterm>
9309

9310 9311 9312
   <indexterm zone="functions-info">
    <primary>pg_get_triggerdef</primary>
   </indexterm>
9313

9314 9315 9316
   <indexterm zone="functions-info">
    <primary>pg_get_constraintdef</primary>
   </indexterm>
9317

9318 9319
   <indexterm zone="functions-info">
    <primary>pg_get_expr</primary>
P
Peter Eisentraut 已提交
9320 9321
   </indexterm>

9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332
   <indexterm zone="functions-info">
    <primary>pg_get_userbyid</primary>
   </indexterm>

   <indexterm zone="functions-info">
    <primary>pg_get_serial_sequence</primary>
   </indexterm>

   <indexterm zone="functions-info">
    <primary>pg_tablespace_databases</primary>
   </indexterm>
9333 9334

  <para>
9335 9336
   <xref linkend="functions-info-catalog-table"> lists functions that
   extract information from the system catalogs.
9337 9338
  </para>

9339 9340 9341 9342 9343 9344 9345 9346
   <table id="functions-info-catalog-table">
    <title>System Catalog Information Functions</title>
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
     </thead>

     <tbody>
9347 9348 9349 9350 9351
      <row>
       <entry><literal><function>format_type</function>(<parameter>type_oid</parameter>, <parameter>typemod</>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get SQL name of a data type</entry>
      </row>
9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421
      <row>
       <entry><literal><function>pg_get_viewdef</function>(<parameter>view_name</parameter>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get <command>CREATE VIEW</> command for view (<emphasis>deprecated</emphasis>)</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_viewdef</function>(<parameter>view_name</parameter>, <parameter>pretty_bool</>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get <command>CREATE VIEW</> command for view (<emphasis>deprecated</emphasis>)</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_viewdef</function>(<parameter>view_oid</parameter>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get <command>CREATE VIEW</> command for view</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_viewdef</function>(<parameter>view_oid</parameter>, <parameter>pretty_bool</>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get <command>CREATE VIEW</> command for view</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_ruledef</function>(<parameter>rule_oid</parameter>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get <command>CREATE RULE</> command for rule</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_ruledef</function>(<parameter>rule_oid</parameter>, <parameter>pretty_bool</>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get <command>CREATE RULE</> command for rule</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_indexdef</function>(<parameter>index_oid</parameter>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get <command>CREATE INDEX</> command for index</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_indexdef</function>(<parameter>index_oid</parameter>, <parameter>column_no</>, <parameter>pretty_bool</>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get <command>CREATE INDEX</> command for index,
       or definition of just one index column when
       <parameter>column_no</> is not zero</entry>
      </row>
      <row>
       <entry><function>pg_get_triggerdef</function>(<parameter>trigger_oid</parameter>)</entry>
       <entry><type>text</type></entry>
       <entry>get <command>CREATE [ CONSTRAINT ] TRIGGER</> command for trigger</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_constraintdef</function>(<parameter>constraint_oid</parameter>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get definition of a constraint</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_constraintdef</function>(<parameter>constraint_oid</parameter>, <parameter>pretty_bool</>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get definition of a constraint</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_expr</function>(<parameter>expr_text</parameter>, <parameter>relation_oid</>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>decompile internal form of an expression, assuming that any Vars
       in it refer to the relation indicated by the second parameter</entry>
      </row>
      <row>
       <entry><literal><function>pg_get_expr</function>(<parameter>expr_text</parameter>, <parameter>relation_oid</>, <parameter>pretty_bool</>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>decompile internal form of an expression, assuming that any Vars
       in it refer to the relation indicated by the second parameter</entry>
      </row>
      <row>
9422
       <entry><literal><function>pg_get_userbyid</function>(<parameter>roleid</parameter>)</literal></entry>
9423
       <entry><type>name</type></entry>
9424
       <entry>get role name with given ID</entry>
9425 9426 9427 9428
      </row>
      <row>
       <entry><literal><function>pg_get_serial_sequence</function>(<parameter>table_name</parameter>, <parameter>column_name</parameter>)</literal></entry>
       <entry><type>text</type></entry>
P
Peter Eisentraut 已提交
9429
       <entry>get name of the sequence that a <type>serial</type> or <type>bigserial</type> column
9430 9431 9432 9433 9434
       uses</entry>
      </row>
      <row>
       <entry><literal><function>pg_tablespace_databases</function>(<parameter>tablespace_oid</parameter>)</literal></entry>
       <entry><type>setof oid</type></entry>
9435
       <entry>get the set of database OIDs that have objects in the tablespace</entry>
9436 9437 9438 9439 9440
      </row>
     </tbody>
    </tgroup>
   </table>

9441 9442 9443 9444 9445 9446
  <para>
   <function>format_type</function> returns the SQL name of a data type that
   is identified by its type OID and possibly a type modifier.  Pass NULL
   for the type modifier if no specific modifier is known.
  </para>

9447
  <para>
9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466
   <function>pg_get_viewdef</function>,
   <function>pg_get_ruledef</function>,
   <function>pg_get_indexdef</function>,
   <function>pg_get_triggerdef</function>, and
   <function>pg_get_constraintdef</function> respectively
   reconstruct the creating command for a view, rule, index, trigger, or
   constraint.  (Note that this is a decompiled reconstruction, not
   the original text of the command.)
   <function>pg_get_expr</function> decompiles the internal form of an
   individual expression, such as the default value for a column.  It
   may be useful when examining the contents of system catalogs.
   Most of these functions come in two
   variants, one of which can optionally <quote>pretty-print</> the result.
   The pretty-printed format is more readable, but the default format is more
   likely to be
   interpreted the same way by future versions of <productname>PostgreSQL</>;
   avoid using pretty-printed output for dump purposes.
   Passing <literal>false</> for the pretty-print parameter yields the
   same result as the variant that does not have the parameter at all.
9467 9468 9469
  </para>

  <para>
9470 9471
   <function>pg_get_userbyid</function> extracts a role's name given
   its OID.
9472 9473 9474
  </para>

  <para>
9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485
   <function>pg_get_serial_sequence</function> fetches the name of the
   sequence associated with a <type>serial</> or <type>bigserial</>
   column.  The name is suitably formatted for passing to the sequence
   functions (see <xref linkend="functions-sequence">).  NULL is
   returned if the column does not have an associated sequence.
  </para>

  <para>
  <function>pg_tablespace_databases</function> allows a tablespace to
  be examined. It returns the set of OIDs of databases that have objects
  stored in the tablespace. If this function returns any rows, the
9486 9487 9488 9489 9490
  tablespace is not empty and cannot be dropped. To
  display the specific objects populating the tablespace, you will need
  to connect to the databases identified by 
  <function>pg_tablespace_databases</function> and query their
  <structname>pg_class</> catalogs.
9491 9492
  </para>

9493 9494 9495
   <indexterm zone="functions-info">
    <primary>obj_description</primary>
   </indexterm>
9496

9497 9498 9499
   <indexterm zone="functions-info">
    <primary>col_description</primary>
   </indexterm>
9500

9501 9502 9503 9504
   <indexterm zone="functions-info">
    <primary>shobj_description</primary>
   </indexterm>

9505 9506 9507 9508
   <indexterm zone="functions-info">
    <primary>comment</primary>
    <secondary sortas="database objects">about database objects</secondary>
   </indexterm>
9509

9510 9511 9512 9513 9514 9515 9516
   <para>
    The functions shown in <xref
    linkend="functions-info-comment-table"> extract comments
    previously stored with the <command>COMMENT</command> command.  A
    null value is returned if no comment could be found matching the
    specified parameters.
   </para>
9517

9518 9519 9520 9521 9522 9523
   <table id="functions-info-comment-table">
    <title>Comment Information Functions</title>
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
     </thead>
9524

9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540
     <tbody>
      <row>
       <entry><literal><function>obj_description</function>(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get comment for a database object</entry>
      </row>
      <row>
       <entry><literal><function>obj_description</function>(<parameter>object_oid</parameter>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get comment for a database object (<emphasis>deprecated</emphasis>)</entry>
      </row>
      <row>
       <entry><literal><function>col_description</function>(<parameter>table_oid</parameter>, <parameter>column_number</parameter>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get comment for a table column</entry>
      </row>
9541 9542 9543 9544 9545
      <row>
       <entry><literal><function>shobj_description</function>(<parameter>object_oid</parameter>, <parameter>catalog_name</parameter>)</literal></entry>
       <entry><type>text</type></entry>
       <entry>get comment for a shared database object</entry>
      </row>
9546 9547 9548
     </tbody>
    </tgroup>
   </table>
9549

9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560
   <para>
    The two-parameter form of <function>obj_description</function> returns the
    comment for a database object specified by its OID and the name of the
    containing system catalog.  For example,
    <literal>obj_description(123456,'pg_class')</literal>
    would retrieve the comment for a table with OID 123456.
    The one-parameter form of <function>obj_description</function> requires only
    the object OID.  It is now deprecated since there is no guarantee that
    OIDs are unique across different system catalogs; therefore, the wrong
    comment could be returned.
   </para>
9561

9562 9563 9564 9565 9566 9567
   <para>
    <function>col_description</function> returns the comment for a table column,
    which is specified by the OID of its table and its column number.
    <function>obj_description</function> cannot be used for table columns since
    columns do not have OIDs of their own.
   </para>
9568 9569 9570 9571 9572 9573 9574 9575

   <para>
    <function>shobj_description</function> is used just like
    <function>obj_description</function> only that it is used for retrieving
    comments on shared objects.  Some system catalogs are global to all
    databases within each cluster and their descriptions are stored globally
    as well.
   </para>
9576
  </sect1>
9577

9578 9579
 <sect1 id="functions-admin">
  <title>System Administration Functions</title>
9580 9581

  <para>
9582 9583
   <xref linkend="functions-admin-set-table"> shows the functions
   available to query and alter run-time configuration parameters.
9584 9585
  </para>

9586 9587 9588 9589 9590 9591
   <table id="functions-admin-set-table">
    <title>Configuration Settings Functions</title>
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry></row>
     </thead>
9592

9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612
     <tbody>
      <row>
       <entry>
        <literal><function>current_setting</function>(<parameter>setting_name</parameter>)</literal>
       </entry>
       <entry><type>text</type></entry>
       <entry>current value of setting</entry>
      </row>
      <row>
       <entry>
        <literal><function>set_config(<parameter>setting_name</parameter>,
                             <parameter>new_value</parameter>,
                             <parameter>is_local</parameter>)</function></literal>
       </entry>
       <entry><type>text</type></entry>
       <entry>set parameter and return new value</entry>
      </row>
     </tbody>
    </tgroup>
   </table>
9613

9614 9615 9616
   <indexterm zone="functions-admin">
    <primary>SET</primary>
   </indexterm>
9617

9618 9619 9620
   <indexterm zone="functions-admin">
    <primary>SHOW</primary>
   </indexterm>
9621

9622 9623 9624 9625 9626
   <indexterm zone="functions-admin">
    <primary>configuration</primary>
    <secondary sortas="server">of the server</secondary>
    <tertiary>functions</tertiary>
   </indexterm>
9627

9628 9629 9630 9631 9632 9633 9634
   <para>
    The function <function>current_setting</function> yields the
    current value of the setting <parameter>setting_name</parameter>.
    It corresponds to the <acronym>SQL</acronym> command
    <command>SHOW</command>.  An example:
<programlisting>
SELECT current_setting('datestyle');
9635

9636 9637 9638 9639 9640 9641
 current_setting
-----------------
 ISO, MDY
(1 row)
</programlisting>
   </para>
9642

9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653
   <para>
    <function>set_config</function> sets the parameter
    <parameter>setting_name</parameter> to
    <parameter>new_value</parameter>.  If
    <parameter>is_local</parameter> is <literal>true</literal>, the
    new value will only apply to the current transaction. If you want
    the new value to apply for the current session, use
    <literal>false</literal> instead. The function corresponds to the
    SQL command <command>SET</command>. An example:
<programlisting>
SELECT set_config('log_statement_stats', 'off', false);
9654

9655 9656 9657 9658 9659 9660
 set_config
------------
 off
(1 row)
</programlisting>
   </para>
9661

9662 9663 9664
   <indexterm zone="functions-admin">
    <primary>pg_cancel_backend</primary>
   </indexterm>
9665 9666 9667
   <indexterm zone="functions-admin">
    <primary>pg_reload_conf</primary>
   </indexterm>
9668 9669 9670
   <indexterm zone="functions-admin">
    <primary>pg_rotate_logfile</primary>
   </indexterm>
9671

9672 9673 9674 9675
   <indexterm zone="functions-admin">
    <primary>signal</primary>
    <secondary sortas="backend">backend processes</secondary>
   </indexterm>
9676

9677
   <para>
9678
    The functions shown in <xref
9679 9680
    linkend="functions-admin-signal-table"> send control signals to
    other server processes.  Use of these functions is restricted
9681 9682
    to superusers.
   </para>
9683

9684
   <table id="functions-admin-signal-table">
9685
    <title>Server Signalling Functions</title>
9686 9687 9688 9689 9690
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
      </row>
     </thead>
9691

9692 9693 9694
     <tbody>
      <row>
       <entry>
9695
        <literal><function>pg_cancel_backend</function>(<parameter>pid</parameter> <type>int</>)</literal>
9696
        </entry>
9697
       <entry><type>boolean</type></entry>
9698 9699
       <entry>Cancel a backend's current query</entry>
      </row>
9700 9701 9702 9703
      <row>
       <entry>
        <literal><function>pg_reload_conf</function>()</literal>
        </entry>
9704
       <entry><type>boolean</type></entry>
9705
       <entry>Cause server processes to reload their configuration files</entry>
9706
      </row>
9707 9708 9709 9710
      <row>
       <entry>
        <literal><function>pg_rotate_logfile</function>()</literal>
        </entry>
9711
       <entry><type>boolean</type></entry>
9712
       <entry>Rotate server's log file</entry>
9713
      </row>
9714 9715 9716
     </tbody>
    </tgroup>
   </table>
9717

9718
   <para>
9719 9720
    Each of these functions returns <literal>true</literal> if
    successful and <literal>false</literal> otherwise.
9721 9722 9723
   </para>

   <para>
9724 9725 9726 9727
    <function>pg_cancel_backend</> sends a query cancel
    (<systemitem>SIGINT</>) signal to a backend process identified by
    process ID.  The process ID of an active backend can be found from
    the <structfield>procpid</structfield> column in the
9728 9729 9730
    <structname>pg_stat_activity</structname> view, or by listing the
    <command>postgres</command> processes on the server with
    <application>ps</>.
9731
   </para>
9732

9733
   <para>
9734 9735 9736
    <function>pg_reload_conf</> sends a <systemitem>SIGHUP</> signal
    to the <application>postmaster</>, causing the configuration files
    to be reloaded by all server processes.
9737
   </para>
9738

9739
   <para>
9740
    <function>pg_rotate_logfile</> signals the log-file manager to switch
9741 9742
    to a new output file immediately.  This works only when
    <varname>redirect_stderr</> is used for logging, since otherwise there
9743
    is no log-file manager subprocess.
9744 9745
   </para>

9746 9747 9748 9749 9750 9751 9752 9753 9754
   <indexterm zone="functions-admin">
    <primary>pg_start_backup</primary>
   </indexterm>
   <indexterm zone="functions-admin">
    <primary>pg_stop_backup</primary>
   </indexterm>
   <indexterm zone="functions-admin">
    <primary>backup</primary>
   </indexterm>
9755

9756 9757 9758 9759 9760
   <para>
    The functions shown in <xref
    linkend="functions-admin-backup-table"> assist in making on-line backups.
    Use of these functions is restricted to superusers.
   </para>
9761

9762 9763 9764 9765 9766 9767 9768
   <table id="functions-admin-backup-table">
    <title>Backup Control Functions</title>
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
      </row>
     </thead>
9769

9770 9771 9772
     <tbody>
      <row>
       <entry>
9773
        <literal><function>pg_start_backup</function>(<parameter>label</> <type>text</>)</literal>
9774
        </entry>
9775 9776 9777 9778 9779
       <entry><type>text</type></entry>
       <entry>Set up for performing on-line backup</entry>
      </row>
      <row>
       <entry>
9780 9781
        <literal><function>pg_stop_backup</function>()</literal>
        </entry>
9782 9783 9784 9785 9786 9787
       <entry><type>text</type></entry>
       <entry>Finish performing on-line backup</entry>
      </row>
     </tbody>
    </tgroup>
   </table>
9788

9789 9790 9791 9792 9793 9794 9795 9796 9797
   <para>
    <function>pg_start_backup</> accepts a single parameter which is an
    arbitrary user-defined label for the backup.  (Typically this would be
    the name under which the backup dump file will be stored.)  The function
    writes a backup label file into the database cluster's data directory,
    and then returns the backup's starting WAL offset as text.  (The user
    need not pay any attention to this result value, but it is provided in
    case it is of use.)
   </para>
9798

9799 9800 9801 9802 9803 9804 9805 9806 9807
   <para>
    <function>pg_stop_backup</> removes the label file created by
    <function>pg_start_backup</>, and instead creates a backup history file in
    the WAL archive area.  The history file includes the label given to
    <function>pg_start_backup</>, the starting and ending WAL offsets for
    the backup, and the starting and ending times of the backup.  The return
    value is the backup's ending WAL offset (which again may be of little
    interest).
   </para>
9808

9809 9810 9811 9812
   <para>
    For details about proper usage of these functions, see
    <xref linkend="backup-online">.
   </para>
9813 9814

   <para>
9815 9816
    The functions shown in <xref linkend="functions-admin-dbsize"> calculate
    the actual disk space usage of database objects.
9817 9818
   </para>

9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831
   <indexterm zone="functions-admin">
    <primary>pg_column_size</primary>
   </indexterm>
   <indexterm zone="functions-admin">
    <primary>pg_tablespace_size</primary>
   </indexterm>
   <indexterm zone="functions-admin">
    <primary>pg_database_size</primary>
   </indexterm>
   <indexterm zone="functions-admin">
    <primary>pg_relation_size</primary>
   </indexterm>
   <indexterm zone="functions-admin">
9832
    <primary>pg_total_relation_size</primary>
9833 9834 9835 9836 9837
   </indexterm>
   <indexterm zone="functions-admin">
    <primary>pg_size_pretty</primary>
   </indexterm>

9838 9839 9840 9841 9842 9843 9844 9845 9846
   <table id="functions-admin-dbsize">
    <title>Database Object Size Functions</title>
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
      </row>
     </thead>

     <tbody>
9847
      <row>
9848
       <entry><function>pg_column_size</function>(<type>any</type>)</entry>
9849
       <entry><type>int</type></entry>
9850 9851
       <entry>Number of bytes used to store a particular value (possibly compressed)</entry>
      </row>
9852 9853
      <row>
       <entry>
9854
        <literal><function>pg_tablespace_size</function>(<type>oid</type>)</literal>
9855
        </entry>
9856
       <entry><type>bigint</type></entry>
9857
       <entry>Disk space used by the tablespace with the specified OID</entry>
9858 9859 9860
      </row>
      <row>
       <entry>
9861
        <literal><function>pg_tablespace_size</function>(<type>name</type>)</literal>
9862
        </entry>
9863
       <entry><type>bigint</type></entry>
9864
       <entry>Disk space used by the tablespace with the specified name</entry>
9865 9866 9867
      </row>
      <row>
       <entry>
9868
        <literal><function>pg_database_size</function>(<type>oid</type>)</literal>
9869
        </entry>
9870
       <entry><type>bigint</type></entry>
9871
       <entry>Disk space used by the database with the specified OID</entry>
9872 9873 9874
      </row>
      <row>
       <entry>
9875
        <literal><function>pg_database_size</function>(<type>name</type>)</literal>
9876
        </entry>
9877
       <entry><type>bigint</type></entry>
9878
       <entry>Disk space used by the database with the specified name</entry>
9879 9880 9881
      </row>
      <row>
       <entry>
9882
        <literal><function>pg_relation_size</function>(<type>oid</type>)</literal>
9883
        </entry>
9884 9885
       <entry><type>bigint</type></entry>
       <entry>Disk space used by the table or index with the specified OID</entry>
9886 9887 9888
      </row>
      <row>
       <entry>
9889
        <literal><function>pg_relation_size</function>(<type>text</type>)</literal>
9890
        </entry>
9891
       <entry><type>bigint</type></entry>
9892 9893 9894 9895
       <entry>
        Disk space used by the table or index with the specified name.
        The table name may be qualified with a schema name
       </entry>
9896 9897 9898
      </row>
      <row>
       <entry>
9899
        <literal><function>pg_total_relation_size</function>(<type>oid</type>)</literal>
9900
        </entry>
9901
       <entry><type>bigint</type></entry>
9902 9903 9904 9905
       <entry>
        Total disk space used by the table with the specified OID,
        including indexes and toasted data
       </entry>
9906 9907 9908
      </row>
      <row>
       <entry>
9909
        <literal><function>pg_total_relation_size</function>(<type>text</type>)</literal>
9910
        </entry>
9911
       <entry><type>bigint</type></entry>
9912 9913 9914 9915 9916
       <entry>
        Total disk space used by the table with the specified name,
        including indexes and toasted data.  The table name may be
        qualified with a schema name
       </entry>
9917 9918 9919
      </row>
      <row>
       <entry>
9920
        <literal><function>pg_size_pretty</function>(<type>bigint</type>)</literal>
9921 9922
        </entry>
       <entry><type>text</type></entry>
9923
       <entry>Converts a size in bytes into a human-readable format with size units</entry>
9924 9925 9926 9927 9928 9929
      </row>
     </tbody>
    </tgroup>
   </table>

   <para>
9930 9931
    <function>pg_column_size</> shows the space used to store any individual
    data value.
9932 9933 9934
   </para>

   <para>
9935 9936 9937 9938 9939 9940 9941
    <function>pg_tablespace_size</> and <function>pg_database_size</> accept
    the OID or name of a tablespace or database, and return the total disk
    space used therein.
   </para>

   <para>
    <function>pg_relation_size</> accepts the OID or name of a table, index or
9942
    toast table, and returns the size in bytes.
9943
   </para>
9944

9945
   <para>
9946 9947 9948
    <function>pg_total_relation_size</> accepts the OID or name of a
    table or toast table, and returns the size in bytes of the data
    and all associated indexes and toast tables.
9949
   </para>
9950

9951
   <para>
9952 9953 9954
    <function>pg_size_pretty</> can be used to format the result of one of
    the other functions in a human-readable way, using kB, MB, GB or TB as
    appropriate.
9955 9956
   </para>

9957 9958 9959
   <para>
    The functions shown in <xref
    linkend="functions-admin-genfile"> provide native file access to
9960 9961 9962 9963 9964
    files on the machine hosting the server. Only files within the
    database cluster directory and the <varname>log_directory</> may be
    accessed.  Use a relative path for files within the cluster directory,
    and a path matching the <varname>log_directory</> configuration setting
    for log files.  Use of these functions is restricted to superusers.
9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977
   </para>

   <table id="functions-admin-genfile">
    <title>Generic File Access Functions</title>
    <tgroup cols="3">
     <thead>
      <row><entry>Name</entry> <entry>Return Type</entry> <entry>Description</entry>
      </row>
     </thead>

     <tbody>
      <row>
       <entry>
9978
        <literal><function>pg_ls_dir</function>(<parameter>dirname</> <type>text</>)</literal>
9979 9980 9981 9982 9983 9984
       </entry>
       <entry><type>setof text</type></entry>
       <entry>List the contents of a directory</entry>
      </row>
      <row>
       <entry>
9985
        <literal><function>pg_read_file</function>(<parameter>filename</> <type>text</>, <parameter>offset</> <type>bigint</>, <parameter>length</> <type>bigint</>)</literal>
9986 9987
       </entry>
       <entry><type>text</type></entry>
9988
       <entry>Return the contents of a text file</entry>
9989 9990 9991
      </row>
      <row>
       <entry>
9992
        <literal><function>pg_stat_file</function>(<parameter>filename</> <type>text</>)</literal>
9993 9994
       </entry>
       <entry><type>record</type></entry>
9995
       <entry>Return information about a file</entry>
9996 9997 9998 9999 10000
      </row>
     </tbody>
    </tgroup>
   </table>

10001 10002 10003 10004
   <indexterm zone="functions-admin">
    <primary>pg_ls_dir</primary>
   </indexterm>
   <para>
10005
    <function>pg_ls_dir</> returns all the names in the specified
10006 10007 10008 10009
    directory, except the special entries <quote><literal>.</></> and
    <quote><literal>..</></>.
   </para>

10010 10011 10012 10013
   <indexterm zone="functions-admin">
    <primary>pg_read_file</primary>
   </indexterm>
   <para>
10014
    <function>pg_read_file</> returns part of a text file, starting
10015 10016 10017
    at the given <parameter>offset</>, returning at most <parameter>length</>
    bytes (less if the end of file is reached first).  If <parameter>offset</>
    is negative, it is relative to the end of the file.
10018 10019 10020 10021 10022 10023
   </para>

   <indexterm zone="functions-admin">
    <primary>pg_stat_file</primary>
   </indexterm>
   <para>
10024
    <function>pg_stat_file</> returns a record containing the file
10025 10026 10027
    size, last accessed time stamp, last modified time stamp, 
    last file status change time stamp (Unix platforms only), 
    file creation timestamp (Windows only), and a <type>boolean</type> indicating 
10028
    if it is a directory.  Typical usages include:
10029
<programlisting>
10030
SELECT * FROM pg_stat_file('filename');
10031
SELECT (pg_stat_file('filename')).modification;
10032
</programlisting>
10033 10034
   </para>

10035
  </sect1>
10036
</chapter>
10037

10038 10039
<!-- Keep this comment at the end of the file
Local variables:
T
Thomas G. Lockhart 已提交
10040
mode:sgml
10041
sgml-omittag:nil
10042 10043 10044 10045 10046 10047 10048 10049
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
T
Thomas G. Lockhart 已提交
10050
sgml-local-catalogs:("/usr/lib/sgml/catalog")
10051 10052 10053
sgml-local-ecat-files:nil
End:
-->