Debian Codegraph @

doc/src/sgml/func.sgml

raw
1 <!-- doc/src/sgml/func.sgml -->
2
3 <chapter id="functions">
4 <title>Functions and Operators</title>
5
6 <indexterm zone="functions">
7 <primary>function</primary>
8 </indexterm>
9
10 <indexterm zone="functions">
11 <primary>operator</primary>
12 </indexterm>
13
14 <para>
15 <productname>PostgreSQL</productname> provides a large number of
16 functions and operators for the built-in data types. This chapter
17 describes most of them, although additional special-purpose functions
18 appear in relevant sections of the manual. Users can also
19 define their own functions and operators, as described in
20 <xref linkend="server-programming"/>. The
21 <application>psql</application> commands <command>\df</command> and
22 <command>\do</command> can be used to list all
23 available functions and operators, respectively.
24 </para>
25
26 <para>
27 The notation used throughout this chapter to describe the argument and
28 result data types of a function or operator is like this:
29 <synopsis>
30 <function>repeat</function> ( <type>text</type>, <type>integer</type> ) <returnvalue>text</returnvalue>
31 </synopsis>
32 which says that the function <function>repeat</function> takes one text and
33 one integer argument and returns a result of type text. The right arrow
34 is also used to indicate the result of an example, thus:
35 <programlisting>
36 repeat('Pg', 4) <returnvalue>PgPgPgPg</returnvalue>
37 </programlisting>
38 </para>
39
40 <para>
41 If you are concerned about portability then note that most of
42 the functions and operators described in this chapter, with the
43 exception of the most trivial arithmetic and comparison operators
44 and some explicitly marked functions, are not specified by the
45 <acronym>SQL</acronym> standard. Some of this extended functionality
46 is present in other <acronym>SQL</acronym> database management
47 systems, and in many cases this functionality is compatible and
48 consistent between the various implementations.
49 </para>
50
51
52 <sect1 id="functions-logical">
53 <title>Logical Operators</title>
54
55 <indexterm zone="functions-logical">
56 <primary>operator</primary>
57 <secondary>logical</secondary>
58 </indexterm>
59
60 <indexterm>
61 <primary>Boolean</primary>
62 <secondary>operators</secondary>
63 <see>operators, logical</see>
64 </indexterm>
65
66 <para>
67 The usual logical operators are available:
68
69 <indexterm>
70 <primary>AND (operator)</primary>
71 </indexterm>
72
73 <indexterm>
74 <primary>OR (operator)</primary>
75 </indexterm>
76
77 <indexterm>
78 <primary>NOT (operator)</primary>
79 </indexterm>
80
81 <indexterm>
82 <primary>conjunction</primary>
83 </indexterm>
84
85 <indexterm>
86 <primary>disjunction</primary>
87 </indexterm>
88
89 <indexterm>
90 <primary>negation</primary>
91 </indexterm>
92
93 <synopsis>
94 <type>boolean</type> <literal>AND</literal> <type>boolean</type> <returnvalue>boolean</returnvalue>
95 <type>boolean</type> <literal>OR</literal> <type>boolean</type> <returnvalue>boolean</returnvalue>
96 <literal>NOT</literal> <type>boolean</type> <returnvalue>boolean</returnvalue>
97 </synopsis>
98
99 <acronym>SQL</acronym> uses a three-valued logic system with true,
100 false, and <literal>null</literal>, which represents <quote>unknown</quote>.
101 Observe the following truth tables:
102
103 <informaltable>
104 <tgroup cols="4">
105 <thead>
106 <row>
107 <entry><replaceable>a</replaceable></entry>
108 <entry><replaceable>b</replaceable></entry>
109 <entry><replaceable>a</replaceable> AND <replaceable>b</replaceable></entry>
110 <entry><replaceable>a</replaceable> OR <replaceable>b</replaceable></entry>
111 </row>
112 </thead>
113
114 <tbody>
115 <row>
116 <entry>TRUE</entry>
117 <entry>TRUE</entry>
118 <entry>TRUE</entry>
119 <entry>TRUE</entry>
120 </row>
121
122 <row>
123 <entry>TRUE</entry>
124 <entry>FALSE</entry>
125 <entry>FALSE</entry>
126 <entry>TRUE</entry>
127 </row>
128
129 <row>
130 <entry>TRUE</entry>
131 <entry>NULL</entry>
132 <entry>NULL</entry>
133 <entry>TRUE</entry>
134 </row>
135
136 <row>
137 <entry>FALSE</entry>
138 <entry>FALSE</entry>
139 <entry>FALSE</entry>
140 <entry>FALSE</entry>
141 </row>
142
143 <row>
144 <entry>FALSE</entry>
145 <entry>NULL</entry>
146 <entry>FALSE</entry>
147 <entry>NULL</entry>
148 </row>
149
150 <row>
151 <entry>NULL</entry>
152 <entry>NULL</entry>
153 <entry>NULL</entry>
154 <entry>NULL</entry>
155 </row>
156 </tbody>
157 </tgroup>
158 </informaltable>
159
160 <informaltable>
161 <tgroup cols="2">
162 <thead>
163 <row>
164 <entry><replaceable>a</replaceable></entry>
165 <entry>NOT <replaceable>a</replaceable></entry>
166 </row>
167 </thead>
168
169 <tbody>
170 <row>
171 <entry>TRUE</entry>
172 <entry>FALSE</entry>
173 </row>
174
175 <row>
176 <entry>FALSE</entry>
177 <entry>TRUE</entry>
178 </row>
179
180 <row>
181 <entry>NULL</entry>
182 <entry>NULL</entry>
183 </row>
184 </tbody>
185 </tgroup>
186 </informaltable>
187 </para>
188
189 <para>
190 The operators <literal>AND</literal> and <literal>OR</literal> are
191 commutative, that is, you can switch the left and right operands
192 without affecting the result. (However, it is not guaranteed that
193 the left operand is evaluated before the right operand. See <xref
194 linkend="syntax-express-eval"/> for more information about the
195 order of evaluation of subexpressions.)
196 </para>
197 </sect1>
198
199 <sect1 id="functions-comparison">
200 <title>Comparison Functions and Operators</title>
201
202 <indexterm zone="functions-comparison">
203 <primary>comparison</primary>
204 <secondary>operators</secondary>
205 </indexterm>
206
207 <para>
208 The usual comparison operators are available, as shown in <xref
209 linkend="functions-comparison-op-table"/>.
210 </para>
211
212 <table id="functions-comparison-op-table">
213 <title>Comparison Operators</title>
214 <tgroup cols="2">
215 <thead>
216 <row>
217 <entry>Operator</entry>
218 <entry>Description</entry>
219 </row>
220 </thead>
221
222 <tbody>
223 <row>
224 <entry>
225 <replaceable>datatype</replaceable> <literal>&lt;</literal> <replaceable>datatype</replaceable>
226 <returnvalue>boolean</returnvalue>
227 </entry>
228 <entry>Less than</entry>
229 </row>
230
231 <row>
232 <entry>
233 <replaceable>datatype</replaceable> <literal>&gt;</literal> <replaceable>datatype</replaceable>
234 <returnvalue>boolean</returnvalue>
235 </entry>
236 <entry>Greater than</entry>
237 </row>
238
239 <row>
240 <entry>
241 <replaceable>datatype</replaceable> <literal>&lt;=</literal> <replaceable>datatype</replaceable>
242 <returnvalue>boolean</returnvalue>
243 </entry>
244 <entry>Less than or equal to</entry>
245 </row>
246
247 <row>
248 <entry>
249 <replaceable>datatype</replaceable> <literal>&gt;=</literal> <replaceable>datatype</replaceable>
250 <returnvalue>boolean</returnvalue>
251 </entry>
252 <entry>Greater than or equal to</entry>
253 </row>
254
255 <row>
256 <entry>
257 <replaceable>datatype</replaceable> <literal>=</literal> <replaceable>datatype</replaceable>
258 <returnvalue>boolean</returnvalue>
259 </entry>
260 <entry>Equal</entry>
261 </row>
262
263 <row>
264 <entry>
265 <replaceable>datatype</replaceable> <literal>&lt;&gt;</literal> <replaceable>datatype</replaceable>
266 <returnvalue>boolean</returnvalue>
267 </entry>
268 <entry>Not equal</entry>
269 </row>
270
271 <row>
272 <entry>
273 <replaceable>datatype</replaceable> <literal>!=</literal> <replaceable>datatype</replaceable>
274 <returnvalue>boolean</returnvalue>
275 </entry>
276 <entry>Not equal</entry>
277 </row>
278 </tbody>
279 </tgroup>
280 </table>
281
282 <note>
283 <para>
284 <literal>&lt;&gt;</literal> is the standard SQL notation for <quote>not
285 equal</quote>. <literal>!=</literal> is an alias, which is converted
286 to <literal>&lt;&gt;</literal> at a very early stage of parsing.
287 Hence, it is not possible to implement <literal>!=</literal>
288 and <literal>&lt;&gt;</literal> operators that do different things.
289 </para>
290 </note>
291
292 <para>
293 These comparison operators are available for all built-in data types
294 that have a natural ordering, including numeric, string, and date/time
295 types. In addition, arrays, composite types, and ranges can be compared
296 if their component data types are comparable.
297 </para>
298
299 <para>
300 It is usually possible to compare values of related data
301 types as well; for example <type>integer</type> <literal>&gt;</literal>
302 <type>bigint</type> will work. Some cases of this sort are implemented
303 directly by <quote>cross-type</quote> comparison operators, but if no
304 such operator is available, the parser will coerce the less-general type
305 to the more-general type and apply the latter's comparison operator.
306 </para>
307
308 <para>
309 As shown above, all comparison operators are binary operators that
310 return values of type <type>boolean</type>. Thus, expressions like
311 <literal>1 &lt; 2 &lt; 3</literal> are not valid (because there is
312 no <literal>&lt;</literal> operator to compare a Boolean value with
313 <literal>3</literal>). Use the <literal>BETWEEN</literal> predicates
314 shown below to perform range tests.
315 </para>
316
317 <para>
318 There are also some comparison predicates, as shown in <xref
319 linkend="functions-comparison-pred-table"/>. These behave much like
320 operators, but have special syntax mandated by the SQL standard.
321 </para>
322
323 <table id="functions-comparison-pred-table">
324 <title>Comparison Predicates</title>
325 <tgroup cols="1">
326 <thead>
327 <row>
328 <entry role="func_table_entry"><para role="func_signature">
329 Predicate
330 </para>
331 <para>
332 Description
333 </para>
334 <para>
335 Example(s)
336 </para></entry>
337 </row>
338 </thead>
339
340 <tbody>
341 <row>
342 <entry role="func_table_entry"><para role="func_signature">
343 <replaceable>datatype</replaceable> <literal>BETWEEN</literal> <replaceable>datatype</replaceable> <literal>AND</literal> <replaceable>datatype</replaceable>
344 <returnvalue>boolean</returnvalue>
345 </para>
346 <para>
347 Between (inclusive of the range endpoints).
348 </para>
349 <para>
350 <literal>2 BETWEEN 1 AND 3</literal>
351 <returnvalue>t</returnvalue>
352 </para>
353 <para>
354 <literal>2 BETWEEN 3 AND 1</literal>
355 <returnvalue>f</returnvalue>
356 </para></entry>
357 </row>
358
359 <row>
360 <entry role="func_table_entry"><para role="func_signature">
361 <replaceable>datatype</replaceable> <literal>NOT BETWEEN</literal> <replaceable>datatype</replaceable> <literal>AND</literal> <replaceable>datatype</replaceable>
362 <returnvalue>boolean</returnvalue>
363 </para>
364 <para>
365 Not between (the negation of <literal>BETWEEN</literal>).
366 </para>
367 <para>
368 <literal>2 NOT BETWEEN 1 AND 3</literal>
369 <returnvalue>f</returnvalue>
370 </para></entry>
371 </row>
372
373 <row>
374 <entry role="func_table_entry"><para role="func_signature">
375 <replaceable>datatype</replaceable> <literal>BETWEEN SYMMETRIC</literal> <replaceable>datatype</replaceable> <literal>AND</literal> <replaceable>datatype</replaceable>
376 <returnvalue>boolean</returnvalue>
377 </para>
378 <para>
379 Between, after sorting the two endpoint values.
380 </para>
381 <para>
382 <literal>2 BETWEEN SYMMETRIC 3 AND 1</literal>
383 <returnvalue>t</returnvalue>
384 </para></entry>
385 </row>
386
387 <row>
388 <entry role="func_table_entry"><para role="func_signature">
389 <replaceable>datatype</replaceable> <literal>NOT BETWEEN SYMMETRIC</literal> <replaceable>datatype</replaceable> <literal>AND</literal> <replaceable>datatype</replaceable>
390 <returnvalue>boolean</returnvalue>
391 </para>
392 <para>
393 Not between, after sorting the two endpoint values.
394 </para>
395 <para>
396 <literal>2 NOT BETWEEN SYMMETRIC 3 AND 1</literal>
397 <returnvalue>f</returnvalue>
398 </para></entry>
399 </row>
400
401 <row>
402 <entry role="func_table_entry"><para role="func_signature">
403 <replaceable>datatype</replaceable> <literal>IS DISTINCT FROM</literal> <replaceable>datatype</replaceable>
404 <returnvalue>boolean</returnvalue>
405 </para>
406 <para>
407 Not equal, treating null as a comparable value.
408 </para>
409 <para>
410 <literal>1 IS DISTINCT FROM NULL</literal>
411 <returnvalue>t</returnvalue> (rather than <literal>NULL</literal>)
412 </para>
413 <para>
414 <literal>NULL IS DISTINCT FROM NULL</literal>
415 <returnvalue>f</returnvalue> (rather than <literal>NULL</literal>)
416 </para></entry>
417 </row>
418
419 <row>
420 <entry role="func_table_entry"><para role="func_signature">
421 <replaceable>datatype</replaceable> <literal>IS NOT DISTINCT FROM</literal> <replaceable>datatype</replaceable>
422 <returnvalue>boolean</returnvalue>
423 </para>
424 <para>
425 Equal, treating null as a comparable value.
426 </para>
427 <para>
428 <literal>1 IS NOT DISTINCT FROM NULL</literal>
429 <returnvalue>f</returnvalue> (rather than <literal>NULL</literal>)
430 </para>
431 <para>
432 <literal>NULL IS NOT DISTINCT FROM NULL</literal>
433 <returnvalue>t</returnvalue> (rather than <literal>NULL</literal>)
434 </para></entry>
435 </row>
436
437 <row>
438 <entry role="func_table_entry"><para role="func_signature">
439 <replaceable>datatype</replaceable> <literal>IS NULL</literal>
440 <returnvalue>boolean</returnvalue>
441 </para>
442 <para>
443 Test whether value is null.
444 </para>
445 <para>
446 <literal>1.5 IS NULL</literal>
447 <returnvalue>f</returnvalue>
448 </para></entry>
449 </row>
450
451 <row>
452 <entry role="func_table_entry"><para role="func_signature">
453 <replaceable>datatype</replaceable> <literal>IS NOT NULL</literal>
454 <returnvalue>boolean</returnvalue>
455 </para>
456 <para>
457 Test whether value is not null.
458 </para>
459 <para>
460 <literal>'null' IS NOT NULL</literal>
461 <returnvalue>t</returnvalue>
462 </para></entry>
463 </row>
464
465 <row>
466 <entry role="func_table_entry"><para role="func_signature">
467 <replaceable>datatype</replaceable> <literal>ISNULL</literal>
468 <returnvalue>boolean</returnvalue>
469 </para>
470 <para>
471 Test whether value is null (nonstandard syntax).
472 </para></entry>
473 </row>
474
475 <row>
476 <entry role="func_table_entry"><para role="func_signature">
477 <replaceable>datatype</replaceable> <literal>NOTNULL</literal>
478 <returnvalue>boolean</returnvalue>
479 </para>
480 <para>
481 Test whether value is not null (nonstandard syntax).
482 </para></entry>
483 </row>
484
485 <row>
486 <entry role="func_table_entry"><para role="func_signature">
487 <type>boolean</type> <literal>IS TRUE</literal>
488 <returnvalue>boolean</returnvalue>
489 </para>
490 <para>
491 Test whether boolean expression yields true.
492 </para>
493 <para>
494 <literal>true IS TRUE</literal>
495 <returnvalue>t</returnvalue>
496 </para>
497 <para>
498 <literal>NULL::boolean IS TRUE</literal>
499 <returnvalue>f</returnvalue> (rather than <literal>NULL</literal>)
500 </para></entry>
501 </row>
502
503 <row>
504 <entry role="func_table_entry"><para role="func_signature">
505 <type>boolean</type> <literal>IS NOT TRUE</literal>
506 <returnvalue>boolean</returnvalue>
507 </para>
508 <para>
509 Test whether boolean expression yields false or unknown.
510 </para>
511 <para>
512 <literal>true IS NOT TRUE</literal>
513 <returnvalue>f</returnvalue>
514 </para>
515 <para>
516 <literal>NULL::boolean IS NOT TRUE</literal>
517 <returnvalue>t</returnvalue> (rather than <literal>NULL</literal>)
518 </para></entry>
519 </row>
520
521 <row>
522 <entry role="func_table_entry"><para role="func_signature">
523 <type>boolean</type> <literal>IS FALSE</literal>
524 <returnvalue>boolean</returnvalue>
525 </para>
526 <para>
527 Test whether boolean expression yields false.
528 </para>
529 <para>
530 <literal>true IS FALSE</literal>
531 <returnvalue>f</returnvalue>
532 </para>
533 <para>
534 <literal>NULL::boolean IS FALSE</literal>
535 <returnvalue>f</returnvalue> (rather than <literal>NULL</literal>)
536 </para></entry>
537 </row>
538
539 <row>
540 <entry role="func_table_entry"><para role="func_signature">
541 <type>boolean</type> <literal>IS NOT FALSE</literal>
542 <returnvalue>boolean</returnvalue>
543 </para>
544 <para>
545 Test whether boolean expression yields true or unknown.
546 </para>
547 <para>
548 <literal>true IS NOT FALSE</literal>
549 <returnvalue>t</returnvalue>
550 </para>
551 <para>
552 <literal>NULL::boolean IS NOT FALSE</literal>
553 <returnvalue>t</returnvalue> (rather than <literal>NULL</literal>)
554 </para></entry>
555 </row>
556
557 <row>
558 <entry role="func_table_entry"><para role="func_signature">
559 <type>boolean</type> <literal>IS UNKNOWN</literal>
560 <returnvalue>boolean</returnvalue>
561 </para>
562 <para>
563 Test whether boolean expression yields unknown.
564 </para>
565 <para>
566 <literal>true IS UNKNOWN</literal>
567 <returnvalue>f</returnvalue>
568 </para>
569 <para>
570 <literal>NULL::boolean IS UNKNOWN</literal>
571 <returnvalue>t</returnvalue> (rather than <literal>NULL</literal>)
572 </para></entry>
573 </row>
574
575 <row>
576 <entry role="func_table_entry"><para role="func_signature">
577 <type>boolean</type> <literal>IS NOT UNKNOWN</literal>
578 <returnvalue>boolean</returnvalue>
579 </para>
580 <para>
581 Test whether boolean expression yields true or false.
582 </para>
583 <para>
584 <literal>true IS NOT UNKNOWN</literal>
585 <returnvalue>t</returnvalue>
586 </para>
587 <para>
588 <literal>NULL::boolean IS NOT UNKNOWN</literal>
589 <returnvalue>f</returnvalue> (rather than <literal>NULL</literal>)
590 </para></entry>
591 </row>
592 </tbody>
593 </tgroup>
594 </table>
595
596 <para>
597 <indexterm>
598 <primary>BETWEEN</primary>
599 </indexterm>
600 <indexterm>
601 <primary>BETWEEN SYMMETRIC</primary>
602 </indexterm>
603 The <token>BETWEEN</token> predicate simplifies range tests:
604 <synopsis>
605 <replaceable>a</replaceable> BETWEEN <replaceable>x</replaceable> AND <replaceable>y</replaceable>
606 </synopsis>
607 is equivalent to
608 <synopsis>
609 <replaceable>a</replaceable> &gt;= <replaceable>x</replaceable> AND <replaceable>a</replaceable> &lt;= <replaceable>y</replaceable>
610 </synopsis>
611 Notice that <token>BETWEEN</token> treats the endpoint values as included
612 in the range.
613 <literal>BETWEEN SYMMETRIC</literal> is like <literal>BETWEEN</literal>
614 except there is no requirement that the argument to the left of
615 <literal>AND</literal> be less than or equal to the argument on the right.
616 If it is not, those two arguments are automatically swapped, so that
617 a nonempty range is always implied.
618 </para>
619
620 <para>
621 The various variants of <literal>BETWEEN</literal> are implemented in
622 terms of the ordinary comparison operators, and therefore will work for
623 any data type(s) that can be compared.
624 </para>
625
626 <note>
627 <para>
628 The use of <literal>AND</literal> in the <literal>BETWEEN</literal>
629 syntax creates an ambiguity with the use of <literal>AND</literal> as a
630 logical operator. To resolve this, only a limited set of expression
631 types are allowed as the second argument of a <literal>BETWEEN</literal>
632 clause. If you need to write a more complex sub-expression
633 in <literal>BETWEEN</literal>, write parentheses around the
634 sub-expression.
635 </para>
636 </note>
637
638 <para>
639 <indexterm>
640 <primary>IS DISTINCT FROM</primary>
641 </indexterm>
642 <indexterm>
643 <primary>IS NOT DISTINCT FROM</primary>
644 </indexterm>
645 Ordinary comparison operators yield null (signifying <quote>unknown</quote>),
646 not true or false, when either input is null. For example,
647 <literal>7 = NULL</literal> yields null, as does <literal>7 &lt;&gt; NULL</literal>. When
648 this behavior is not suitable, use the
649 <literal>IS <optional> NOT </optional> DISTINCT FROM</literal> predicates:
650 <synopsis>
651 <replaceable>a</replaceable> IS DISTINCT FROM <replaceable>b</replaceable>
652 <replaceable>a</replaceable> IS NOT DISTINCT FROM <replaceable>b</replaceable>
653 </synopsis>
654 For non-null inputs, <literal>IS DISTINCT FROM</literal> is
655 the same as the <literal>&lt;&gt;</literal> operator. However, if both
656 inputs are null it returns false, and if only one input is
657 null it returns true. Similarly, <literal>IS NOT DISTINCT
658 FROM</literal> is identical to <literal>=</literal> for non-null
659 inputs, but it returns true when both inputs are null, and false when only
660 one input is null. Thus, these predicates effectively act as though null
661 were a normal data value, rather than <quote>unknown</quote>.
662 </para>
663
664 <para>
665 <indexterm>
666 <primary>IS NULL</primary>
667 </indexterm>
668 <indexterm>
669 <primary>IS NOT NULL</primary>
670 </indexterm>
671 <indexterm>
672 <primary>ISNULL</primary>
673 </indexterm>
674 <indexterm>
675 <primary>NOTNULL</primary>
676 </indexterm>
677 To check whether a value is or is not null, use the predicates:
678 <synopsis>
679 <replaceable>expression</replaceable> IS NULL
680 <replaceable>expression</replaceable> IS NOT NULL
681 </synopsis>
682 or the equivalent, but nonstandard, predicates:
683 <synopsis>
684 <replaceable>expression</replaceable> ISNULL
685 <replaceable>expression</replaceable> NOTNULL
686 </synopsis>
687 <indexterm><primary>null value</primary><secondary>comparing</secondary></indexterm>
688 </para>
689
690 <para>
691 Do <emphasis>not</emphasis> write
692 <literal><replaceable>expression</replaceable> = NULL</literal>
693 because <literal>NULL</literal> is not <quote>equal to</quote>
694 <literal>NULL</literal>. (The null value represents an unknown value,
695 and it is not known whether two unknown values are equal.)
696 </para>
697
698 <tip>
699 <para>
700 Some applications might expect that
701 <literal><replaceable>expression</replaceable> = NULL</literal>
702 returns true if <replaceable>expression</replaceable> evaluates to
703 the null value. It is highly recommended that these applications
704 be modified to comply with the SQL standard. However, if that
705 cannot be done the <xref linkend="guc-transform-null-equals"/>
706 configuration variable is available. If it is enabled,
707 <productname>PostgreSQL</productname> will convert <literal>x =
708 NULL</literal> clauses to <literal>x IS NULL</literal>.
709 </para>
710 </tip>
711
712 <para>
713 If the <replaceable>expression</replaceable> is row-valued, then
714 <literal>IS NULL</literal> is true when the row expression itself is null
715 or when all the row's fields are null, while
716 <literal>IS NOT NULL</literal> is true when the row expression itself is non-null
717 and all the row's fields are non-null. Because of this behavior,
718 <literal>IS NULL</literal> and <literal>IS NOT NULL</literal> do not always return
719 inverse results for row-valued expressions; in particular, a row-valued
720 expression that contains both null and non-null fields will return false
721 for both tests. For example:
722
723 <programlisting>
724 SELECT ROW(1,2.5,'this is a test') = ROW(1, 3, 'not the same');
725
726 SELECT ROW(table.*) IS NULL FROM table; -- detect all-null rows
727
728 SELECT ROW(table.*) IS NOT NULL FROM table; -- detect all-non-null rows
729
730 SELECT NOT(ROW(table.*) IS NOT NULL) FROM TABLE; -- detect at least one null in rows
731 </programlisting>
732
733 In some cases, it may be preferable to
734 write <replaceable>row</replaceable> <literal>IS DISTINCT FROM NULL</literal>
735 or <replaceable>row</replaceable> <literal>IS NOT DISTINCT FROM NULL</literal>,
736 which will simply check whether the overall row value is null without any
737 additional tests on the row fields.
738 </para>
739
740 <para>
741 <indexterm>
742 <primary>IS TRUE</primary>
743 </indexterm>
744 <indexterm>
745 <primary>IS NOT TRUE</primary>
746 </indexterm>
747 <indexterm>
748 <primary>IS FALSE</primary>
749 </indexterm>
750 <indexterm>
751 <primary>IS NOT FALSE</primary>
752 </indexterm>
753 <indexterm>
754 <primary>IS UNKNOWN</primary>
755 </indexterm>
756 <indexterm>
757 <primary>IS NOT UNKNOWN</primary>
758 </indexterm>
759 Boolean values can also be tested using the predicates
760 <synopsis>
761 <replaceable>boolean_expression</replaceable> IS TRUE
762 <replaceable>boolean_expression</replaceable> IS NOT TRUE
763 <replaceable>boolean_expression</replaceable> IS FALSE
764 <replaceable>boolean_expression</replaceable> IS NOT FALSE
765 <replaceable>boolean_expression</replaceable> IS UNKNOWN
766 <replaceable>boolean_expression</replaceable> IS NOT UNKNOWN
767 </synopsis>
768 These will always return true or false, never a null value, even when the
769 operand is null.
770 A null input is treated as the logical value <quote>unknown</quote>.
771 Notice that <literal>IS UNKNOWN</literal> and <literal>IS NOT UNKNOWN</literal> are
772 effectively the same as <literal>IS NULL</literal> and
773 <literal>IS NOT NULL</literal>, respectively, except that the input
774 expression must be of Boolean type.
775 </para>
776
777 <para>
778 Some comparison-related functions are also available, as shown in <xref
779 linkend="functions-comparison-func-table"/>.
780 </para>
781
782 <table id="functions-comparison-func-table">
783 <title>Comparison Functions</title>
784 <tgroup cols="1">
785 <thead>
786 <row>
787 <entry role="func_table_entry"><para role="func_signature">
788 Function
789 </para>
790 <para>
791 Description
792 </para>
793 <para>
794 Example(s)
795 </para></entry>
796 </row>
797 </thead>
798
799 <tbody>
800 <row>
801 <entry role="func_table_entry"><para role="func_signature">
802 <indexterm>
803 <primary>num_nonnulls</primary>
804 </indexterm>
805 <function>num_nonnulls</function> ( <literal>VARIADIC</literal> <type>"any"</type> )
806 <returnvalue>integer</returnvalue>
807 </para>
808 <para>
809 Returns the number of non-null arguments.
810 </para>
811 <para>
812 <literal>num_nonnulls(1, NULL, 2)</literal>
813 <returnvalue>2</returnvalue>
814 </para></entry>
815 </row>
816 <row>
817 <entry role="func_table_entry"><para role="func_signature">
818 <indexterm>
819 <primary>num_nulls</primary>
820 </indexterm>
821 <function>num_nulls</function> ( <literal>VARIADIC</literal> <type>"any"</type> )
822 <returnvalue>integer</returnvalue>
823 </para>
824 <para>
825 Returns the number of null arguments.
826 </para>
827 <para>
828 <literal>num_nulls(1, NULL, 2)</literal>
829 <returnvalue>1</returnvalue>
830 </para></entry>
831 </row>
832 </tbody>
833 </tgroup>
834 </table>
835
836 </sect1>
837
838 <sect1 id="functions-math">
839 <title>Mathematical Functions and Operators</title>
840
841 <para>
842 Mathematical operators are provided for many
843 <productname>PostgreSQL</productname> types. For types without
844 standard mathematical conventions
845 (e.g., date/time types) we
846 describe the actual behavior in subsequent sections.
847 </para>
848
849 <para>
850 <xref linkend="functions-math-op-table"/> shows the mathematical
851 operators that are available for the standard numeric types.
852 Unless otherwise noted, operators shown as
853 accepting <replaceable>numeric_type</replaceable> are available for all
854 the types <type>smallint</type>, <type>integer</type>,
855 <type>bigint</type>, <type>numeric</type>, <type>real</type>,
856 and <type>double precision</type>.
857 Operators shown as accepting <replaceable>integral_type</replaceable>
858 are available for the types <type>smallint</type>, <type>integer</type>,
859 and <type>bigint</type>.
860 Except where noted, each form of an operator returns the same data type
861 as its argument(s). Calls involving multiple argument data types, such
862 as <type>integer</type> <literal>+</literal> <type>numeric</type>,
863 are resolved by using the type appearing later in these lists.
864 </para>
865
866 <table id="functions-math-op-table">
867 <title>Mathematical Operators</title>
868
869 <tgroup cols="1">
870 <thead>
871 <row>
872 <entry role="func_table_entry"><para role="func_signature">
873 Operator
874 </para>
875 <para>
876 Description
877 </para>
878 <para>
879 Example(s)
880 </para></entry>
881 </row>
882 </thead>
883
884 <tbody>
885 <row>
886 <entry role="func_table_entry"><para role="func_signature">
887 <replaceable>numeric_type</replaceable> <literal>+</literal> <replaceable>numeric_type</replaceable>
888 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
889 </para>
890 <para>
891 Addition
892 </para>
893 <para>
894 <literal>2 + 3</literal>
895 <returnvalue>5</returnvalue>
896 </para></entry>
897 </row>
898
899 <row>
900 <entry role="func_table_entry"><para role="func_signature">
901 <literal>+</literal> <replaceable>numeric_type</replaceable>
902 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
903 </para>
904 <para>
905 Unary plus (no operation)
906 </para>
907 <para>
908 <literal>+ 3.5</literal>
909 <returnvalue>3.5</returnvalue>
910 </para></entry>
911 </row>
912
913 <row>
914 <entry role="func_table_entry"><para role="func_signature">
915 <replaceable>numeric_type</replaceable> <literal>-</literal> <replaceable>numeric_type</replaceable>
916 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
917 </para>
918 <para>
919 Subtraction
920 </para>
921 <para>
922 <literal>2 - 3</literal>
923 <returnvalue>-1</returnvalue>
924 </para></entry>
925 </row>
926
927 <row>
928 <entry role="func_table_entry"><para role="func_signature">
929 <literal>-</literal> <replaceable>numeric_type</replaceable>
930 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
931 </para>
932 <para>
933 Negation
934 </para>
935 <para>
936 <literal>- (-4)</literal>
937 <returnvalue>4</returnvalue>
938 </para></entry>
939 </row>
940
941 <row>
942 <entry role="func_table_entry"><para role="func_signature">
943 <replaceable>numeric_type</replaceable> <literal>*</literal> <replaceable>numeric_type</replaceable>
944 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
945 </para>
946 <para>
947 Multiplication
948 </para>
949 <para>
950 <literal>2 * 3</literal>
951 <returnvalue>6</returnvalue>
952 </para></entry>
953 </row>
954
955 <row>
956 <entry role="func_table_entry"><para role="func_signature">
957 <replaceable>numeric_type</replaceable> <literal>/</literal> <replaceable>numeric_type</replaceable>
958 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
959 </para>
960 <para>
961 Division (for integral types, division truncates the result towards
962 zero)
963 </para>
964 <para>
965 <literal>5.0 / 2</literal>
966 <returnvalue>2.5000000000000000</returnvalue>
967 </para>
968 <para>
969 <literal>5 / 2</literal>
970 <returnvalue>2</returnvalue>
971 </para>
972 <para>
973 <literal>(-5) / 2</literal>
974 <returnvalue>-2</returnvalue>
975 </para></entry>
976 </row>
977
978 <row>
979 <entry role="func_table_entry"><para role="func_signature">
980 <replaceable>numeric_type</replaceable> <literal>%</literal> <replaceable>numeric_type</replaceable>
981 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
982 </para>
983 <para>
984 Modulo (remainder); available for <type>smallint</type>,
985 <type>integer</type>, <type>bigint</type>, and <type>numeric</type>
986 </para>
987 <para>
988 <literal>5 % 4</literal>
989 <returnvalue>1</returnvalue>
990 </para></entry>
991 </row>
992
993 <row>
994 <entry role="func_table_entry"><para role="func_signature">
995 <type>numeric</type> <literal>^</literal> <type>numeric</type>
996 <returnvalue>numeric</returnvalue>
997 </para>
998 <para role="func_signature">
999 <type>double precision</type> <literal>^</literal> <type>double precision</type>
1000 <returnvalue>double precision</returnvalue>
1001 </para>
1002 <para>
1003 Exponentiation
1004 </para>
1005 <para>
1006 <literal>2 ^ 3</literal>
1007 <returnvalue>8</returnvalue>
1008 </para>
1009 <para>
1010 Unlike typical mathematical practice, multiple uses of
1011 <literal>^</literal> will associate left to right by default:
1012 </para>
1013 <para>
1014 <literal>2 ^ 3 ^ 3</literal>
1015 <returnvalue>512</returnvalue>
1016 </para>
1017 <para>
1018 <literal>2 ^ (3 ^ 3)</literal>
1019 <returnvalue>134217728</returnvalue>
1020 </para></entry>
1021 </row>
1022
1023 <row>
1024 <entry role="func_table_entry"><para role="func_signature">
1025 <literal>|/</literal> <type>double precision</type>
1026 <returnvalue>double precision</returnvalue>
1027 </para>
1028 <para>
1029 Square root
1030 </para>
1031 <para>
1032 <literal>|/ 25.0</literal>
1033 <returnvalue>5</returnvalue>
1034 </para></entry>
1035 </row>
1036
1037 <row>
1038 <entry role="func_table_entry"><para role="func_signature">
1039 <literal>||/</literal> <type>double precision</type>
1040 <returnvalue>double precision</returnvalue>
1041 </para>
1042 <para>
1043 Cube root
1044 </para>
1045 <para>
1046 <literal>||/ 64.0</literal>
1047 <returnvalue>4</returnvalue>
1048 </para></entry>
1049 </row>
1050
1051 <row>
1052 <entry role="func_table_entry"><para role="func_signature">
1053 <literal>@</literal> <replaceable>numeric_type</replaceable>
1054 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
1055 </para>
1056 <para>
1057 Absolute value
1058 </para>
1059 <para>
1060 <literal>@ -5.0</literal>
1061 <returnvalue>5.0</returnvalue>
1062 </para></entry>
1063 </row>
1064
1065 <row>
1066 <entry role="func_table_entry"><para role="func_signature">
1067 <replaceable>integral_type</replaceable> <literal>&amp;</literal> <replaceable>integral_type</replaceable>
1068 <returnvalue><replaceable>integral_type</replaceable></returnvalue>
1069 </para>
1070 <para>
1071 Bitwise AND
1072 </para>
1073 <para>
1074 <literal>91 &amp; 15</literal>
1075 <returnvalue>11</returnvalue>
1076 </para></entry>
1077 </row>
1078
1079 <row>
1080 <entry role="func_table_entry"><para role="func_signature">
1081 <replaceable>integral_type</replaceable> <literal>|</literal> <replaceable>integral_type</replaceable>
1082 <returnvalue><replaceable>integral_type</replaceable></returnvalue>
1083 </para>
1084 <para>
1085 Bitwise OR
1086 </para>
1087 <para>
1088 <literal>32 | 3</literal>
1089 <returnvalue>35</returnvalue>
1090 </para></entry>
1091 </row>
1092
1093 <row>
1094 <entry role="func_table_entry"><para role="func_signature">
1095 <replaceable>integral_type</replaceable> <literal>#</literal> <replaceable>integral_type</replaceable>
1096 <returnvalue><replaceable>integral_type</replaceable></returnvalue>
1097 </para>
1098 <para>
1099 Bitwise exclusive OR
1100 </para>
1101 <para>
1102 <literal>17 # 5</literal>
1103 <returnvalue>20</returnvalue>
1104 </para></entry>
1105 </row>
1106
1107 <row>
1108 <entry role="func_table_entry"><para role="func_signature">
1109 <literal>~</literal> <replaceable>integral_type</replaceable>
1110 <returnvalue><replaceable>integral_type</replaceable></returnvalue>
1111 </para>
1112 <para>
1113 Bitwise NOT
1114 </para>
1115 <para>
1116 <literal>~1</literal>
1117 <returnvalue>-2</returnvalue>
1118 </para></entry>
1119 </row>
1120
1121 <row>
1122 <entry role="func_table_entry"><para role="func_signature">
1123 <replaceable>integral_type</replaceable> <literal>&lt;&lt;</literal> <type>integer</type>
1124 <returnvalue><replaceable>integral_type</replaceable></returnvalue>
1125 </para>
1126 <para>
1127 Bitwise shift left
1128 </para>
1129 <para>
1130 <literal>1 &lt;&lt; 4</literal>
1131 <returnvalue>16</returnvalue>
1132 </para></entry>
1133 </row>
1134
1135 <row>
1136 <entry role="func_table_entry"><para role="func_signature">
1137 <replaceable>integral_type</replaceable> <literal>&gt;&gt;</literal> <type>integer</type>
1138 <returnvalue><replaceable>integral_type</replaceable></returnvalue>
1139 </para>
1140 <para>
1141 Bitwise shift right
1142 </para>
1143 <para>
1144 <literal>8 &gt;&gt; 2</literal>
1145 <returnvalue>2</returnvalue>
1146 </para></entry>
1147 </row>
1148
1149 </tbody>
1150 </tgroup>
1151 </table>
1152
1153 <para>
1154 <xref linkend="functions-math-func-table"/> shows the available
1155 mathematical functions.
1156 Many of these functions are provided in multiple forms with different
1157 argument types.
1158 Except where noted, any given form of a function returns the same
1159 data type as its argument(s); cross-type cases are resolved in the
1160 same way as explained above for operators.
1161 The functions working with <type>double precision</type> data are mostly
1162 implemented on top of the host system's C library; accuracy and behavior in
1163 boundary cases can therefore vary depending on the host system.
1164 </para>
1165
1166 <table id="functions-math-func-table">
1167 <title>Mathematical Functions</title>
1168 <tgroup cols="1">
1169 <thead>
1170 <row>
1171 <entry role="func_table_entry"><para role="func_signature">
1172 Function
1173 </para>
1174 <para>
1175 Description
1176 </para>
1177 <para>
1178 Example(s)
1179 </para></entry>
1180 </row>
1181 </thead>
1182
1183 <tbody>
1184 <row>
1185 <entry role="func_table_entry"><para role="func_signature">
1186 <indexterm>
1187 <primary>abs</primary>
1188 </indexterm>
1189 <function>abs</function> ( <replaceable>numeric_type</replaceable> )
1190 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
1191 </para>
1192 <para>
1193 Absolute value
1194 </para>
1195 <para>
1196 <literal>abs(-17.4)</literal>
1197 <returnvalue>17.4</returnvalue>
1198 </para></entry>
1199 </row>
1200
1201 <row>
1202 <entry role="func_table_entry"><para role="func_signature">
1203 <indexterm>
1204 <primary>cbrt</primary>
1205 </indexterm>
1206 <function>cbrt</function> ( <type>double precision</type> )
1207 <returnvalue>double precision</returnvalue>
1208 </para>
1209 <para>
1210 Cube root
1211 </para>
1212 <para>
1213 <literal>cbrt(64.0)</literal>
1214 <returnvalue>4</returnvalue>
1215 </para></entry>
1216 </row>
1217
1218 <row>
1219 <entry role="func_table_entry"><para role="func_signature">
1220 <indexterm>
1221 <primary>ceil</primary>
1222 </indexterm>
1223 <function>ceil</function> ( <type>numeric</type> )
1224 <returnvalue>numeric</returnvalue>
1225 </para>
1226 <para role="func_signature">
1227 <function>ceil</function> ( <type>double precision</type> )
1228 <returnvalue>double precision</returnvalue>
1229 </para>
1230 <para>
1231 Nearest integer greater than or equal to argument
1232 </para>
1233 <para>
1234 <literal>ceil(42.2)</literal>
1235 <returnvalue>43</returnvalue>
1236 </para>
1237 <para>
1238 <literal>ceil(-42.8)</literal>
1239 <returnvalue>-42</returnvalue>
1240 </para></entry>
1241 </row>
1242
1243 <row>
1244 <entry role="func_table_entry"><para role="func_signature">
1245 <indexterm>
1246 <primary>ceiling</primary>
1247 </indexterm>
1248 <function>ceiling</function> ( <type>numeric</type> )
1249 <returnvalue>numeric</returnvalue>
1250 </para>
1251 <para role="func_signature">
1252 <function>ceiling</function> ( <type>double precision</type> )
1253 <returnvalue>double precision</returnvalue>
1254 </para>
1255 <para>
1256 Nearest integer greater than or equal to argument (same
1257 as <function>ceil</function>)
1258 </para>
1259 <para>
1260 <literal>ceiling(95.3)</literal>
1261 <returnvalue>96</returnvalue>
1262 </para></entry>
1263 </row>
1264
1265 <row>
1266 <entry role="func_table_entry"><para role="func_signature">
1267 <indexterm>
1268 <primary>degrees</primary>
1269 </indexterm>
1270 <function>degrees</function> ( <type>double precision</type> )
1271 <returnvalue>double precision</returnvalue>
1272 </para>
1273 <para>
1274 Converts radians to degrees
1275 </para>
1276 <para>
1277 <literal>degrees(0.5)</literal>
1278 <returnvalue>28.64788975654116</returnvalue>
1279 </para></entry>
1280 </row>
1281
1282 <row>
1283 <entry role="func_table_entry"><para role="func_signature">
1284 <indexterm>
1285 <primary>div</primary>
1286 </indexterm>
1287 <function>div</function> ( <parameter>y</parameter> <type>numeric</type>,
1288 <parameter>x</parameter> <type>numeric</type> )
1289 <returnvalue>numeric</returnvalue>
1290 </para>
1291 <para>
1292 Integer quotient of <parameter>y</parameter>/<parameter>x</parameter>
1293 (truncates towards zero)
1294 </para>
1295 <para>
1296 <literal>div(9, 4)</literal>
1297 <returnvalue>2</returnvalue>
1298 </para></entry>
1299 </row>
1300
1301 <row>
1302 <entry role="func_table_entry"><para role="func_signature">
1303 <indexterm>
1304 <primary>erf</primary>
1305 </indexterm>
1306 <function>erf</function> ( <type>double precision</type> )
1307 <returnvalue>double precision</returnvalue>
1308 </para>
1309 <para>
1310 Error function
1311 </para>
1312 <para>
1313 <literal>erf(1.0)</literal>
1314 <returnvalue>0.8427007929497149</returnvalue>
1315 </para></entry>
1316 </row>
1317
1318 <row>
1319 <entry role="func_table_entry"><para role="func_signature">
1320 <indexterm>
1321 <primary>erfc</primary>
1322 </indexterm>
1323 <function>erfc</function> ( <type>double precision</type> )
1324 <returnvalue>double precision</returnvalue>
1325 </para>
1326 <para>
1327 Complementary error function (<literal>1 - erf(x)</literal>, without
1328 loss of precision for large inputs)
1329 </para>
1330 <para>
1331 <literal>erfc(1.0)</literal>
1332 <returnvalue>0.15729920705028513</returnvalue>
1333 </para></entry>
1334 </row>
1335
1336 <row>
1337 <entry role="func_table_entry"><para role="func_signature">
1338 <indexterm>
1339 <primary>exp</primary>
1340 </indexterm>
1341 <function>exp</function> ( <type>numeric</type> )
1342 <returnvalue>numeric</returnvalue>
1343 </para>
1344 <para role="func_signature">
1345 <function>exp</function> ( <type>double precision</type> )
1346 <returnvalue>double precision</returnvalue>
1347 </para>
1348 <para>
1349 Exponential (<literal>e</literal> raised to the given power)
1350 </para>
1351 <para>
1352 <literal>exp(1.0)</literal>
1353 <returnvalue>2.7182818284590452</returnvalue>
1354 </para></entry>
1355 </row>
1356
1357 <row>
1358 <entry role="func_table_entry"><para role="func_signature">
1359 <indexterm id="function-factorial">
1360 <primary>factorial</primary>
1361 </indexterm>
1362 <function>factorial</function> ( <type>bigint</type> )
1363 <returnvalue>numeric</returnvalue>
1364 </para>
1365 <para>
1366 Factorial
1367 </para>
1368 <para>
1369 <literal>factorial(5)</literal>
1370 <returnvalue>120</returnvalue>
1371 </para></entry>
1372 </row>
1373
1374 <row>
1375 <entry role="func_table_entry"><para role="func_signature">
1376 <indexterm>
1377 <primary>floor</primary>
1378 </indexterm>
1379 <function>floor</function> ( <type>numeric</type> )
1380 <returnvalue>numeric</returnvalue>
1381 </para>
1382 <para role="func_signature">
1383 <function>floor</function> ( <type>double precision</type> )
1384 <returnvalue>double precision</returnvalue>
1385 </para>
1386 <para>
1387 Nearest integer less than or equal to argument
1388 </para>
1389 <para>
1390 <literal>floor(42.8)</literal>
1391 <returnvalue>42</returnvalue>
1392 </para>
1393 <para>
1394 <literal>floor(-42.8)</literal>
1395 <returnvalue>-43</returnvalue>
1396 </para></entry>
1397 </row>
1398
1399 <row>
1400 <entry role="func_table_entry"><para role="func_signature">
1401 <indexterm>
1402 <primary>gamma</primary>
1403 </indexterm>
1404 <function>gamma</function> ( <type>double precision</type> )
1405 <returnvalue>double precision</returnvalue>
1406 </para>
1407 <para>
1408 Gamma function
1409 </para>
1410 <para>
1411 <literal>gamma(0.5)</literal>
1412 <returnvalue>1.772453850905516</returnvalue>
1413 </para>
1414 <para>
1415 <literal>gamma(6)</literal>
1416 <returnvalue>120</returnvalue>
1417 </para></entry>
1418 </row>
1419
1420 <row>
1421 <entry role="func_table_entry"><para role="func_signature">
1422 <indexterm>
1423 <primary>gcd</primary>
1424 </indexterm>
1425 <function>gcd</function> ( <replaceable>numeric_type</replaceable>, <replaceable>numeric_type</replaceable> )
1426 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
1427 </para>
1428 <para>
1429 Greatest common divisor (the largest positive number that divides both
1430 inputs with no remainder); returns <literal>0</literal> if both inputs
1431 are zero; available for <type>integer</type>, <type>bigint</type>,
1432 and <type>numeric</type>
1433 </para>
1434 <para>
1435 <literal>gcd(1071, 462)</literal>
1436 <returnvalue>21</returnvalue>
1437 </para></entry>
1438 </row>
1439
1440 <row>
1441 <entry role="func_table_entry"><para role="func_signature">
1442 <indexterm>
1443 <primary>lcm</primary>
1444 </indexterm>
1445 <function>lcm</function> ( <replaceable>numeric_type</replaceable>, <replaceable>numeric_type</replaceable> )
1446 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
1447 </para>
1448 <para>
1449 Least common multiple (the smallest strictly positive number that is
1450 an integral multiple of both inputs); returns <literal>0</literal> if
1451 either input is zero; available for <type>integer</type>,
1452 <type>bigint</type>, and <type>numeric</type>
1453 </para>
1454 <para>
1455 <literal>lcm(1071, 462)</literal>
1456 <returnvalue>23562</returnvalue>
1457 </para></entry>
1458 </row>
1459
1460 <row>
1461 <entry role="func_table_entry"><para role="func_signature">
1462 <indexterm>
1463 <primary>lgamma</primary>
1464 </indexterm>
1465 <function>lgamma</function> ( <type>double precision</type> )
1466 <returnvalue>double precision</returnvalue>
1467 </para>
1468 <para>
1469 Natural logarithm of the absolute value of the gamma function
1470 </para>
1471 <para>
1472 <literal>lgamma(1000)</literal>
1473 <returnvalue>5905.220423209181</returnvalue>
1474 </para></entry>
1475 </row>
1476
1477 <row>
1478 <entry role="func_table_entry"><para role="func_signature">
1479 <indexterm>
1480 <primary>ln</primary>
1481 </indexterm>
1482 <function>ln</function> ( <type>numeric</type> )
1483 <returnvalue>numeric</returnvalue>
1484 </para>
1485 <para role="func_signature">
1486 <function>ln</function> ( <type>double precision</type> )
1487 <returnvalue>double precision</returnvalue>
1488 </para>
1489 <para>
1490 Natural logarithm
1491 </para>
1492 <para>
1493 <literal>ln(2.0)</literal>
1494 <returnvalue>0.6931471805599453</returnvalue>
1495 </para></entry>
1496 </row>
1497
1498 <row>
1499 <entry role="func_table_entry"><para role="func_signature">
1500 <indexterm>
1501 <primary>log</primary>
1502 </indexterm>
1503 <function>log</function> ( <type>numeric</type> )
1504 <returnvalue>numeric</returnvalue>
1505 </para>
1506 <para role="func_signature">
1507 <function>log</function> ( <type>double precision</type> )
1508 <returnvalue>double precision</returnvalue>
1509 </para>
1510 <para>
1511 Base 10 logarithm
1512 </para>
1513 <para>
1514 <literal>log(100)</literal>
1515 <returnvalue>2</returnvalue>
1516 </para></entry>
1517 </row>
1518
1519 <row>
1520 <entry role="func_table_entry"><para role="func_signature">
1521 <indexterm>
1522 <primary>log10</primary>
1523 </indexterm>
1524 <function>log10</function> ( <type>numeric</type> )
1525 <returnvalue>numeric</returnvalue>
1526 </para>
1527 <para role="func_signature">
1528 <function>log10</function> ( <type>double precision</type> )
1529 <returnvalue>double precision</returnvalue>
1530 </para>
1531 <para>
1532 Base 10 logarithm (same as <function>log</function>)
1533 </para>
1534 <para>
1535 <literal>log10(1000)</literal>
1536 <returnvalue>3</returnvalue>
1537 </para></entry>
1538 </row>
1539
1540 <row>
1541 <entry role="func_table_entry"><para role="func_signature">
1542 <function>log</function> ( <parameter>b</parameter> <type>numeric</type>,
1543 <parameter>x</parameter> <type>numeric</type> )
1544 <returnvalue>numeric</returnvalue>
1545 </para>
1546 <para>
1547 Logarithm of <parameter>x</parameter> to base <parameter>b</parameter>
1548 </para>
1549 <para>
1550 <literal>log(2.0, 64.0)</literal>
1551 <returnvalue>6.0000000000000000</returnvalue>
1552 </para></entry>
1553 </row>
1554
1555 <row>
1556 <entry role="func_table_entry"><para role="func_signature">
1557 <indexterm>
1558 <primary>min_scale</primary>
1559 </indexterm>
1560 <function>min_scale</function> ( <type>numeric</type> )
1561 <returnvalue>integer</returnvalue>
1562 </para>
1563 <para>
1564 Minimum scale (number of fractional decimal digits) needed
1565 to represent the supplied value precisely
1566 </para>
1567 <para>
1568 <literal>min_scale(8.4100)</literal>
1569 <returnvalue>2</returnvalue>
1570 </para></entry>
1571 </row>
1572
1573 <row>
1574 <entry role="func_table_entry"><para role="func_signature">
1575 <indexterm>
1576 <primary>mod</primary>
1577 </indexterm>
1578 <function>mod</function> ( <parameter>y</parameter> <replaceable>numeric_type</replaceable>,
1579 <parameter>x</parameter> <replaceable>numeric_type</replaceable> )
1580 <returnvalue><replaceable>numeric_type</replaceable></returnvalue>
1581 </para>
1582 <para>
1583 Remainder of <parameter>y</parameter>/<parameter>x</parameter>;
1584 available for <type>smallint</type>, <type>integer</type>,
1585 <type>bigint</type>, and <type>numeric</type>
1586 </para>
1587 <para>
1588 <literal>mod(9, 4)</literal>
1589 <returnvalue>1</returnvalue>
1590 </para></entry>
1591 </row>
1592
1593 <row>
1594 <entry role="func_table_entry"><para role="func_signature">
1595 <indexterm>
1596 <primary>pi</primary>
1597 </indexterm>
1598 <function>pi</function> ( )
1599 <returnvalue>double precision</returnvalue>
1600 </para>
1601 <para>
1602 Approximate value of <phrase role="symbol_font">&pi;</phrase>
1603 </para>
1604 <para>
1605 <literal>pi()</literal>
1606 <returnvalue>3.141592653589793</returnvalue>
1607 </para></entry>
1608 </row>
1609
1610 <row>
1611 <entry role="func_table_entry"><para role="func_signature">
1612 <indexterm>
1613 <primary>power</primary>
1614 </indexterm>
1615 <function>power</function> ( <parameter>a</parameter> <type>numeric</type>,
1616 <parameter>b</parameter> <type>numeric</type> )
1617 <returnvalue>numeric</returnvalue>
1618 </para>
1619 <para role="func_signature">
1620 <function>power</function> ( <parameter>a</parameter> <type>double precision</type>,
1621 <parameter>b</parameter> <type>double precision</type> )
1622 <returnvalue>double precision</returnvalue>
1623 </para>
1624 <para>
1625 <parameter>a</parameter> raised to the power of <parameter>b</parameter>
1626 </para>
1627 <para>
1628 <literal>power(9, 3)</literal>
1629 <returnvalue>729</returnvalue>
1630 </para></entry>
1631 </row>
1632
1633 <row>
1634 <entry role="func_table_entry"><para role="func_signature">
1635 <indexterm>
1636 <primary>radians</primary>
1637 </indexterm>
1638 <function>radians</function> ( <type>double precision</type> )
1639 <returnvalue>double precision</returnvalue>
1640 </para>
1641 <para>
1642 Converts degrees to radians
1643 </para>
1644 <para>
1645 <literal>radians(45.0)</literal>
1646 <returnvalue>0.7853981633974483</returnvalue>
1647 </para></entry>
1648 </row>
1649
1650 <row>
1651 <entry role="func_table_entry"><para role="func_signature">
1652 <indexterm>
1653 <primary>round</primary>
1654 </indexterm>
1655 <function>round</function> ( <type>numeric</type> )
1656 <returnvalue>numeric</returnvalue>
1657 </para>
1658 <para role="func_signature">
1659 <function>round</function> ( <type>double precision</type> )
1660 <returnvalue>double precision</returnvalue>
1661 </para>
1662 <para>
1663 Rounds to nearest integer. For <type>numeric</type>, ties are
1664 broken by rounding away from zero. For <type>double precision</type>,
1665 the tie-breaking behavior is platform dependent, but
1666 <quote>round to nearest even</quote> is the most common rule.
1667 </para>
1668 <para>
1669 <literal>round(42.4)</literal>
1670 <returnvalue>42</returnvalue>
1671 </para></entry>
1672 </row>
1673
1674 <row>
1675 <entry role="func_table_entry"><para role="func_signature">
1676 <function>round</function> ( <parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>integer</type> )
1677 <returnvalue>numeric</returnvalue>
1678 </para>
1679 <para>
1680 Rounds <parameter>v</parameter> to <parameter>s</parameter> decimal
1681 places. Ties are broken by rounding away from zero.
1682 </para>
1683 <para>
1684 <literal>round(42.4382, 2)</literal>
1685 <returnvalue>42.44</returnvalue>
1686 </para>
1687 <para>
1688 <literal>round(1234.56, -1)</literal>
1689 <returnvalue>1230</returnvalue>
1690 </para></entry>
1691 </row>
1692
1693 <row>
1694 <entry role="func_table_entry"><para role="func_signature">
1695 <indexterm>
1696 <primary>scale</primary>
1697 </indexterm>
1698 <function>scale</function> ( <type>numeric</type> )
1699 <returnvalue>integer</returnvalue>
1700 </para>
1701 <para>
1702 Scale of the argument (the number of decimal digits in the fractional part)
1703 </para>
1704 <para>
1705 <literal>scale(8.4100)</literal>
1706 <returnvalue>4</returnvalue>
1707 </para></entry>
1708 </row>
1709
1710 <row>
1711 <entry role="func_table_entry"><para role="func_signature">
1712 <indexterm>
1713 <primary>sign</primary>
1714 </indexterm>
1715 <function>sign</function> ( <type>numeric</type> )
1716 <returnvalue>numeric</returnvalue>
1717 </para>
1718 <para role="func_signature">
1719 <function>sign</function> ( <type>double precision</type> )
1720 <returnvalue>double precision</returnvalue>
1721 </para>
1722 <para>
1723 Sign of the argument (-1, 0, or +1)
1724 </para>
1725 <para>
1726 <literal>sign(-8.4)</literal>
1727 <returnvalue>-1</returnvalue>
1728 </para></entry>
1729 </row>
1730
1731 <row>
1732 <entry role="func_table_entry"><para role="func_signature">
1733 <indexterm>
1734 <primary>sqrt</primary>
1735 </indexterm>
1736 <function>sqrt</function> ( <type>numeric</type> )
1737 <returnvalue>numeric</returnvalue>
1738 </para>
1739 <para role="func_signature">
1740 <function>sqrt</function> ( <type>double precision</type> )
1741 <returnvalue>double precision</returnvalue>
1742 </para>
1743 <para>
1744 Square root
1745 </para>
1746 <para>
1747 <literal>sqrt(2)</literal>
1748 <returnvalue>1.4142135623730951</returnvalue>
1749 </para></entry>
1750 </row>
1751
1752 <row>
1753 <entry role="func_table_entry"><para role="func_signature">
1754 <indexterm>
1755 <primary>trim_scale</primary>
1756 </indexterm>
1757 <function>trim_scale</function> ( <type>numeric</type> )
1758 <returnvalue>numeric</returnvalue>
1759 </para>
1760 <para>
1761 Reduces the value's scale (number of fractional decimal digits) by
1762 removing trailing zeroes
1763 </para>
1764 <para>
1765 <literal>trim_scale(8.4100)</literal>
1766 <returnvalue>8.41</returnvalue>
1767 </para></entry>
1768 </row>
1769
1770 <row>
1771 <entry role="func_table_entry"><para role="func_signature">
1772 <indexterm>
1773 <primary>trunc</primary>
1774 </indexterm>
1775 <function>trunc</function> ( <type>numeric</type> )
1776 <returnvalue>numeric</returnvalue>
1777 </para>
1778 <para role="func_signature">
1779 <function>trunc</function> ( <type>double precision</type> )
1780 <returnvalue>double precision</returnvalue>
1781 </para>
1782 <para>
1783 Truncates to integer (towards zero)
1784 </para>
1785 <para>
1786 <literal>trunc(42.8)</literal>
1787 <returnvalue>42</returnvalue>
1788 </para>
1789 <para>
1790 <literal>trunc(-42.8)</literal>
1791 <returnvalue>-42</returnvalue>
1792 </para></entry>
1793 </row>
1794
1795 <row>
1796 <entry role="func_table_entry"><para role="func_signature">
1797 <function>trunc</function> ( <parameter>v</parameter> <type>numeric</type>, <parameter>s</parameter> <type>integer</type> )
1798 <returnvalue>numeric</returnvalue>
1799 </para>
1800 <para>
1801 Truncates <parameter>v</parameter> to <parameter>s</parameter>
1802 decimal places
1803 </para>
1804 <para>
1805 <literal>trunc(42.4382, 2)</literal>
1806 <returnvalue>42.43</returnvalue>
1807 </para></entry>
1808 </row>
1809
1810 <row>
1811 <entry role="func_table_entry"><para role="func_signature">
1812 <indexterm>
1813 <primary>width_bucket</primary>
1814 </indexterm>
1815 <function>width_bucket</function> ( <parameter>operand</parameter> <type>numeric</type>, <parameter>low</parameter> <type>numeric</type>, <parameter>high</parameter> <type>numeric</type>, <parameter>count</parameter> <type>integer</type> )
1816 <returnvalue>integer</returnvalue>
1817 </para>
1818 <para role="func_signature">
1819 <function>width_bucket</function> ( <parameter>operand</parameter> <type>double precision</type>, <parameter>low</parameter> <type>double precision</type>, <parameter>high</parameter> <type>double precision</type>, <parameter>count</parameter> <type>integer</type> )
1820 <returnvalue>integer</returnvalue>
1821 </para>
1822 <para>
1823 Returns the number of the bucket in
1824 which <parameter>operand</parameter> falls in a histogram
1825 having <parameter>count</parameter> equal-width buckets spanning the
1826 range <parameter>low</parameter> to <parameter>high</parameter>.
1827 The buckets have inclusive lower bounds and exclusive upper bounds.
1828 Returns <literal>0</literal> for an input less
1829 than <parameter>low</parameter>,
1830 or <literal><parameter>count</parameter>+1</literal> for an input
1831 greater than or equal to <parameter>high</parameter>.
1832 If <parameter>low</parameter> &gt; <parameter>high</parameter>,
1833 the behavior is mirror-reversed, with bucket <literal>1</literal>
1834 now being the one just below <parameter>low</parameter>, and the
1835 inclusive bounds now being on the upper side.
1836 </para>
1837 <para>
1838 <literal>width_bucket(5.35, 0.024, 10.06, 5)</literal>
1839 <returnvalue>3</returnvalue>
1840 </para>
1841 <para>
1842 <literal>width_bucket(9, 10, 0, 10)</literal>
1843 <returnvalue>2</returnvalue>
1844 </para></entry>
1845 </row>
1846
1847 <row>
1848 <entry role="func_table_entry"><para role="func_signature">
1849 <function>width_bucket</function> ( <parameter>operand</parameter> <type>anycompatible</type>, <parameter>thresholds</parameter> <type>anycompatiblearray</type> )
1850 <returnvalue>integer</returnvalue>
1851 </para>
1852 <para>
1853 Returns the number of the bucket in
1854 which <parameter>operand</parameter> falls given an array listing the
1855 inclusive lower bounds of the buckets.
1856 Returns <literal>0</literal> for an input less than the first lower
1857 bound. <parameter>operand</parameter> and the array elements can be
1858 of any type having standard comparison operators.
1859 The <parameter>thresholds</parameter> array <emphasis>must be
1860 sorted</emphasis>, smallest first, or unexpected results will be
1861 obtained.
1862 </para>
1863 <para>
1864 <literal>width_bucket(now(), array['yesterday', 'today', 'tomorrow']::timestamptz[])</literal>
1865 <returnvalue>2</returnvalue>
1866 </para></entry>
1867 </row>
1868 </tbody>
1869 </tgroup>
1870 </table>
1871
1872 <para>
1873 <xref linkend="functions-math-random-table"/> shows functions for
1874 generating random numbers.
1875 </para>
1876
1877 <table id="functions-math-random-table">
1878 <title>Random Functions</title>
1879
1880 <tgroup cols="1">
1881 <thead>
1882 <row>
1883 <entry role="func_table_entry"><para role="func_signature">
1884 Function
1885 </para>
1886 <para>
1887 Description
1888 </para>
1889 <para>
1890 Example(s)
1891 </para></entry>
1892 </row>
1893 </thead>
1894
1895 <tbody>
1896 <row>
1897 <entry role="func_table_entry"><para role="func_signature">
1898 <indexterm>
1899 <primary>random</primary>
1900 </indexterm>
1901 <function>random</function> ( )
1902 <returnvalue>double precision</returnvalue>
1903 </para>
1904 <para>
1905 Returns a random value in the range 0.0 &lt;= x &lt; 1.0
1906 </para>
1907 <para>
1908 <literal>random()</literal>
1909 <returnvalue>0.897124072839091</returnvalue>
1910 </para></entry>
1911 </row>
1912
1913 <row>
1914 <entry role="func_table_entry"><para role="func_signature">
1915 <indexterm>
1916 <primary>random</primary>
1917 </indexterm>
1918 <function>random</function> ( <parameter>min</parameter> <type>integer</type>, <parameter>max</parameter> <type>integer</type> )
1919 <returnvalue>integer</returnvalue>
1920 </para>
1921 <para role="func_signature">
1922 <function>random</function> ( <parameter>min</parameter> <type>bigint</type>, <parameter>max</parameter> <type>bigint</type> )
1923 <returnvalue>bigint</returnvalue>
1924 </para>
1925 <para role="func_signature">
1926 <function>random</function> ( <parameter>min</parameter> <type>numeric</type>, <parameter>max</parameter> <type>numeric</type> )
1927 <returnvalue>numeric</returnvalue>
1928 </para>
1929 <para>
1930 Returns a random value in the range
1931 <parameter>min</parameter> &lt;= x &lt;= <parameter>max</parameter>.
1932 For type <type>numeric</type>, the result will have the same number of
1933 fractional decimal digits as <parameter>min</parameter> or
1934 <parameter>max</parameter>, whichever has more.
1935 </para>
1936 <para>
1937 <literal>random(1, 10)</literal>
1938 <returnvalue>7</returnvalue>
1939 </para>
1940 <para>
1941 <literal>random(-0.499, 0.499)</literal>
1942 <returnvalue>0.347</returnvalue>
1943 </para></entry>
1944 </row>
1945
1946 <row>
1947 <entry role="func_table_entry"><para role="func_signature">
1948 <indexterm>
1949 <primary>random_normal</primary>
1950 </indexterm>
1951
1952 <function>random_normal</function> (
1953 <optional> <parameter>mean</parameter> <type>double precision</type>
1954 <optional>, <parameter>stddev</parameter> <type>double precision</type> </optional></optional> )
1955 <returnvalue>double precision</returnvalue>
1956 </para>
1957 <para>
1958 Returns a random value from the normal distribution with the given
1959 parameters; <parameter>mean</parameter> defaults to 0.0
1960 and <parameter>stddev</parameter> defaults to 1.0
1961 </para>
1962 <para>
1963 <literal>random_normal(0.0, 1.0)</literal>
1964 <returnvalue>0.051285419</returnvalue>
1965 </para></entry>
1966 </row>
1967
1968 <row>
1969 <entry role="func_table_entry"><para role="func_signature">
1970 <indexterm>
1971 <primary>setseed</primary>
1972 </indexterm>
1973 <function>setseed</function> ( <type>double precision</type> )
1974 <returnvalue>void</returnvalue>
1975 </para>
1976 <para>
1977 Sets the seed for subsequent <literal>random()</literal> and
1978 <literal>random_normal()</literal> calls;
1979 argument must be between -1.0 and 1.0, inclusive
1980 </para>
1981 <para>
1982 <literal>setseed(0.12345)</literal>
1983 </para></entry>
1984 </row>
1985 </tbody>
1986 </tgroup>
1987 </table>
1988
1989 <para>
1990 The <function>random()</function> and <function>random_normal()</function>
1991 functions listed in <xref linkend="functions-math-random-table"/> use a
1992 deterministic pseudo-random number generator.
1993 It is fast but not suitable for cryptographic
1994 applications; see the <xref linkend="pgcrypto"/> module for a more
1995 secure alternative.
1996 If <function>setseed()</function> is called, the series of results of
1997 subsequent calls to these functions in the current session
1998 can be repeated by re-issuing <function>setseed()</function> with the same
1999 argument.
2000 Without any prior <function>setseed()</function> call in the same
2001 session, the first call to any of these functions obtains a seed
2002 from a platform-dependent source of random bits.
2003 </para>
2004
2005 <para>
2006 <xref linkend="functions-math-trig-table"/> shows the
2007 available trigonometric functions. Each of these functions comes in
2008 two variants, one that measures angles in radians and one that
2009 measures angles in degrees.
2010 </para>
2011
2012 <table id="functions-math-trig-table">
2013 <title>Trigonometric Functions</title>
2014
2015 <tgroup cols="1">
2016 <thead>
2017 <row>
2018 <entry role="func_table_entry"><para role="func_signature">
2019 Function
2020 </para>
2021 <para>
2022 Description
2023 </para>
2024 <para>
2025 Example(s)
2026 </para></entry>
2027 </row>
2028 </thead>
2029
2030 <tbody>
2031 <row>
2032 <entry role="func_table_entry"><para role="func_signature">
2033 <indexterm>
2034 <primary>acos</primary>
2035 </indexterm>
2036 <function>acos</function> ( <type>double precision</type> )
2037 <returnvalue>double precision</returnvalue>
2038 </para>
2039 <para>
2040 Inverse cosine, result in radians
2041 </para>
2042 <para>
2043 <literal>acos(1)</literal>
2044 <returnvalue>0</returnvalue>
2045 </para></entry>
2046 </row>
2047
2048 <row>
2049 <entry role="func_table_entry"><para role="func_signature">
2050 <indexterm>
2051 <primary>acosd</primary>
2052 </indexterm>
2053 <function>acosd</function> ( <type>double precision</type> )
2054 <returnvalue>double precision</returnvalue>
2055 </para>
2056 <para>
2057 Inverse cosine, result in degrees
2058 </para>
2059 <para>
2060 <literal>acosd(0.5)</literal>
2061 <returnvalue>60</returnvalue>
2062 </para></entry>
2063 </row>
2064
2065 <row>
2066 <entry role="func_table_entry"><para role="func_signature">
2067 <indexterm>
2068 <primary>asin</primary>
2069 </indexterm>
2070 <function>asin</function> ( <type>double precision</type> )
2071 <returnvalue>double precision</returnvalue>
2072 </para>
2073 <para>
2074 Inverse sine, result in radians
2075 </para>
2076 <para>
2077 <literal>asin(1)</literal>
2078 <returnvalue>1.5707963267948966</returnvalue>
2079 </para></entry>
2080 </row>
2081
2082 <row>
2083 <entry role="func_table_entry"><para role="func_signature">
2084 <indexterm>
2085 <primary>asind</primary>
2086 </indexterm>
2087 <function>asind</function> ( <type>double precision</type> )
2088 <returnvalue>double precision</returnvalue>
2089 </para>
2090 <para>
2091 Inverse sine, result in degrees
2092 </para>
2093 <para>
2094 <literal>asind(0.5)</literal>
2095 <returnvalue>30</returnvalue>
2096 </para></entry>
2097 </row>
2098
2099 <row>
2100 <entry role="func_table_entry"><para role="func_signature">
2101 <indexterm>
2102 <primary>atan</primary>
2103 </indexterm>
2104 <function>atan</function> ( <type>double precision</type> )
2105 <returnvalue>double precision</returnvalue>
2106 </para>
2107 <para>
2108 Inverse tangent, result in radians
2109 </para>
2110 <para>
2111 <literal>atan(1)</literal>
2112 <returnvalue>0.7853981633974483</returnvalue>
2113 </para></entry>
2114 </row>
2115
2116 <row>
2117 <entry role="func_table_entry"><para role="func_signature">
2118 <indexterm>
2119 <primary>atand</primary>
2120 </indexterm>
2121 <function>atand</function> ( <type>double precision</type> )
2122 <returnvalue>double precision</returnvalue>
2123 </para>
2124 <para>
2125 Inverse tangent, result in degrees
2126 </para>
2127 <para>
2128 <literal>atand(1)</literal>
2129 <returnvalue>45</returnvalue>
2130 </para></entry>
2131 </row>
2132
2133 <row>
2134 <entry role="func_table_entry"><para role="func_signature">
2135 <indexterm>
2136 <primary>atan2</primary>
2137 </indexterm>
2138 <function>atan2</function> ( <parameter>y</parameter> <type>double precision</type>,
2139 <parameter>x</parameter> <type>double precision</type> )
2140 <returnvalue>double precision</returnvalue>
2141 </para>
2142 <para>
2143 Inverse tangent of
2144 <parameter>y</parameter>/<parameter>x</parameter>,
2145 result in radians
2146 </para>
2147 <para>
2148 <literal>atan2(1, 0)</literal>
2149 <returnvalue>1.5707963267948966</returnvalue>
2150 </para></entry>
2151 </row>
2152
2153 <row>
2154 <entry role="func_table_entry"><para role="func_signature">
2155 <indexterm>
2156 <primary>atan2d</primary>
2157 </indexterm>
2158 <function>atan2d</function> ( <parameter>y</parameter> <type>double precision</type>,
2159 <parameter>x</parameter> <type>double precision</type> )
2160 <returnvalue>double precision</returnvalue>
2161 </para>
2162 <para>
2163 Inverse tangent of
2164 <parameter>y</parameter>/<parameter>x</parameter>,
2165 result in degrees
2166 </para>
2167 <para>
2168 <literal>atan2d(1, 0)</literal>
2169 <returnvalue>90</returnvalue>
2170 </para></entry>
2171 </row>
2172
2173 <row>
2174 <entry role="func_table_entry"><para role="func_signature">
2175 <indexterm>
2176 <primary>cos</primary>
2177 </indexterm>
2178 <function>cos</function> ( <type>double precision</type> )
2179 <returnvalue>double precision</returnvalue>
2180 </para>
2181 <para>
2182 Cosine, argument in radians
2183 </para>
2184 <para>
2185 <literal>cos(0)</literal>
2186 <returnvalue>1</returnvalue>
2187 </para></entry>
2188 </row>
2189
2190 <row>
2191 <entry role="func_table_entry"><para role="func_signature">
2192 <indexterm>
2193 <primary>cosd</primary>
2194 </indexterm>
2195 <function>cosd</function> ( <type>double precision</type> )
2196 <returnvalue>double precision</returnvalue>
2197 </para>
2198 <para>
2199 Cosine, argument in degrees
2200 </para>
2201 <para>
2202 <literal>cosd(60)</literal>
2203 <returnvalue>0.5</returnvalue>
2204 </para></entry>
2205 </row>
2206
2207 <row>
2208 <entry role="func_table_entry"><para role="func_signature">
2209 <indexterm>
2210 <primary>cot</primary>
2211 </indexterm>
2212 <function>cot</function> ( <type>double precision</type> )
2213 <returnvalue>double precision</returnvalue>
2214 </para>
2215 <para>
2216 Cotangent, argument in radians
2217 </para>
2218 <para>
2219 <literal>cot(0.5)</literal>
2220 <returnvalue>1.830487721712452</returnvalue>
2221 </para></entry>
2222 </row>
2223
2224 <row>
2225 <entry role="func_table_entry"><para role="func_signature">
2226 <indexterm>
2227 <primary>cotd</primary>
2228 </indexterm>
2229 <function>cotd</function> ( <type>double precision</type> )
2230 <returnvalue>double precision</returnvalue>
2231 </para>
2232 <para>
2233 Cotangent, argument in degrees
2234 </para>
2235 <para>
2236 <literal>cotd(45)</literal>
2237 <returnvalue>1</returnvalue>
2238 </para></entry>
2239 </row>
2240
2241 <row>
2242 <entry role="func_table_entry"><para role="func_signature">
2243 <indexterm>
2244 <primary>sin</primary>
2245 </indexterm>
2246 <function>sin</function> ( <type>double precision</type> )
2247 <returnvalue>double precision</returnvalue>
2248 </para>
2249 <para>
2250 Sine, argument in radians
2251 </para>
2252 <para>
2253 <literal>sin(1)</literal>
2254 <returnvalue>0.8414709848078965</returnvalue>
2255 </para></entry>
2256 </row>
2257
2258 <row>
2259 <entry role="func_table_entry"><para role="func_signature">
2260 <indexterm>
2261 <primary>sind</primary>
2262 </indexterm>
2263 <function>sind</function> ( <type>double precision</type> )
2264 <returnvalue>double precision</returnvalue>
2265 </para>
2266 <para>
2267 Sine, argument in degrees
2268 </para>
2269 <para>
2270 <literal>sind(30)</literal>
2271 <returnvalue>0.5</returnvalue>
2272 </para></entry>
2273 </row>
2274
2275 <row>
2276 <entry role="func_table_entry"><para role="func_signature">
2277 <indexterm>
2278 <primary>tan</primary>
2279 </indexterm>
2280 <function>tan</function> ( <type>double precision</type> )
2281 <returnvalue>double precision</returnvalue>
2282 </para>
2283 <para>
2284 Tangent, argument in radians
2285 </para>
2286 <para>
2287 <literal>tan(1)</literal>
2288 <returnvalue>1.5574077246549023</returnvalue>
2289 </para></entry>
2290 </row>
2291
2292 <row>
2293 <entry role="func_table_entry"><para role="func_signature">
2294 <indexterm>
2295 <primary>tand</primary>
2296 </indexterm>
2297 <function>tand</function> ( <type>double precision</type> )
2298 <returnvalue>double precision</returnvalue>
2299 </para>
2300 <para>
2301 Tangent, argument in degrees
2302 </para>
2303 <para>
2304 <literal>tand(45)</literal>
2305 <returnvalue>1</returnvalue>
2306 </para></entry>
2307 </row>
2308 </tbody>
2309 </tgroup>
2310 </table>
2311
2312 <note>
2313 <para>
2314 Another way to work with angles measured in degrees is to use the unit
2315 transformation functions <literal><function>radians()</function></literal>
2316 and <literal><function>degrees()</function></literal> shown earlier.
2317 However, using the degree-based trigonometric functions is preferred,
2318 as that way avoids round-off error for special cases such
2319 as <literal>sind(30)</literal>.
2320 </para>
2321 </note>
2322
2323 <para>
2324 <xref linkend="functions-math-hyp-table"/> shows the
2325 available hyperbolic functions.
2326 </para>
2327
2328 <table id="functions-math-hyp-table">
2329 <title>Hyperbolic Functions</title>
2330
2331 <tgroup cols="1">
2332 <thead>
2333 <row>
2334 <entry role="func_table_entry"><para role="func_signature">
2335 Function
2336 </para>
2337 <para>
2338 Description
2339 </para>
2340 <para>
2341 Example(s)
2342 </para></entry>
2343 </row>
2344 </thead>
2345
2346 <tbody>
2347 <row>
2348 <entry role="func_table_entry"><para role="func_signature">
2349 <indexterm>
2350 <primary>sinh</primary>
2351 </indexterm>
2352 <function>sinh</function> ( <type>double precision</type> )
2353 <returnvalue>double precision</returnvalue>
2354 </para>
2355 <para>
2356 Hyperbolic sine
2357 </para>
2358 <para>
2359 <literal>sinh(1)</literal>
2360 <returnvalue>1.1752011936438014</returnvalue>
2361 </para></entry>
2362 </row>
2363
2364 <row>
2365 <entry role="func_table_entry"><para role="func_signature">
2366 <indexterm>
2367 <primary>cosh</primary>
2368 </indexterm>
2369 <function>cosh</function> ( <type>double precision</type> )
2370 <returnvalue>double precision</returnvalue>
2371 </para>
2372 <para>
2373 Hyperbolic cosine
2374 </para>
2375 <para>
2376 <literal>cosh(0)</literal>
2377 <returnvalue>1</returnvalue>
2378 </para></entry>
2379 </row>
2380
2381 <row>
2382 <entry role="func_table_entry"><para role="func_signature">
2383 <indexterm>
2384 <primary>tanh</primary>
2385 </indexterm>
2386 <function>tanh</function> ( <type>double precision</type> )
2387 <returnvalue>double precision</returnvalue>
2388 </para>
2389 <para>
2390 Hyperbolic tangent
2391 </para>
2392 <para>
2393 <literal>tanh(1)</literal>
2394 <returnvalue>0.7615941559557649</returnvalue>
2395 </para></entry>
2396 </row>
2397
2398 <row>
2399 <entry role="func_table_entry"><para role="func_signature">
2400 <indexterm>
2401 <primary>asinh</primary>
2402 </indexterm>
2403 <function>asinh</function> ( <type>double precision</type> )
2404 <returnvalue>double precision</returnvalue>
2405 </para>
2406 <para>
2407 Inverse hyperbolic sine
2408 </para>
2409 <para>
2410 <literal>asinh(1)</literal>
2411 <returnvalue>0.881373587019543</returnvalue>
2412 </para></entry>
2413 </row>
2414
2415 <row>
2416 <entry role="func_table_entry"><para role="func_signature">
2417 <indexterm>
2418 <primary>acosh</primary>
2419 </indexterm>
2420 <function>acosh</function> ( <type>double precision</type> )
2421 <returnvalue>double precision</returnvalue>
2422 </para>
2423 <para>
2424 Inverse hyperbolic cosine
2425 </para>
2426 <para>
2427 <literal>acosh(1)</literal>
2428 <returnvalue>0</returnvalue>
2429 </para></entry>
2430 </row>
2431
2432 <row>
2433 <entry role="func_table_entry"><para role="func_signature">
2434 <indexterm>
2435 <primary>atanh</primary>
2436 </indexterm>
2437 <function>atanh</function> ( <type>double precision</type> )
2438 <returnvalue>double precision</returnvalue>
2439 </para>
2440 <para>
2441 Inverse hyperbolic tangent
2442 </para>
2443 <para>
2444 <literal>atanh(0.5)</literal>
2445 <returnvalue>0.5493061443340548</returnvalue>
2446 </para></entry>
2447 </row>
2448 </tbody>
2449 </tgroup>
2450 </table>
2451
2452 </sect1>
2453
2454
2455 <sect1 id="functions-string">
2456 <title>String Functions and Operators</title>
2457
2458 <para>
2459 This section describes functions and operators for examining and
2460 manipulating string values. Strings in this context include values
2461 of the types <type>character</type>, <type>character varying</type>,
2462 and <type>text</type>. Except where noted, these functions and operators
2463 are declared to accept and return type <type>text</type>. They will
2464 interchangeably accept <type>character varying</type> arguments.
2465 Values of type <type>character</type> will be converted
2466 to <type>text</type> before the function or operator is applied, resulting
2467 in stripping any trailing spaces in the <type>character</type> value.
2468 </para>
2469
2470 <para>
2471 <acronym>SQL</acronym> defines some string functions that use
2472 key words, rather than commas, to separate
2473 arguments. Details are in
2474 <xref linkend="functions-string-sql"/>.
2475 <productname>PostgreSQL</productname> also provides versions of these functions
2476 that use the regular function invocation syntax
2477 (see <xref linkend="functions-string-other"/>).
2478 </para>
2479
2480 <note>
2481 <para>
2482 The string concatenation operator (<literal>||</literal>) will accept
2483 non-string input, so long as at least one input is of string type, as shown
2484 in <xref linkend="functions-string-sql"/>. For other cases, inserting an
2485 explicit coercion to <type>text</type> can be used to have non-string input
2486 accepted.
2487 </para>
2488 </note>
2489
2490 <table id="functions-string-sql">
2491 <title><acronym>SQL</acronym> String Functions and Operators</title>
2492 <tgroup cols="1">
2493 <thead>
2494 <row>
2495 <entry role="func_table_entry"><para role="func_signature">
2496 Function/Operator
2497 </para>
2498 <para>
2499 Description
2500 </para>
2501 <para>
2502 Example(s)
2503 </para></entry>
2504 </row>
2505 </thead>
2506
2507 <tbody>
2508 <row>
2509 <entry role="func_table_entry"><para role="func_signature">
2510 <indexterm>
2511 <primary>character string</primary>
2512 <secondary>concatenation</secondary>
2513 </indexterm>
2514 <type>text</type> <literal>||</literal> <type>text</type>
2515 <returnvalue>text</returnvalue>
2516 </para>
2517 <para>
2518 Concatenates the two strings.
2519 </para>
2520 <para>
2521 <literal>'Post' || 'greSQL'</literal>
2522 <returnvalue>PostgreSQL</returnvalue>
2523 </para></entry>
2524 </row>
2525
2526 <row>
2527 <entry role="func_table_entry"><para role="func_signature">
2528 <type>text</type> <literal>||</literal> <type>anynonarray</type>
2529 <returnvalue>text</returnvalue>
2530 </para>
2531 <para role="func_signature">
2532 <type>anynonarray</type> <literal>||</literal> <type>text</type>
2533 <returnvalue>text</returnvalue>
2534 </para>
2535 <para>
2536 Converts the non-string input to text, then concatenates the two
2537 strings. (The non-string input cannot be of an array type, because
2538 that would create ambiguity with the array <literal>||</literal>
2539 operators. If you want to concatenate an array's text equivalent,
2540 cast it to <type>text</type> explicitly.)
2541 </para>
2542 <para>
2543 <literal>'Value: ' || 42</literal>
2544 <returnvalue>Value: 42</returnvalue>
2545 </para></entry>
2546 </row>
2547
2548 <row>
2549 <entry role="func_table_entry"><para role="func_signature">
2550 <indexterm>
2551 <primary>btrim</primary>
2552 </indexterm>
2553 <function>btrim</function> ( <parameter>string</parameter> <type>text</type>
2554 <optional>, <parameter>characters</parameter> <type>text</type> </optional> )
2555 <returnvalue>text</returnvalue>
2556 </para>
2557 <para>
2558 Removes the longest string containing only characters
2559 in <parameter>characters</parameter> (a space by default)
2560 from the start and end of <parameter>string</parameter>.
2561 </para>
2562 <para>
2563 <literal>btrim('xyxtrimyyx', 'xyz')</literal>
2564 <returnvalue>trim</returnvalue>
2565 </para></entry>
2566 </row>
2567
2568 <row>
2569 <entry role="func_table_entry"><para role="func_signature">
2570 <indexterm>
2571 <primary>normalized</primary>
2572 </indexterm>
2573 <indexterm>
2574 <primary>Unicode normalization</primary>
2575 </indexterm>
2576 <type>text</type> <literal>IS</literal> <optional><literal>NOT</literal></optional> <optional><parameter>form</parameter></optional> <literal>NORMALIZED</literal>
2577 <returnvalue>boolean</returnvalue>
2578 </para>
2579 <para>
2580 Checks whether the string is in the specified Unicode normalization
2581 form. The optional <parameter>form</parameter> key word specifies the
2582 form: <literal>NFC</literal> (the default), <literal>NFD</literal>,
2583 <literal>NFKC</literal>, or <literal>NFKD</literal>. This expression can
2584 only be used when the server encoding is <literal>UTF8</literal>. Note
2585 that checking for normalization using this expression is often faster
2586 than normalizing possibly already normalized strings.
2587 </para>
2588 <para>
2589 <literal>U&amp;'\0061\0308bc' IS NFD NORMALIZED</literal>
2590 <returnvalue>t</returnvalue>
2591 </para></entry>
2592 </row>
2593
2594 <row>
2595 <entry role="func_table_entry"><para role="func_signature">
2596 <indexterm>
2597 <primary>bit_length</primary>
2598 </indexterm>
2599 <function>bit_length</function> ( <type>text</type> )
2600 <returnvalue>integer</returnvalue>
2601 </para>
2602 <para>
2603 Returns number of bits in the string (8
2604 times the <function>octet_length</function>).
2605 </para>
2606 <para>
2607 <literal>bit_length('jose')</literal>
2608 <returnvalue>32</returnvalue>
2609 </para></entry>
2610 </row>
2611
2612 <row>
2613 <entry role="func_table_entry"><para role="func_signature">
2614 <indexterm>
2615 <primary>char_length</primary>
2616 </indexterm>
2617 <indexterm>
2618 <primary>character string</primary>
2619 <secondary>length</secondary>
2620 </indexterm>
2621 <indexterm>
2622 <primary>length</primary>
2623 <secondary sortas="character string">of a character string</secondary>
2624 <see>character string, length</see>
2625 </indexterm>
2626 <function>char_length</function> ( <type>text</type> )
2627 <returnvalue>integer</returnvalue>
2628 </para>
2629 <para role="func_signature">
2630 <indexterm>
2631 <primary>character_length</primary>
2632 </indexterm>
2633 <function>character_length</function> ( <type>text</type> )
2634 <returnvalue>integer</returnvalue>
2635 </para>
2636 <para>
2637 Returns number of characters in the string.
2638 </para>
2639 <para>
2640 <literal>char_length('jos&eacute;')</literal>
2641 <returnvalue>4</returnvalue>
2642 </para></entry>
2643 </row>
2644
2645 <row>
2646 <entry role="func_table_entry"><para role="func_signature">
2647 <indexterm id="function-lower">
2648 <primary>lower</primary>
2649 </indexterm>
2650 <function>lower</function> ( <type>text</type> )
2651 <returnvalue>text</returnvalue>
2652 </para>
2653 <para>
2654 Converts the string to all lower case, according to the rules of the
2655 database's locale.
2656 </para>
2657 <para>
2658 <literal>lower('TOM')</literal>
2659 <returnvalue>tom</returnvalue>
2660 </para></entry>
2661 </row>
2662
2663 <row>
2664 <entry role="func_table_entry"><para role="func_signature">
2665 <indexterm>
2666 <primary>lpad</primary>
2667 </indexterm>
2668 <function>lpad</function> ( <parameter>string</parameter> <type>text</type>,
2669 <parameter>length</parameter> <type>integer</type>
2670 <optional>, <parameter>fill</parameter> <type>text</type> </optional> )
2671 <returnvalue>text</returnvalue>
2672 </para>
2673 <para>
2674 Extends the <parameter>string</parameter> to length
2675 <parameter>length</parameter> by prepending the characters
2676 <parameter>fill</parameter> (a space by default). If the
2677 <parameter>string</parameter> is already longer than
2678 <parameter>length</parameter> then it is truncated (on the right).
2679 </para>
2680 <para>
2681 <literal>lpad('hi', 5, 'xy')</literal>
2682 <returnvalue>xyxhi</returnvalue>
2683 </para></entry>
2684 </row>
2685
2686 <row>
2687 <entry role="func_table_entry"><para role="func_signature">
2688 <indexterm>
2689 <primary>ltrim</primary>
2690 </indexterm>
2691 <function>ltrim</function> ( <parameter>string</parameter> <type>text</type>
2692 <optional>, <parameter>characters</parameter> <type>text</type> </optional> )
2693 <returnvalue>text</returnvalue>
2694 </para>
2695 <para>
2696 Removes the longest string containing only characters in
2697 <parameter>characters</parameter> (a space by default) from the start of
2698 <parameter>string</parameter>.
2699 </para>
2700 <para>
2701 <literal>ltrim('zzzytest', 'xyz')</literal>
2702 <returnvalue>test</returnvalue>
2703 </para></entry>
2704 </row>
2705
2706 <row>
2707 <entry role="func_table_entry"><para role="func_signature">
2708 <indexterm id="function-normalize">
2709 <primary>normalize</primary>
2710 </indexterm>
2711 <indexterm>
2712 <primary>Unicode normalization</primary>
2713 </indexterm>
2714 <function>normalize</function> ( <type>text</type>
2715 <optional>, <parameter>form</parameter> </optional> )
2716 <returnvalue>text</returnvalue>
2717 </para>
2718 <para>
2719 Converts the string to the specified Unicode
2720 normalization form. The optional <parameter>form</parameter> key word
2721 specifies the form: <literal>NFC</literal> (the default),
2722 <literal>NFD</literal>, <literal>NFKC</literal>, or
2723 <literal>NFKD</literal>. This function can only be used when the
2724 server encoding is <literal>UTF8</literal>.
2725 </para>
2726 <para>
2727 <literal>normalize(U&amp;'\0061\0308bc', NFC)</literal>
2728 <returnvalue>U&amp;'\00E4bc'</returnvalue>
2729 </para></entry>
2730 </row>
2731
2732 <row>
2733 <entry role="func_table_entry"><para role="func_signature">
2734 <indexterm>
2735 <primary>octet_length</primary>
2736 </indexterm>
2737 <function>octet_length</function> ( <type>text</type> )
2738 <returnvalue>integer</returnvalue>
2739 </para>
2740 <para>
2741 Returns number of bytes in the string.
2742 </para>
2743 <para>
2744 <literal>octet_length('jos&eacute;')</literal>
2745 <returnvalue>5</returnvalue> (if server encoding is UTF8)
2746 </para></entry>
2747 </row>
2748
2749 <row>
2750 <entry role="func_table_entry"><para role="func_signature">
2751 <indexterm>
2752 <primary>octet_length</primary>
2753 </indexterm>
2754 <function>octet_length</function> ( <type>character</type> )
2755 <returnvalue>integer</returnvalue>
2756 </para>
2757 <para>
2758 Returns number of bytes in the string. Since this version of the
2759 function accepts type <type>character</type> directly, it will not
2760 strip trailing spaces.
2761 </para>
2762 <para>
2763 <literal>octet_length('abc '::character(4))</literal>
2764 <returnvalue>4</returnvalue>
2765 </para></entry>
2766 </row>
2767
2768 <row>
2769 <entry role="func_table_entry"><para role="func_signature">
2770 <indexterm>
2771 <primary>overlay</primary>
2772 </indexterm>
2773 <function>overlay</function> ( <parameter>string</parameter> <type>text</type> <literal>PLACING</literal> <parameter>newsubstring</parameter> <type>text</type> <literal>FROM</literal> <parameter>start</parameter> <type>integer</type> <optional> <literal>FOR</literal> <parameter>count</parameter> <type>integer</type> </optional> )
2774 <returnvalue>text</returnvalue>
2775 </para>
2776 <para>
2777 Replaces the substring of <parameter>string</parameter> that starts at
2778 the <parameter>start</parameter>'th character and extends
2779 for <parameter>count</parameter> characters
2780 with <parameter>newsubstring</parameter>.
2781 If <parameter>count</parameter> is omitted, it defaults to the length
2782 of <parameter>newsubstring</parameter>.
2783 </para>
2784 <para>
2785 <literal>overlay('Txxxxas' placing 'hom' from 2 for 4)</literal>
2786 <returnvalue>Thomas</returnvalue>
2787 </para></entry>
2788 </row>
2789
2790 <row>
2791 <entry role="func_table_entry"><para role="func_signature">
2792 <indexterm>
2793 <primary>position</primary>
2794 </indexterm>
2795 <function>position</function> ( <parameter>substring</parameter> <type>text</type> <literal>IN</literal> <parameter>string</parameter> <type>text</type> )
2796 <returnvalue>integer</returnvalue>
2797 </para>
2798 <para>
2799 Returns first starting index of the specified
2800 <parameter>substring</parameter> within
2801 <parameter>string</parameter>, or zero if it's not present.
2802 </para>
2803 <para>
2804 <literal>position('om' in 'Thomas')</literal>
2805 <returnvalue>3</returnvalue>
2806 </para></entry>
2807 </row>
2808
2809 <row>
2810 <entry role="func_table_entry"><para role="func_signature">
2811 <indexterm>
2812 <primary>rpad</primary>
2813 </indexterm>
2814 <function>rpad</function> ( <parameter>string</parameter> <type>text</type>,
2815 <parameter>length</parameter> <type>integer</type>
2816 <optional>, <parameter>fill</parameter> <type>text</type> </optional> )
2817 <returnvalue>text</returnvalue>
2818 </para>
2819 <para>
2820 Extends the <parameter>string</parameter> to length
2821 <parameter>length</parameter> by appending the characters
2822 <parameter>fill</parameter> (a space by default). If the
2823 <parameter>string</parameter> is already longer than
2824 <parameter>length</parameter> then it is truncated.
2825 </para>
2826 <para>
2827 <literal>rpad('hi', 5, 'xy')</literal>
2828 <returnvalue>hixyx</returnvalue>
2829 </para></entry>
2830 </row>
2831
2832 <row>
2833 <entry role="func_table_entry"><para role="func_signature">
2834 <indexterm>
2835 <primary>rtrim</primary>
2836 </indexterm>
2837 <function>rtrim</function> ( <parameter>string</parameter> <type>text</type>
2838 <optional>, <parameter>characters</parameter> <type>text</type> </optional> )
2839 <returnvalue>text</returnvalue>
2840 </para>
2841 <para>
2842 Removes the longest string containing only characters in
2843 <parameter>characters</parameter> (a space by default) from the end of
2844 <parameter>string</parameter>.
2845 </para>
2846 <para>
2847 <literal>rtrim('testxxzx', 'xyz')</literal>
2848 <returnvalue>test</returnvalue>
2849 </para></entry>
2850 </row>
2851
2852 <row>
2853 <entry role="func_table_entry"><para role="func_signature">
2854 <indexterm>
2855 <primary>substring</primary>
2856 </indexterm>
2857 <function>substring</function> ( <parameter>string</parameter> <type>text</type> <optional> <literal>FROM</literal> <parameter>start</parameter> <type>integer</type> </optional> <optional> <literal>FOR</literal> <parameter>count</parameter> <type>integer</type> </optional> )
2858 <returnvalue>text</returnvalue>
2859 </para>
2860 <para>
2861 Extracts the substring of <parameter>string</parameter> starting at
2862 the <parameter>start</parameter>'th character if that is specified,
2863 and stopping after <parameter>count</parameter> characters if that is
2864 specified. Provide at least one of <parameter>start</parameter>
2865 and <parameter>count</parameter>.
2866 </para>
2867 <para>
2868 <literal>substring('Thomas' from 2 for 3)</literal>
2869 <returnvalue>hom</returnvalue>
2870 </para>
2871 <para>
2872 <literal>substring('Thomas' from 3)</literal>
2873 <returnvalue>omas</returnvalue>
2874 </para>
2875 <para>
2876 <literal>substring('Thomas' for 2)</literal>
2877 <returnvalue>Th</returnvalue>
2878 </para></entry>
2879 </row>
2880
2881 <row>
2882 <entry role="func_table_entry"><para role="func_signature">
2883 <function>substring</function> ( <parameter>string</parameter> <type>text</type> <literal>FROM</literal> <parameter>pattern</parameter> <type>text</type> )
2884 <returnvalue>text</returnvalue>
2885 </para>
2886 <para>
2887 Extracts the first substring matching POSIX regular expression; see
2888 <xref linkend="functions-posix-regexp"/>.
2889 </para>
2890 <para>
2891 <literal>substring('Thomas' from '...$')</literal>
2892 <returnvalue>mas</returnvalue>
2893 </para></entry>
2894 </row>
2895
2896 <row>
2897 <entry role="func_table_entry"><para role="func_signature">
2898 <function>substring</function> ( <parameter>string</parameter> <type>text</type> <literal>SIMILAR</literal> <parameter>pattern</parameter> <type>text</type> <literal>ESCAPE</literal> <parameter>escape</parameter> <type>text</type> )
2899 <returnvalue>text</returnvalue>
2900 </para>
2901 <para role="func_signature">
2902 <function>substring</function> ( <parameter>string</parameter> <type>text</type> <literal>FROM</literal> <parameter>pattern</parameter> <type>text</type> <literal>FOR</literal> <parameter>escape</parameter> <type>text</type> )
2903 <returnvalue>text</returnvalue>
2904 </para>
2905 <para>
2906 Extracts the first substring matching <acronym>SQL</acronym> regular expression;
2907 see <xref linkend="functions-similarto-regexp"/>. The first form has
2908 been specified since SQL:2003; the second form was only in SQL:1999
2909 and should be considered obsolete.
2910 </para>
2911 <para>
2912 <literal>substring('Thomas' similar '%#"o_a#"_' escape '#')</literal>
2913 <returnvalue>oma</returnvalue>
2914 </para></entry>
2915 </row>
2916
2917 <row>
2918 <entry role="func_table_entry"><para role="func_signature">
2919 <indexterm>
2920 <primary>trim</primary>
2921 </indexterm>
2922 <function>trim</function> ( <optional> <literal>LEADING</literal> | <literal>TRAILING</literal> | <literal>BOTH</literal> </optional>
2923 <optional> <parameter>characters</parameter> <type>text</type> </optional> <literal>FROM</literal>
2924 <parameter>string</parameter> <type>text</type> )
2925 <returnvalue>text</returnvalue>
2926 </para>
2927 <para>
2928 Removes the longest string containing only characters in
2929 <parameter>characters</parameter> (a space by default) from the
2930 start, end, or both ends (<literal>BOTH</literal> is the default)
2931 of <parameter>string</parameter>.
2932 </para>
2933 <para>
2934 <literal>trim(both 'xyz' from 'yxTomxx')</literal>
2935 <returnvalue>Tom</returnvalue>
2936 </para></entry>
2937 </row>
2938
2939 <row>
2940 <entry role="func_table_entry"><para role="func_signature">
2941 <function>trim</function> ( <optional> <literal>LEADING</literal> | <literal>TRAILING</literal> | <literal>BOTH</literal> </optional> <optional> <literal>FROM</literal> </optional>
2942 <parameter>string</parameter> <type>text</type> <optional>,
2943 <parameter>characters</parameter> <type>text</type> </optional> )
2944 <returnvalue>text</returnvalue>
2945 </para>
2946 <para>
2947 This is a non-standard syntax for <function>trim()</function>.
2948 </para>
2949 <para>
2950 <literal>trim(both from 'yxTomxx', 'xyz')</literal>
2951 <returnvalue>Tom</returnvalue>
2952 </para></entry>
2953 </row>
2954
2955 <row>
2956 <entry role="func_table_entry"><para role="func_signature">
2957 <indexterm>
2958 <primary>unicode_assigned</primary>
2959 </indexterm>
2960 <function>unicode_assigned</function> ( <type>text</type> )
2961 <returnvalue>boolean</returnvalue>
2962 </para>
2963 <para>
2964 Returns <literal>true</literal> if all characters in the string are
2965 assigned Unicode codepoints; <literal>false</literal> otherwise. This
2966 function can only be used when the server encoding is
2967 <literal>UTF8</literal>.
2968 </para></entry>
2969 </row>
2970
2971 <row>
2972 <entry role="func_table_entry"><para role="func_signature">
2973 <indexterm>
2974 <primary>upper</primary>
2975 </indexterm>
2976 <function>upper</function> ( <type>text</type> )
2977 <returnvalue>text</returnvalue>
2978 </para>
2979 <para>
2980 Converts the string to all upper case, according to the rules of the
2981 database's locale.
2982 </para>
2983 <para>
2984 <literal>upper('tom')</literal>
2985 <returnvalue>TOM</returnvalue>
2986 </para></entry>
2987 </row>
2988 </tbody>
2989 </tgroup>
2990 </table>
2991
2992 <para>
2993 Additional string manipulation functions and operators are available
2994 and are listed in <xref linkend="functions-string-other"/>. (Some of
2995 these are used internally to implement
2996 the <acronym>SQL</acronym>-standard string functions listed in
2997 <xref linkend="functions-string-sql"/>.)
2998 There are also pattern-matching operators, which are described in
2999 <xref linkend="functions-matching"/>, and operators for full-text
3000 search, which are described in <xref linkend="textsearch"/>.
3001 </para>
3002
3003 <table id="functions-string-other">
3004 <title>Other String Functions and Operators</title>
3005 <tgroup cols="1">
3006 <thead>
3007 <row>
3008 <entry role="func_table_entry"><para role="func_signature">
3009 Function/Operator
3010 </para>
3011 <para>
3012 Description
3013 </para>
3014 <para>
3015 Example(s)
3016 </para></entry>
3017 </row>
3018 </thead>
3019
3020 <tbody>
3021 <row>
3022 <entry role="func_table_entry"><para role="func_signature">
3023 <indexterm>
3024 <primary>character string</primary>
3025 <secondary>prefix test</secondary>
3026 </indexterm>
3027 <type>text</type> <literal>^@</literal> <type>text</type>
3028 <returnvalue>boolean</returnvalue>
3029 </para>
3030 <para>
3031 Returns true if the first string starts with the second string
3032 (equivalent to the <function>starts_with()</function> function).
3033 </para>
3034 <para>
3035 <literal>'alphabet' ^@ 'alph'</literal>
3036 <returnvalue>t</returnvalue>
3037 </para></entry>
3038 </row>
3039
3040 <row>
3041 <entry role="func_table_entry"><para role="func_signature">
3042 <indexterm>
3043 <primary>ascii</primary>
3044 </indexterm>
3045 <function>ascii</function> ( <type>text</type> )
3046 <returnvalue>integer</returnvalue>
3047 </para>
3048 <para>
3049 Returns the numeric code of the first character of the argument.
3050 In <acronym>UTF8</acronym> encoding, returns the Unicode code point
3051 of the character. In other multibyte encodings, the argument must
3052 be an <acronym>ASCII</acronym> character.
3053 </para>
3054 <para>
3055 <literal>ascii('x')</literal>
3056 <returnvalue>120</returnvalue>
3057 </para></entry>
3058 </row>
3059
3060 <row>
3061 <entry role="func_table_entry"><para role="func_signature">
3062 <indexterm>
3063 <primary>chr</primary>
3064 </indexterm>
3065 <function>chr</function> ( <type>integer</type> )
3066 <returnvalue>text</returnvalue>
3067 </para>
3068 <para>
3069 Returns the character with the given code. In <acronym>UTF8</acronym>
3070 encoding the argument is treated as a Unicode code point. In other
3071 multibyte encodings the argument must designate
3072 an <acronym>ASCII</acronym> character. <literal>chr(0)</literal> is
3073 disallowed because text data types cannot store that character.
3074 </para>
3075 <para>
3076 <literal>chr(65)</literal>
3077 <returnvalue>A</returnvalue>
3078 </para></entry>
3079 </row>
3080
3081 <row>
3082 <entry role="func_table_entry"><para role="func_signature">
3083 <indexterm>
3084 <primary>concat</primary>
3085 </indexterm>
3086 <function>concat</function> ( <parameter>val1</parameter> <type>"any"</type>
3087 <optional>, <parameter>val2</parameter> <type>"any"</type> <optional>, ...</optional> </optional> )
3088 <returnvalue>text</returnvalue>
3089 </para>
3090 <para>
3091 Concatenates the text representations of all the arguments.
3092 NULL arguments are ignored.
3093 </para>
3094 <para>
3095 <literal>concat('abcde', 2, NULL, 22)</literal>
3096 <returnvalue>abcde222</returnvalue>
3097 </para></entry>
3098 </row>
3099
3100 <row>
3101 <entry role="func_table_entry"><para role="func_signature">
3102 <indexterm>
3103 <primary>concat_ws</primary>
3104 </indexterm>
3105 <function>concat_ws</function> ( <parameter>sep</parameter> <type>text</type>,
3106 <parameter>val1</parameter> <type>"any"</type>
3107 <optional>, <parameter>val2</parameter> <type>"any"</type> <optional>, ...</optional> </optional> )
3108 <returnvalue>text</returnvalue>
3109 </para>
3110 <para>
3111 Concatenates all but the first argument, with separators. The first
3112 argument is used as the separator string, and should not be NULL.
3113 Other NULL arguments are ignored.
3114 </para>
3115 <para>
3116 <literal>concat_ws(',', 'abcde', 2, NULL, 22)</literal>
3117 <returnvalue>abcde,2,22</returnvalue>
3118 </para></entry>
3119 </row>
3120
3121 <row>
3122 <entry role="func_table_entry"><para role="func_signature">
3123 <indexterm>
3124 <primary>format</primary>
3125 </indexterm>
3126 <function>format</function> ( <parameter>formatstr</parameter> <type>text</type>
3127 <optional>, <parameter>formatarg</parameter> <type>"any"</type> <optional>, ...</optional> </optional> )
3128 <returnvalue>text</returnvalue>
3129 </para>
3130 <para>
3131 Formats arguments according to a format string;
3132 see <xref linkend="functions-string-format"/>.
3133 This function is similar to the C function <function>sprintf</function>.
3134 </para>
3135 <para>
3136 <literal>format('Hello %s, %1$s', 'World')</literal>
3137 <returnvalue>Hello World, World</returnvalue>
3138 </para></entry>
3139 </row>
3140
3141 <row>
3142 <entry role="func_table_entry"><para role="func_signature">
3143 <indexterm>
3144 <primary>initcap</primary>
3145 </indexterm>
3146 <function>initcap</function> ( <type>text</type> )
3147 <returnvalue>text</returnvalue>
3148 </para>
3149 <para>
3150 Converts the first letter of each word to upper case and the
3151 rest to lower case. Words are sequences of alphanumeric
3152 characters separated by non-alphanumeric characters.
3153 </para>
3154 <para>
3155 <literal>initcap('hi THOMAS')</literal>
3156 <returnvalue>Hi Thomas</returnvalue>
3157 </para></entry>
3158 </row>
3159
3160 <row>
3161 <entry role="func_table_entry"><para role="func_signature">
3162 <indexterm>
3163 <primary>casefold</primary>
3164 </indexterm>
3165 <function>casefold</function> ( <type>text</type> )
3166 <returnvalue>text</returnvalue>
3167 </para>
3168 <para>
3169 Performs case folding of the input string according to the collation.
3170 Case folding is similar to case conversion, but the purpose of case
3171 folding is to facilitate case-insensitive matching of strings,
3172 whereas the purpose of case conversion is to convert to a particular
3173 cased form. This function can only be used when the server encoding
3174 is <literal>UTF8</literal>.
3175 </para>
3176 <para>
3177 Ordinarily, case folding simply converts to lowercase, but there may
3178 be exceptions depending on the collation. For instance, some
3179 characters have more than two lowercase variants, or fold to uppercase.
3180 </para>
3181 <para>
3182 Case folding may change the length of the string. For instance, in
3183 the <literal>PG_UNICODE_FAST</literal> collation, <literal>ß</literal>
3184 (U+00DF) folds to <literal>ss</literal>.
3185 </para>
3186 <para>
3187 <function>casefold</function> can be used for Unicode Default Caseless
3188 Matching. It does not always preserve the normalized form of the
3189 input string (see <xref linkend="function-normalize"/>).
3190 </para>
3191 <para>
3192 The <literal>libc</literal> provider doesn't support case folding, so
3193 <function>casefold</function> is identical to <xref
3194 linkend="function-lower"/>.
3195 </para></entry>
3196 </row>
3197
3198 <row>
3199 <entry role="func_table_entry"><para role="func_signature">
3200 <indexterm>
3201 <primary>left</primary>
3202 </indexterm>
3203 <function>left</function> ( <parameter>string</parameter> <type>text</type>,
3204 <parameter>n</parameter> <type>integer</type> )
3205 <returnvalue>text</returnvalue>
3206 </para>
3207 <para>
3208 Returns first <parameter>n</parameter> characters in the
3209 string, or when <parameter>n</parameter> is negative, returns
3210 all but last |<parameter>n</parameter>| characters.
3211 </para>
3212 <para>
3213 <literal>left('abcde', 2)</literal>
3214 <returnvalue>ab</returnvalue>
3215 </para></entry>
3216 </row>
3217
3218 <row>
3219 <entry role="func_table_entry"><para role="func_signature">
3220 <indexterm>
3221 <primary>length</primary>
3222 </indexterm>
3223 <function>length</function> ( <type>text</type> )
3224 <returnvalue>integer</returnvalue>
3225 </para>
3226 <para>
3227 Returns the number of characters in the string.
3228 </para>
3229 <para>
3230 <literal>length('jose')</literal>
3231 <returnvalue>4</returnvalue>
3232 </para></entry>
3233 </row>
3234
3235 <row>
3236 <entry role="func_table_entry"><para role="func_signature">
3237 <indexterm>
3238 <primary>md5</primary>
3239 </indexterm>
3240 <function>md5</function> ( <type>text</type> )
3241 <returnvalue>text</returnvalue>
3242 </para>
3243 <para>
3244 Computes the MD5 <link linkend="functions-hash-note">hash</link> of
3245 the argument, with the result written in hexadecimal.
3246 </para>
3247 <para>
3248 <literal>md5('abc')</literal>
3249 <returnvalue>900150983cd24fb0&zwsp;d6963f7d28e17f72</returnvalue>
3250 </para></entry>
3251 </row>
3252
3253 <row>
3254 <entry role="func_table_entry"><para role="func_signature">
3255 <indexterm>
3256 <primary>parse_ident</primary>
3257 </indexterm>
3258 <function>parse_ident</function> ( <parameter>qualified_identifier</parameter> <type>text</type>
3259 <optional>, <parameter>strict_mode</parameter> <type>boolean</type> <literal>DEFAULT</literal> <literal>true</literal> </optional> )
3260 <returnvalue>text[]</returnvalue>
3261 </para>
3262 <para>
3263 Splits <parameter>qualified_identifier</parameter> into an array of
3264 identifiers, removing any quoting of individual identifiers. By
3265 default, extra characters after the last identifier are considered an
3266 error; but if the second parameter is <literal>false</literal>, then such
3267 extra characters are ignored. (This behavior is useful for parsing
3268 names for objects like functions.) Note that this function does not
3269 truncate over-length identifiers. If you want truncation you can cast
3270 the result to <type>name[]</type>.
3271 </para>
3272 <para>
3273 <literal>parse_ident('"SomeSchema".someTable')</literal>
3274 <returnvalue>{SomeSchema,sometable}</returnvalue>
3275 </para></entry>
3276 </row>
3277
3278 <row>
3279 <entry role="func_table_entry"><para role="func_signature">
3280 <indexterm>
3281 <primary>pg_client_encoding</primary>
3282 </indexterm>
3283 <function>pg_client_encoding</function> ( )
3284 <returnvalue>name</returnvalue>
3285 </para>
3286 <para>
3287 Returns current client encoding name.
3288 </para>
3289 <para>
3290 <literal>pg_client_encoding()</literal>
3291 <returnvalue>UTF8</returnvalue>
3292 </para></entry>
3293 </row>
3294
3295 <row>
3296 <entry role="func_table_entry"><para role="func_signature">
3297 <indexterm>
3298 <primary>quote_ident</primary>
3299 </indexterm>
3300 <function>quote_ident</function> ( <type>text</type> )
3301 <returnvalue>text</returnvalue>
3302 </para>
3303 <para>
3304 Returns the given string suitably quoted to be used as an identifier
3305 in an <acronym>SQL</acronym> statement string.
3306 Quotes are added only if necessary (i.e., if the string contains
3307 non-identifier characters or would be case-folded).
3308 Embedded quotes are properly doubled.
3309 See also <xref linkend="plpgsql-quote-literal-example"/>.
3310 </para>
3311 <para>
3312 <literal>quote_ident('Foo bar')</literal>
3313 <returnvalue>"Foo bar"</returnvalue>
3314 </para></entry>
3315 </row>
3316
3317 <row>
3318 <entry role="func_table_entry"><para role="func_signature">
3319 <indexterm>
3320 <primary>quote_literal</primary>
3321 </indexterm>
3322 <function>quote_literal</function> ( <type>text</type> )
3323 <returnvalue>text</returnvalue>
3324 </para>
3325 <para>
3326 Returns the given string suitably quoted to be used as a string literal
3327 in an <acronym>SQL</acronym> statement string.
3328 Embedded single-quotes and backslashes are properly doubled.
3329 Note that <function>quote_literal</function> returns null on null
3330 input; if the argument might be null,
3331 <function>quote_nullable</function> is often more suitable.
3332 See also <xref linkend="plpgsql-quote-literal-example"/>.
3333 </para>
3334 <para>
3335 <literal>quote_literal(E'O\'Reilly')</literal>
3336 <returnvalue>'O''Reilly'</returnvalue>
3337 </para></entry>
3338 </row>
3339
3340 <row>
3341 <entry role="func_table_entry"><para role="func_signature">
3342 <function>quote_literal</function> ( <type>anyelement</type> )
3343 <returnvalue>text</returnvalue>
3344 </para>
3345 <para>
3346 Converts the given value to text and then quotes it as a literal.
3347 Embedded single-quotes and backslashes are properly doubled.
3348 </para>
3349 <para>
3350 <literal>quote_literal(42.5)</literal>
3351 <returnvalue>'42.5'</returnvalue>
3352 </para></entry>
3353 </row>
3354
3355 <row>
3356 <entry role="func_table_entry"><para role="func_signature">
3357 <indexterm>
3358 <primary>quote_nullable</primary>
3359 </indexterm>
3360 <function>quote_nullable</function> ( <type>text</type> )
3361 <returnvalue>text</returnvalue>
3362 </para>
3363 <para>
3364 Returns the given string suitably quoted to be used as a string literal
3365 in an <acronym>SQL</acronym> statement string; or, if the argument
3366 is null, returns <literal>NULL</literal>.
3367 Embedded single-quotes and backslashes are properly doubled.
3368 See also <xref linkend="plpgsql-quote-literal-example"/>.
3369 </para>
3370 <para>
3371 <literal>quote_nullable(NULL)</literal>
3372 <returnvalue>NULL</returnvalue>
3373 </para></entry>
3374 </row>
3375
3376 <row>
3377 <entry role="func_table_entry"><para role="func_signature">
3378 <function>quote_nullable</function> ( <type>anyelement</type> )
3379 <returnvalue>text</returnvalue>
3380 </para>
3381 <para>
3382 Converts the given value to text and then quotes it as a literal;
3383 or, if the argument is null, returns <literal>NULL</literal>.
3384 Embedded single-quotes and backslashes are properly doubled.
3385 </para>
3386 <para>
3387 <literal>quote_nullable(42.5)</literal>
3388 <returnvalue>'42.5'</returnvalue>
3389 </para></entry>
3390 </row>
3391
3392 <row>
3393 <entry role="func_table_entry"><para role="func_signature">
3394 <indexterm>
3395 <primary>regexp_count</primary>
3396 </indexterm>
3397 <function>regexp_count</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type>
3398 <optional>, <parameter>start</parameter> <type>integer</type>
3399 <optional>, <parameter>flags</parameter> <type>text</type> </optional> </optional> )
3400 <returnvalue>integer</returnvalue>
3401 </para>
3402 <para>
3403 Returns the number of times the POSIX regular
3404 expression <parameter>pattern</parameter> matches in
3405 the <parameter>string</parameter>; see
3406 <xref linkend="functions-posix-regexp"/>.
3407 </para>
3408 <para>
3409 <literal>regexp_count('123456789012', '\d\d\d', 2)</literal>
3410 <returnvalue>3</returnvalue>
3411 </para></entry>
3412 </row>
3413
3414 <row>
3415 <entry role="func_table_entry"><para role="func_signature">
3416 <indexterm>
3417 <primary>regexp_instr</primary>
3418 </indexterm>
3419 <function>regexp_instr</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type>
3420 <optional>, <parameter>start</parameter> <type>integer</type>
3421 <optional>, <parameter>N</parameter> <type>integer</type>
3422 <optional>, <parameter>endoption</parameter> <type>integer</type>
3423 <optional>, <parameter>flags</parameter> <type>text</type>
3424 <optional>, <parameter>subexpr</parameter> <type>integer</type> </optional> </optional> </optional> </optional> </optional> )
3425 <returnvalue>integer</returnvalue>
3426 </para>
3427 <para>
3428 Returns the position within <parameter>string</parameter> where
3429 the <parameter>N</parameter>'th match of the POSIX regular
3430 expression <parameter>pattern</parameter> occurs, or zero if there is
3431 no such match; see <xref linkend="functions-posix-regexp"/>.
3432 </para>
3433 <para>
3434 <literal>regexp_instr('ABCDEF', 'c(.)(..)', 1, 1, 0, 'i')</literal>
3435 <returnvalue>3</returnvalue>
3436 </para>
3437 <para>
3438 <literal>regexp_instr('ABCDEF', 'c(.)(..)', 1, 1, 0, 'i', 2)</literal>
3439 <returnvalue>5</returnvalue>
3440 </para></entry>
3441 </row>
3442
3443 <row>
3444 <entry role="func_table_entry"><para role="func_signature">
3445 <indexterm>
3446 <primary>regexp_like</primary>
3447 </indexterm>
3448 <function>regexp_like</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type>
3449 <optional>, <parameter>flags</parameter> <type>text</type> </optional> )
3450 <returnvalue>boolean</returnvalue>
3451 </para>
3452 <para>
3453 Checks whether a match of the POSIX regular
3454 expression <parameter>pattern</parameter> occurs
3455 within <parameter>string</parameter>; see
3456 <xref linkend="functions-posix-regexp"/>.
3457 </para>
3458 <para>
3459 <literal>regexp_like('Hello World', 'world$', 'i')</literal>
3460 <returnvalue>t</returnvalue>
3461 </para></entry>
3462 </row>
3463
3464 <row>
3465 <entry role="func_table_entry"><para role="func_signature">
3466 <indexterm>
3467 <primary>regexp_match</primary>
3468 </indexterm>
3469 <function>regexp_match</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> <optional>, <parameter>flags</parameter> <type>text</type> </optional> )
3470 <returnvalue>text[]</returnvalue>
3471 </para>
3472 <para>
3473 Returns substrings within the first match of the POSIX regular
3474 expression <parameter>pattern</parameter> to
3475 the <parameter>string</parameter>; see
3476 <xref linkend="functions-posix-regexp"/>.
3477 </para>
3478 <para>
3479 <literal>regexp_match('foobarbequebaz', '(bar)(beque)')</literal>
3480 <returnvalue>{bar,beque}</returnvalue>
3481 </para></entry>
3482 </row>
3483
3484 <row>
3485 <entry role="func_table_entry"><para role="func_signature">
3486 <indexterm>
3487 <primary>regexp_matches</primary>
3488 </indexterm>
3489 <function>regexp_matches</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> <optional>, <parameter>flags</parameter> <type>text</type> </optional> )
3490 <returnvalue>setof text[]</returnvalue>
3491 </para>
3492 <para>
3493 Returns substrings within the first match of the POSIX regular
3494 expression <parameter>pattern</parameter> to
3495 the <parameter>string</parameter>, or substrings within all
3496 such matches if the <literal>g</literal> flag is used;
3497 see <xref linkend="functions-posix-regexp"/>.
3498 </para>
3499 <para>
3500 <literal>regexp_matches('foobarbequebaz', 'ba.', 'g')</literal>
3501 <returnvalue></returnvalue>
3502 <programlisting>
3503 {bar}
3504 {baz}
3505 </programlisting>
3506 </para></entry>
3507 </row>
3508
3509 <row>
3510 <entry role="func_table_entry"><para role="func_signature">
3511 <indexterm>
3512 <primary>regexp_replace</primary>
3513 </indexterm>
3514 <function>regexp_replace</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type>, <parameter>replacement</parameter> <type>text</type>
3515 <optional>, <parameter>flags</parameter> <type>text</type> </optional> )
3516 <returnvalue>text</returnvalue>
3517 </para>
3518 <para>
3519 Replaces the substring that is the first match to the POSIX
3520 regular expression <parameter>pattern</parameter>, or all such
3521 matches if the <literal>g</literal> flag is used; see
3522 <xref linkend="functions-posix-regexp"/>.
3523 </para>
3524 <para>
3525 <literal>regexp_replace('Thomas', '.[mN]a.', 'M')</literal>
3526 <returnvalue>ThM</returnvalue>
3527 </para></entry>
3528 </row>
3529
3530 <row>
3531 <entry role="func_table_entry"><para role="func_signature">
3532 <function>regexp_replace</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type>, <parameter>replacement</parameter> <type>text</type>,
3533 <parameter>start</parameter> <type>integer</type>
3534 <optional>, <parameter>N</parameter> <type>integer</type>
3535 <optional>, <parameter>flags</parameter> <type>text</type> </optional> </optional> )
3536 <returnvalue>text</returnvalue>
3537 </para>
3538 <para>
3539 Replaces the substring that is the <parameter>N</parameter>'th
3540 match to the POSIX regular expression <parameter>pattern</parameter>,
3541 or all such matches if <parameter>N</parameter> is zero, with the
3542 search beginning at the <parameter>start</parameter>'th character
3543 of <parameter>string</parameter>. If <parameter>N</parameter> is
3544 omitted, it defaults to 1. See
3545 <xref linkend="functions-posix-regexp"/>.
3546 </para>
3547 <para>
3548 <literal>regexp_replace('Thomas', '.', 'X', 3, 2)</literal>
3549 <returnvalue>ThoXas</returnvalue>
3550 </para>
3551 <para>
3552 <literal>regexp_replace(string=>'hello world', pattern=>'l', replacement=>'XX', start=>1, "N"=>2)</literal>
3553 <returnvalue>helXXo world</returnvalue>
3554 </para></entry>
3555 </row>
3556
3557 <row>
3558 <entry role="func_table_entry"><para role="func_signature">
3559 <indexterm>
3560 <primary>regexp_split_to_array</primary>
3561 </indexterm>
3562 <function>regexp_split_to_array</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> <optional>, <parameter>flags</parameter> <type>text</type> </optional> )
3563 <returnvalue>text[]</returnvalue>
3564 </para>
3565 <para>
3566 Splits <parameter>string</parameter> using a POSIX regular
3567 expression as the delimiter, producing an array of results; see
3568 <xref linkend="functions-posix-regexp"/>.
3569 </para>
3570 <para>
3571 <literal>regexp_split_to_array('hello world', '\s+')</literal>
3572 <returnvalue>{hello,world}</returnvalue>
3573 </para></entry>
3574 </row>
3575
3576 <row>
3577 <entry role="func_table_entry"><para role="func_signature">
3578 <indexterm>
3579 <primary>regexp_split_to_table</primary>
3580 </indexterm>
3581 <function>regexp_split_to_table</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type> <optional>, <parameter>flags</parameter> <type>text</type> </optional> )
3582 <returnvalue>setof text</returnvalue>
3583 </para>
3584 <para>
3585 Splits <parameter>string</parameter> using a POSIX regular
3586 expression as the delimiter, producing a set of results; see
3587 <xref linkend="functions-posix-regexp"/>.
3588 </para>
3589 <para>
3590 <literal>regexp_split_to_table('hello world', '\s+')</literal>
3591 <returnvalue></returnvalue>
3592 <programlisting>
3593 hello
3594 world
3595 </programlisting>
3596 </para></entry>
3597 </row>
3598
3599 <row>
3600 <entry role="func_table_entry"><para role="func_signature">
3601 <indexterm>
3602 <primary>regexp_substr</primary>
3603 </indexterm>
3604 <function>regexp_substr</function> ( <parameter>string</parameter> <type>text</type>, <parameter>pattern</parameter> <type>text</type>
3605 <optional>, <parameter>start</parameter> <type>integer</type>
3606 <optional>, <parameter>N</parameter> <type>integer</type>
3607 <optional>, <parameter>flags</parameter> <type>text</type>
3608 <optional>, <parameter>subexpr</parameter> <type>integer</type> </optional> </optional> </optional> </optional> )
3609 <returnvalue>text</returnvalue>
3610 </para>
3611 <para>
3612 Returns the substring within <parameter>string</parameter> that
3613 matches the <parameter>N</parameter>'th occurrence of the POSIX
3614 regular expression <parameter>pattern</parameter>,
3615 or <literal>NULL</literal> if there is no such match; see
3616 <xref linkend="functions-posix-regexp"/>.
3617 </para>
3618 <para>
3619 <literal>regexp_substr('ABCDEF', 'c(.)(..)', 1, 1, 'i')</literal>
3620 <returnvalue>CDEF</returnvalue>
3621 </para>
3622 <para>
3623 <literal>regexp_substr('ABCDEF', 'c(.)(..)', 1, 1, 'i', 2)</literal>
3624 <returnvalue>EF</returnvalue>
3625 </para></entry>
3626 </row>
3627
3628 <row>
3629 <entry role="func_table_entry"><para role="func_signature">
3630 <indexterm>
3631 <primary>repeat</primary>
3632 </indexterm>
3633 <function>repeat</function> ( <parameter>string</parameter> <type>text</type>, <parameter>number</parameter> <type>integer</type> )
3634 <returnvalue>text</returnvalue>
3635 </para>
3636 <para>
3637 Repeats <parameter>string</parameter> the specified
3638 <parameter>number</parameter> of times.
3639 </para>
3640 <para>
3641 <literal>repeat('Pg', 4)</literal>
3642 <returnvalue>PgPgPgPg</returnvalue>
3643 </para></entry>
3644 </row>
3645
3646 <row>
3647 <entry role="func_table_entry"><para role="func_signature">
3648 <indexterm>
3649 <primary>replace</primary>
3650 </indexterm>
3651 <function>replace</function> ( <parameter>string</parameter> <type>text</type>,
3652 <parameter>from</parameter> <type>text</type>,
3653 <parameter>to</parameter> <type>text</type> )
3654 <returnvalue>text</returnvalue>
3655 </para>
3656 <para>
3657 Replaces all occurrences in <parameter>string</parameter> of
3658 substring <parameter>from</parameter> with
3659 substring <parameter>to</parameter>.
3660 </para>
3661 <para>
3662 <literal>replace('abcdefabcdef', 'cd', 'XX')</literal>
3663 <returnvalue>abXXefabXXef</returnvalue>
3664 </para></entry>
3665 </row>
3666
3667 <row>
3668 <entry role="func_table_entry"><para role="func_signature">
3669 <indexterm>
3670 <primary>reverse</primary>
3671 </indexterm>
3672 <function>reverse</function> ( <type>text</type> )
3673 <returnvalue>text</returnvalue>
3674 </para>
3675 <para>
3676 Reverses the order of the characters in the string.
3677 </para>
3678 <para>
3679 <literal>reverse('abcde')</literal>
3680 <returnvalue>edcba</returnvalue>
3681 </para></entry>
3682 </row>
3683
3684 <row>
3685 <entry role="func_table_entry"><para role="func_signature">
3686 <indexterm>
3687 <primary>right</primary>
3688 </indexterm>
3689 <function>right</function> ( <parameter>string</parameter> <type>text</type>,
3690 <parameter>n</parameter> <type>integer</type> )
3691 <returnvalue>text</returnvalue>
3692 </para>
3693 <para>
3694 Returns last <parameter>n</parameter> characters in the string,
3695 or when <parameter>n</parameter> is negative, returns all but
3696 first |<parameter>n</parameter>| characters.
3697 </para>
3698 <para>
3699 <literal>right('abcde', 2)</literal>
3700 <returnvalue>de</returnvalue>
3701 </para></entry>
3702 </row>
3703
3704 <row>
3705 <entry role="func_table_entry"><para role="func_signature">
3706 <indexterm>
3707 <primary>split_part</primary>
3708 </indexterm>
3709 <function>split_part</function> ( <parameter>string</parameter> <type>text</type>,
3710 <parameter>delimiter</parameter> <type>text</type>,
3711 <parameter>n</parameter> <type>integer</type> )
3712 <returnvalue>text</returnvalue>
3713 </para>
3714 <para>
3715 Splits <parameter>string</parameter> at occurrences
3716 of <parameter>delimiter</parameter> and returns
3717 the <parameter>n</parameter>'th field (counting from one),
3718 or when <parameter>n</parameter> is negative, returns
3719 the |<parameter>n</parameter>|'th-from-last field.
3720 </para>
3721 <para>
3722 <literal>split_part('abc~@~def~@~ghi', '~@~', 2)</literal>
3723 <returnvalue>def</returnvalue>
3724 </para>
3725 <para>
3726 <literal>split_part('abc,def,ghi,jkl', ',', -2)</literal>
3727 <returnvalue>ghi</returnvalue>
3728 </para></entry>
3729 </row>
3730
3731 <row>
3732 <entry role="func_table_entry"><para role="func_signature">
3733 <indexterm>
3734 <primary>starts_with</primary>
3735 </indexterm>
3736 <function>starts_with</function> ( <parameter>string</parameter> <type>text</type>, <parameter>prefix</parameter> <type>text</type> )
3737 <returnvalue>boolean</returnvalue>
3738 </para>
3739 <para>
3740 Returns true if <parameter>string</parameter> starts
3741 with <parameter>prefix</parameter>.
3742 </para>
3743 <para>
3744 <literal>starts_with('alphabet', 'alph')</literal>
3745 <returnvalue>t</returnvalue>
3746 </para></entry>
3747 </row>
3748
3749 <row>
3750 <entry role="func_table_entry"><para role="func_signature">
3751 <indexterm id="function-string-to-array">
3752 <primary>string_to_array</primary>
3753 </indexterm>
3754 <function>string_to_array</function> ( <parameter>string</parameter> <type>text</type>, <parameter>delimiter</parameter> <type>text</type> <optional>, <parameter>null_string</parameter> <type>text</type> </optional> )
3755 <returnvalue>text[]</returnvalue>
3756 </para>
3757 <para>
3758 Splits the <parameter>string</parameter> at occurrences
3759 of <parameter>delimiter</parameter> and forms the resulting fields
3760 into a <type>text</type> array.
3761 If <parameter>delimiter</parameter> is <literal>NULL</literal>,
3762 each character in the <parameter>string</parameter> will become a
3763 separate element in the array.
3764 If <parameter>delimiter</parameter> is an empty string, then
3765 the <parameter>string</parameter> is treated as a single field.
3766 If <parameter>null_string</parameter> is supplied and is
3767 not <literal>NULL</literal>, fields matching that string are
3768 replaced by <literal>NULL</literal>.
3769 See also <link linkend="function-array-to-string"><function>array_to_string</function></link>.
3770 </para>
3771 <para>
3772 <literal>string_to_array('xx~~yy~~zz', '~~', 'yy')</literal>
3773 <returnvalue>{xx,NULL,zz}</returnvalue>
3774 </para></entry>
3775 </row>
3776
3777 <row>
3778 <entry role="func_table_entry"><para role="func_signature">
3779 <indexterm>
3780 <primary>string_to_table</primary>
3781 </indexterm>
3782 <function>string_to_table</function> ( <parameter>string</parameter> <type>text</type>, <parameter>delimiter</parameter> <type>text</type> <optional>, <parameter>null_string</parameter> <type>text</type> </optional> )
3783 <returnvalue>setof text</returnvalue>
3784 </para>
3785 <para>
3786 Splits the <parameter>string</parameter> at occurrences
3787 of <parameter>delimiter</parameter> and returns the resulting fields
3788 as a set of <type>text</type> rows.
3789 If <parameter>delimiter</parameter> is <literal>NULL</literal>,
3790 each character in the <parameter>string</parameter> will become a
3791 separate row of the result.
3792 If <parameter>delimiter</parameter> is an empty string, then
3793 the <parameter>string</parameter> is treated as a single field.
3794 If <parameter>null_string</parameter> is supplied and is
3795 not <literal>NULL</literal>, fields matching that string are
3796 replaced by <literal>NULL</literal>.
3797 </para>
3798 <para>
3799 <literal>string_to_table('xx~^~yy~^~zz', '~^~', 'yy')</literal>
3800 <returnvalue></returnvalue>
3801 <programlisting>
3802 xx
3803 NULL
3804 zz
3805 </programlisting>
3806 </para></entry>
3807 </row>
3808
3809 <row>
3810 <entry role="func_table_entry"><para role="func_signature">
3811 <indexterm>
3812 <primary>strpos</primary>
3813 </indexterm>
3814 <function>strpos</function> ( <parameter>string</parameter> <type>text</type>, <parameter>substring</parameter> <type>text</type> )
3815 <returnvalue>integer</returnvalue>
3816 </para>
3817 <para>
3818 Returns first starting index of the specified <parameter>substring</parameter>
3819 within <parameter>string</parameter>, or zero if it's not present.
3820 (Same as <literal>position(<parameter>substring</parameter> in
3821 <parameter>string</parameter>)</literal>, but note the reversed
3822 argument order.)
3823 </para>
3824 <para>
3825 <literal>strpos('high', 'ig')</literal>
3826 <returnvalue>2</returnvalue>
3827 </para></entry>
3828 </row>
3829
3830 <row>
3831 <entry role="func_table_entry"><para role="func_signature">
3832 <indexterm>
3833 <primary>substr</primary>
3834 </indexterm>
3835 <function>substr</function> ( <parameter>string</parameter> <type>text</type>, <parameter>start</parameter> <type>integer</type> <optional>, <parameter>count</parameter> <type>integer</type> </optional> )
3836 <returnvalue>text</returnvalue>
3837 </para>
3838 <para>
3839 Extracts the substring of <parameter>string</parameter> starting at
3840 the <parameter>start</parameter>'th character,
3841 and extending for <parameter>count</parameter> characters if that is
3842 specified. (Same
3843 as <literal>substring(<parameter>string</parameter>
3844 from <parameter>start</parameter>
3845 for <parameter>count</parameter>)</literal>.)
3846 </para>
3847 <para>
3848 <literal>substr('alphabet', 3)</literal>
3849 <returnvalue>phabet</returnvalue>
3850 </para>
3851 <para>
3852 <literal>substr('alphabet', 3, 2)</literal>
3853 <returnvalue>ph</returnvalue>
3854 </para></entry>
3855 </row>
3856
3857 <row>
3858 <entry role="func_table_entry"><para role="func_signature">
3859 <indexterm>
3860 <primary>to_ascii</primary>
3861 </indexterm>
3862 <function>to_ascii</function> ( <parameter>string</parameter> <type>text</type> )
3863 <returnvalue>text</returnvalue>
3864 </para>
3865 <para role="func_signature">
3866 <function>to_ascii</function> ( <parameter>string</parameter> <type>text</type>,
3867 <parameter>encoding</parameter> <type>name</type> )
3868 <returnvalue>text</returnvalue>
3869 </para>
3870 <para role="func_signature">
3871 <function>to_ascii</function> ( <parameter>string</parameter> <type>text</type>,
3872 <parameter>encoding</parameter> <type>integer</type> )
3873 <returnvalue>text</returnvalue>
3874 </para>
3875 <para>
3876 Converts <parameter>string</parameter> to <acronym>ASCII</acronym>
3877 from another encoding, which may be identified by name or number.
3878 If <parameter>encoding</parameter> is omitted the database encoding
3879 is assumed (which in practice is the only useful case).
3880 The conversion consists primarily of dropping accents.
3881 Conversion is only supported
3882 from <literal>LATIN1</literal>, <literal>LATIN2</literal>,
3883 <literal>LATIN9</literal>, and <literal>WIN1250</literal> encodings.
3884 (See the <xref linkend="unaccent"/> module for another, more flexible
3885 solution.)
3886 </para>
3887 <para>
3888 <literal>to_ascii('Kar&eacute;l')</literal>
3889 <returnvalue>Karel</returnvalue>
3890 </para></entry>
3891 </row>
3892
3893 <row>
3894 <entry role="func_table_entry"><para role="func_signature">
3895 <indexterm>
3896 <primary>to_bin</primary>
3897 </indexterm>
3898 <function>to_bin</function> ( <type>integer</type> )
3899 <returnvalue>text</returnvalue>
3900 </para>
3901 <para role="func_signature">
3902 <function>to_bin</function> ( <type>bigint</type> )
3903 <returnvalue>text</returnvalue>
3904 </para>
3905 <para>
3906 Converts the number to its equivalent two's complement binary
3907 representation.
3908 </para>
3909 <para>
3910 <literal>to_bin(2147483647)</literal>
3911 <returnvalue>1111111111111111111111111111111</returnvalue>
3912 </para>
3913 <para>
3914 <literal>to_bin(-1234)</literal>
3915 <returnvalue>11111111111111111111101100101110</returnvalue>
3916 </para></entry>
3917 </row>
3918
3919 <row>
3920 <entry role="func_table_entry"><para role="func_signature">
3921 <indexterm>
3922 <primary>to_hex</primary>
3923 </indexterm>
3924 <function>to_hex</function> ( <type>integer</type> )
3925 <returnvalue>text</returnvalue>
3926 </para>
3927 <para role="func_signature">
3928 <function>to_hex</function> ( <type>bigint</type> )
3929 <returnvalue>text</returnvalue>
3930 </para>
3931 <para>
3932 Converts the number to its equivalent two's complement hexadecimal
3933 representation.
3934 </para>
3935 <para>
3936 <literal>to_hex(2147483647)</literal>
3937 <returnvalue>7fffffff</returnvalue>
3938 </para>
3939 <para>
3940 <literal>to_hex(-1234)</literal>
3941 <returnvalue>fffffb2e</returnvalue>
3942 </para></entry>
3943 </row>
3944
3945 <row>
3946 <entry role="func_table_entry"><para role="func_signature">
3947 <indexterm>
3948 <primary>to_oct</primary>
3949 </indexterm>
3950 <function>to_oct</function> ( <type>integer</type> )
3951 <returnvalue>text</returnvalue>
3952 </para>
3953 <para role="func_signature">
3954 <function>to_oct</function> ( <type>bigint</type> )
3955 <returnvalue>text</returnvalue>
3956 </para>
3957 <para>
3958 Converts the number to its equivalent two's complement octal
3959 representation.
3960 </para>
3961 <para>
3962 <literal>to_oct(2147483647)</literal>
3963 <returnvalue>17777777777</returnvalue>
3964 </para>
3965 <para>
3966 <literal>to_oct(-1234)</literal>
3967 <returnvalue>37777775456</returnvalue>
3968 </para></entry>
3969 </row>
3970
3971 <row>
3972 <entry role="func_table_entry"><para role="func_signature">
3973 <indexterm>
3974 <primary>translate</primary>
3975 </indexterm>
3976 <function>translate</function> ( <parameter>string</parameter> <type>text</type>,
3977 <parameter>from</parameter> <type>text</type>,
3978 <parameter>to</parameter> <type>text</type> )
3979 <returnvalue>text</returnvalue>
3980 </para>
3981 <para>
3982 Replaces each character in <parameter>string</parameter> that
3983 matches a character in the <parameter>from</parameter> set with the
3984 corresponding character in the <parameter>to</parameter>
3985 set. If <parameter>from</parameter> is longer than
3986 <parameter>to</parameter>, occurrences of the extra characters in
3987 <parameter>from</parameter> are deleted.
3988 </para>
3989 <para>
3990 <literal>translate('12345', '143', 'ax')</literal>
3991 <returnvalue>a2x5</returnvalue>
3992 </para></entry>
3993 </row>
3994
3995 <row>
3996 <entry role="func_table_entry"><para role="func_signature">
3997 <indexterm>
3998 <primary>unistr</primary>
3999 </indexterm>
4000 <function>unistr</function> ( <type>text</type> )
4001 <returnvalue>text</returnvalue>
4002 </para>
4003 <para>
4004 Evaluate escaped Unicode characters in the argument. Unicode characters
4005 can be specified as
4006 <literal>\<replaceable>XXXX</replaceable></literal> (4 hexadecimal
4007 digits), <literal>\+<replaceable>XXXXXX</replaceable></literal> (6
4008 hexadecimal digits),
4009 <literal>\u<replaceable>XXXX</replaceable></literal> (4 hexadecimal
4010 digits), or <literal>\U<replaceable>XXXXXXXX</replaceable></literal>
4011 (8 hexadecimal digits). To specify a backslash, write two
4012 backslashes. All other characters are taken literally.
4013 </para>
4014
4015 <para>
4016 If the server encoding is not UTF-8, the Unicode code point identified
4017 by one of these escape sequences is converted to the actual server
4018 encoding; an error is reported if that's not possible.
4019 </para>
4020
4021 <para>
4022 This function provides a (non-standard) alternative to string
4023 constants with Unicode escapes (see <xref
4024 linkend="sql-syntax-strings-uescape"/>).
4025 </para>
4026
4027 <para>
4028 <literal>unistr('d\0061t\+000061')</literal>
4029 <returnvalue>data</returnvalue>
4030 </para>
4031 <para>
4032 <literal>unistr('d\u0061t\U00000061')</literal>
4033 <returnvalue>data</returnvalue>
4034 </para></entry>
4035 </row>
4036
4037 </tbody>
4038 </tgroup>
4039 </table>
4040
4041 <para>
4042 The <function>concat</function>, <function>concat_ws</function> and
4043 <function>format</function> functions are variadic, so it is possible to
4044 pass the values to be concatenated or formatted as an array marked with
4045 the <literal>VARIADIC</literal> keyword (see <xref
4046 linkend="xfunc-sql-variadic-functions"/>). The array's elements are
4047 treated as if they were separate ordinary arguments to the function.
4048 If the variadic array argument is NULL, <function>concat</function>
4049 and <function>concat_ws</function> return NULL, but
4050 <function>format</function> treats a NULL as a zero-element array.
4051 </para>
4052
4053 <para>
4054 See also the aggregate function <function>string_agg</function> in
4055 <xref linkend="functions-aggregate"/>, and the functions for
4056 converting between strings and the <type>bytea</type> type in
4057 <xref linkend="functions-binarystring-conversions"/>.
4058 </para>
4059
4060 <sect2 id="functions-string-format">
4061 <title><function>format</function></title>
4062
4063 <indexterm>
4064 <primary>format</primary>
4065 </indexterm>
4066
4067 <para>
4068 The function <function>format</function> produces output formatted according to
4069 a format string, in a style similar to the C function
4070 <function>sprintf</function>.
4071 </para>
4072
4073 <para>
4074 <synopsis>
4075 <function>format</function>(<parameter>formatstr</parameter> <type>text</type> <optional>, <parameter>formatarg</parameter> <type>"any"</type> <optional>, ...</optional> </optional>)
4076 </synopsis>
4077 <parameter>formatstr</parameter> is a format string that specifies how the
4078 result should be formatted. Text in the format string is copied
4079 directly to the result, except where <firstterm>format specifiers</firstterm> are
4080 used. Format specifiers act as placeholders in the string, defining how
4081 subsequent function arguments should be formatted and inserted into the
4082 result. Each <parameter>formatarg</parameter> argument is converted to text
4083 according to the usual output rules for its data type, and then formatted
4084 and inserted into the result string according to the format specifier(s).
4085 </para>
4086
4087 <para>
4088 Format specifiers are introduced by a <literal>%</literal> character and have
4089 the form
4090 <synopsis>
4091 %[<parameter>position</parameter>][<parameter>flags</parameter>][<parameter>width</parameter>]<parameter>type</parameter>
4092 </synopsis>
4093 where the component fields are:
4094
4095 <variablelist>
4096 <varlistentry>
4097 <term><parameter>position</parameter> (optional)</term>
4098 <listitem>
4099 <para>
4100 A string of the form <literal><parameter>n</parameter>$</literal> where
4101 <parameter>n</parameter> is the index of the argument to print.
4102 Index 1 means the first argument after
4103 <parameter>formatstr</parameter>. If the <parameter>position</parameter> is
4104 omitted, the default is to use the next argument in sequence.
4105 </para>
4106 </listitem>
4107 </varlistentry>
4108
4109 <varlistentry>
4110 <term><parameter>flags</parameter> (optional)</term>
4111 <listitem>
4112 <para>
4113 Additional options controlling how the format specifier's output is
4114 formatted. Currently the only supported flag is a minus sign
4115 (<literal>-</literal>) which will cause the format specifier's output to be
4116 left-justified. This has no effect unless the <parameter>width</parameter>
4117 field is also specified.
4118 </para>
4119 </listitem>
4120 </varlistentry>
4121
4122 <varlistentry>
4123 <term><parameter>width</parameter> (optional)</term>
4124 <listitem>
4125 <para>
4126 Specifies the <emphasis>minimum</emphasis> number of characters to use to
4127 display the format specifier's output. The output is padded on the
4128 left or right (depending on the <literal>-</literal> flag) with spaces as
4129 needed to fill the width. A too-small width does not cause
4130 truncation of the output, but is simply ignored. The width may be
4131 specified using any of the following: a positive integer; an
4132 asterisk (<literal>*</literal>) to use the next function argument as the
4133 width; or a string of the form <literal>*<parameter>n</parameter>$</literal> to
4134 use the <parameter>n</parameter>th function argument as the width.
4135 </para>
4136
4137 <para>
4138 If the width comes from a function argument, that argument is
4139 consumed before the argument that is used for the format specifier's
4140 value. If the width argument is negative, the result is left
4141 aligned (as if the <literal>-</literal> flag had been specified) within a
4142 field of length <function>abs</function>(<parameter>width</parameter>).
4143 </para>
4144 </listitem>
4145 </varlistentry>
4146
4147 <varlistentry>
4148 <term><parameter>type</parameter> (required)</term>
4149 <listitem>
4150 <para>
4151 The type of format conversion to use to produce the format
4152 specifier's output. The following types are supported:
4153 <itemizedlist>
4154 <listitem>
4155 <para>
4156 <literal>s</literal> formats the argument value as a simple
4157 string. A null value is treated as an empty string.
4158 </para>
4159 </listitem>
4160 <listitem>
4161 <para>
4162 <literal>I</literal> treats the argument value as an SQL
4163 identifier, double-quoting it if necessary.
4164 It is an error for the value to be null (equivalent to
4165 <function>quote_ident</function>).
4166 </para>
4167 </listitem>
4168 <listitem>
4169 <para>
4170 <literal>L</literal> quotes the argument value as an SQL literal.
4171 A null value is displayed as the string <literal>NULL</literal>, without
4172 quotes (equivalent to <function>quote_nullable</function>).
4173 </para>
4174 </listitem>
4175 </itemizedlist>
4176 </para>
4177 </listitem>
4178 </varlistentry>
4179 </variablelist>
4180 </para>
4181
4182 <para>
4183 In addition to the format specifiers described above, the special sequence
4184 <literal>%%</literal> may be used to output a literal <literal>%</literal> character.
4185 </para>
4186
4187 <para>
4188 Here are some examples of the basic format conversions:
4189
4190 <screen>
4191 SELECT format('Hello %s', 'World');
4192 <lineannotation>Result: </lineannotation><computeroutput>Hello World</computeroutput>
4193
4194 SELECT format('Testing %s, %s, %s, %%', 'one', 'two', 'three');
4195 <lineannotation>Result: </lineannotation><computeroutput>Testing one, two, three, %</computeroutput>
4196
4197 SELECT format('INSERT INTO %I VALUES(%L)', 'Foo bar', E'O\'Reilly');
4198 <lineannotation>Result: </lineannotation><computeroutput>INSERT INTO "Foo bar" VALUES('O''Reilly')</computeroutput>
4199
4200 SELECT format('INSERT INTO %I VALUES(%L)', 'locations', 'C:\Program Files');
4201 <lineannotation>Result: </lineannotation><computeroutput>INSERT INTO locations VALUES('C:\Program Files')</computeroutput>
4202 </screen>
4203 </para>
4204
4205 <para>
4206 Here are examples using <parameter>width</parameter> fields
4207 and the <literal>-</literal> flag:
4208
4209 <screen>
4210 SELECT format('|%10s|', 'foo');
4211 <lineannotation>Result: </lineannotation><computeroutput>| foo|</computeroutput>
4212
4213 SELECT format('|%-10s|', 'foo');
4214 <lineannotation>Result: </lineannotation><computeroutput>|foo |</computeroutput>
4215
4216 SELECT format('|%*s|', 10, 'foo');
4217 <lineannotation>Result: </lineannotation><computeroutput>| foo|</computeroutput>
4218
4219 SELECT format('|%*s|', -10, 'foo');
4220 <lineannotation>Result: </lineannotation><computeroutput>|foo |</computeroutput>
4221
4222 SELECT format('|%-*s|', 10, 'foo');
4223 <lineannotation>Result: </lineannotation><computeroutput>|foo |</computeroutput>
4224
4225 SELECT format('|%-*s|', -10, 'foo');
4226 <lineannotation>Result: </lineannotation><computeroutput>|foo |</computeroutput>
4227 </screen>
4228 </para>
4229
4230 <para>
4231 These examples show use of <parameter>position</parameter> fields:
4232
4233 <screen>
4234 SELECT format('Testing %3$s, %2$s, %1$s', 'one', 'two', 'three');
4235 <lineannotation>Result: </lineannotation><computeroutput>Testing three, two, one</computeroutput>
4236
4237 SELECT format('|%*2$s|', 'foo', 10, 'bar');
4238 <lineannotation>Result: </lineannotation><computeroutput>| bar|</computeroutput>
4239
4240 SELECT format('|%1$*2$s|', 'foo', 10, 'bar');
4241 <lineannotation>Result: </lineannotation><computeroutput>| foo|</computeroutput>
4242 </screen>
4243 </para>
4244
4245 <para>
4246 Unlike the standard C function <function>sprintf</function>,
4247 <productname>PostgreSQL</productname>'s <function>format</function> function allows format
4248 specifiers with and without <parameter>position</parameter> fields to be mixed
4249 in the same format string. A format specifier without a
4250 <parameter>position</parameter> field always uses the next argument after the
4251 last argument consumed.
4252 In addition, the <function>format</function> function does not require all
4253 function arguments to be used in the format string.
4254 For example:
4255
4256 <screen>
4257 SELECT format('Testing %3$s, %2$s, %s', 'one', 'two', 'three');
4258 <lineannotation>Result: </lineannotation><computeroutput>Testing three, two, three</computeroutput>
4259 </screen>
4260 </para>
4261
4262 <para>
4263 The <literal>%I</literal> and <literal>%L</literal> format specifiers are particularly
4264 useful for safely constructing dynamic SQL statements. See
4265 <xref linkend="plpgsql-quote-literal-example"/>.
4266 </para>
4267 </sect2>
4268
4269 </sect1>
4270
4271
4272 <sect1 id="functions-binarystring">
4273 <title>Binary String Functions and Operators</title>
4274
4275 <indexterm zone="functions-binarystring">
4276 <primary>binary data</primary>
4277 <secondary>functions</secondary>
4278 </indexterm>
4279
4280 <para>
4281 This section describes functions and operators for examining and
4282 manipulating binary strings, that is values of type <type>bytea</type>.
4283 Many of these are equivalent, in purpose and syntax, to the
4284 text-string functions described in the previous section.
4285 </para>
4286
4287 <para>
4288 <acronym>SQL</acronym> defines some string functions that use
4289 key words, rather than commas, to separate
4290 arguments. Details are in
4291 <xref linkend="functions-binarystring-sql"/>.
4292 <productname>PostgreSQL</productname> also provides versions of these functions
4293 that use the regular function invocation syntax
4294 (see <xref linkend="functions-binarystring-other"/>).
4295 </para>
4296
4297 <table id="functions-binarystring-sql">
4298 <title><acronym>SQL</acronym> Binary String Functions and Operators</title>
4299 <tgroup cols="1">
4300 <thead>
4301 <row>
4302 <entry role="func_table_entry"><para role="func_signature">
4303 Function/Operator
4304 </para>
4305 <para>
4306 Description
4307 </para>
4308 <para>
4309 Example(s)
4310 </para></entry>
4311 </row>
4312 </thead>
4313
4314 <tbody>
4315 <row>
4316 <entry role="func_table_entry"><para role="func_signature">
4317 <indexterm>
4318 <primary>binary string</primary>
4319 <secondary>concatenation</secondary>
4320 </indexterm>
4321 <type>bytea</type> <literal>||</literal> <type>bytea</type>
4322 <returnvalue>bytea</returnvalue>
4323 </para>
4324 <para>
4325 Concatenates the two binary strings.
4326 </para>
4327 <para>
4328 <literal>'\x123456'::bytea || '\x789a00bcde'::bytea</literal>
4329 <returnvalue>\x123456789a00bcde</returnvalue>
4330 </para></entry>
4331 </row>
4332
4333 <row>
4334 <entry role="func_table_entry"><para role="func_signature">
4335 <indexterm>
4336 <primary>bit_length</primary>
4337 </indexterm>
4338 <function>bit_length</function> ( <type>bytea</type> )
4339 <returnvalue>integer</returnvalue>
4340 </para>
4341 <para>
4342 Returns number of bits in the binary string (8
4343 times the <function>octet_length</function>).
4344 </para>
4345 <para>
4346 <literal>bit_length('\x123456'::bytea)</literal>
4347 <returnvalue>24</returnvalue>
4348 </para></entry>
4349 </row>
4350
4351 <row>
4352 <entry role="func_table_entry"><para role="func_signature">
4353 <indexterm>
4354 <primary>btrim</primary>
4355 </indexterm>
4356 <function>btrim</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4357 <parameter>bytesremoved</parameter> <type>bytea</type> )
4358 <returnvalue>bytea</returnvalue>
4359 </para>
4360 <para>
4361 Removes the longest string containing only bytes appearing in
4362 <parameter>bytesremoved</parameter> from the start and end of
4363 <parameter>bytes</parameter>.
4364 </para>
4365 <para>
4366 <literal>btrim('\x1234567890'::bytea, '\x9012'::bytea)</literal>
4367 <returnvalue>\x345678</returnvalue>
4368 </para></entry>
4369 </row>
4370
4371 <row>
4372 <entry role="func_table_entry"><para role="func_signature">
4373 <indexterm>
4374 <primary>ltrim</primary>
4375 </indexterm>
4376 <function>ltrim</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4377 <parameter>bytesremoved</parameter> <type>bytea</type> )
4378 <returnvalue>bytea</returnvalue>
4379 </para>
4380 <para>
4381 Removes the longest string containing only bytes appearing in
4382 <parameter>bytesremoved</parameter> from the start of
4383 <parameter>bytes</parameter>.
4384 </para>
4385 <para>
4386 <literal>ltrim('\x1234567890'::bytea, '\x9012'::bytea)</literal>
4387 <returnvalue>\x34567890</returnvalue>
4388 </para></entry>
4389 </row>
4390
4391 <row>
4392 <entry role="func_table_entry"><para role="func_signature">
4393 <indexterm>
4394 <primary>octet_length</primary>
4395 </indexterm>
4396 <function>octet_length</function> ( <type>bytea</type> )
4397 <returnvalue>integer</returnvalue>
4398 </para>
4399 <para>
4400 Returns number of bytes in the binary string.
4401 </para>
4402 <para>
4403 <literal>octet_length('\x123456'::bytea)</literal>
4404 <returnvalue>3</returnvalue>
4405 </para></entry>
4406 </row>
4407
4408 <row>
4409 <entry role="func_table_entry"><para role="func_signature">
4410 <indexterm>
4411 <primary>overlay</primary>
4412 </indexterm>
4413 <function>overlay</function> ( <parameter>bytes</parameter> <type>bytea</type> <literal>PLACING</literal> <parameter>newsubstring</parameter> <type>bytea</type> <literal>FROM</literal> <parameter>start</parameter> <type>integer</type> <optional> <literal>FOR</literal> <parameter>count</parameter> <type>integer</type> </optional> )
4414 <returnvalue>bytea</returnvalue>
4415 </para>
4416 <para>
4417 Replaces the substring of <parameter>bytes</parameter> that starts at
4418 the <parameter>start</parameter>'th byte and extends
4419 for <parameter>count</parameter> bytes
4420 with <parameter>newsubstring</parameter>.
4421 If <parameter>count</parameter> is omitted, it defaults to the length
4422 of <parameter>newsubstring</parameter>.
4423 </para>
4424 <para>
4425 <literal>overlay('\x1234567890'::bytea placing '\002\003'::bytea from 2 for 3)</literal>
4426 <returnvalue>\x12020390</returnvalue>
4427 </para></entry>
4428 </row>
4429
4430 <row>
4431 <entry role="func_table_entry"><para role="func_signature">
4432 <indexterm>
4433 <primary>position</primary>
4434 </indexterm>
4435 <function>position</function> ( <parameter>substring</parameter> <type>bytea</type> <literal>IN</literal> <parameter>bytes</parameter> <type>bytea</type> )
4436 <returnvalue>integer</returnvalue>
4437 </para>
4438 <para>
4439 Returns first starting index of the specified
4440 <parameter>substring</parameter> within
4441 <parameter>bytes</parameter>, or zero if it's not present.
4442 </para>
4443 <para>
4444 <literal>position('\x5678'::bytea in '\x1234567890'::bytea)</literal>
4445 <returnvalue>3</returnvalue>
4446 </para></entry>
4447 </row>
4448
4449 <row>
4450 <entry role="func_table_entry"><para role="func_signature">
4451 <indexterm>
4452 <primary>rtrim</primary>
4453 </indexterm>
4454 <function>rtrim</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4455 <parameter>bytesremoved</parameter> <type>bytea</type> )
4456 <returnvalue>bytea</returnvalue>
4457 </para>
4458 <para>
4459 Removes the longest string containing only bytes appearing in
4460 <parameter>bytesremoved</parameter> from the end of
4461 <parameter>bytes</parameter>.
4462 </para>
4463 <para>
4464 <literal>rtrim('\x1234567890'::bytea, '\x9012'::bytea)</literal>
4465 <returnvalue>\x12345678</returnvalue>
4466 </para></entry>
4467 </row>
4468
4469 <row>
4470 <entry role="func_table_entry"><para role="func_signature">
4471 <indexterm>
4472 <primary>substring</primary>
4473 </indexterm>
4474 <function>substring</function> ( <parameter>bytes</parameter> <type>bytea</type> <optional> <literal>FROM</literal> <parameter>start</parameter> <type>integer</type> </optional> <optional> <literal>FOR</literal> <parameter>count</parameter> <type>integer</type> </optional> )
4475 <returnvalue>bytea</returnvalue>
4476 </para>
4477 <para>
4478 Extracts the substring of <parameter>bytes</parameter> starting at
4479 the <parameter>start</parameter>'th byte if that is specified,
4480 and stopping after <parameter>count</parameter> bytes if that is
4481 specified. Provide at least one of <parameter>start</parameter>
4482 and <parameter>count</parameter>.
4483 </para>
4484 <para>
4485 <literal>substring('\x1234567890'::bytea from 3 for 2)</literal>
4486 <returnvalue>\x5678</returnvalue>
4487 </para></entry>
4488 </row>
4489
4490 <row>
4491 <entry role="func_table_entry"><para role="func_signature">
4492 <indexterm>
4493 <primary>trim</primary>
4494 </indexterm>
4495 <function>trim</function> ( <optional> <literal>LEADING</literal> | <literal>TRAILING</literal> | <literal>BOTH</literal> </optional>
4496 <parameter>bytesremoved</parameter> <type>bytea</type> <literal>FROM</literal>
4497 <parameter>bytes</parameter> <type>bytea</type> )
4498 <returnvalue>bytea</returnvalue>
4499 </para>
4500 <para>
4501 Removes the longest string containing only bytes appearing in
4502 <parameter>bytesremoved</parameter> from the start,
4503 end, or both ends (<literal>BOTH</literal> is the default)
4504 of <parameter>bytes</parameter>.
4505 </para>
4506 <para>
4507 <literal>trim('\x9012'::bytea from '\x1234567890'::bytea)</literal>
4508 <returnvalue>\x345678</returnvalue>
4509 </para></entry>
4510 </row>
4511
4512 <row>
4513 <entry role="func_table_entry"><para role="func_signature">
4514 <function>trim</function> ( <optional> <literal>LEADING</literal> | <literal>TRAILING</literal> | <literal>BOTH</literal> </optional> <optional> <literal>FROM</literal> </optional>
4515 <parameter>bytes</parameter> <type>bytea</type>,
4516 <parameter>bytesremoved</parameter> <type>bytea</type> )
4517 <returnvalue>bytea</returnvalue>
4518 </para>
4519 <para>
4520 This is a non-standard syntax for <function>trim()</function>.
4521 </para>
4522 <para>
4523 <literal>trim(both from '\x1234567890'::bytea, '\x9012'::bytea)</literal>
4524 <returnvalue>\x345678</returnvalue>
4525 </para></entry>
4526 </row>
4527 </tbody>
4528 </tgroup>
4529 </table>
4530
4531 <para>
4532 Additional binary string manipulation functions are available and
4533 are listed in <xref linkend="functions-binarystring-other"/>. Some
4534 of them are used internally to implement the
4535 <acronym>SQL</acronym>-standard string functions listed in <xref
4536 linkend="functions-binarystring-sql"/>.
4537 </para>
4538
4539 <table id="functions-binarystring-other">
4540 <title>Other Binary String Functions</title>
4541 <tgroup cols="1">
4542 <thead>
4543 <row>
4544 <entry role="func_table_entry"><para role="func_signature">
4545 Function
4546 </para>
4547 <para>
4548 Description
4549 </para>
4550 <para>
4551 Example(s)
4552 </para></entry>
4553 </row>
4554 </thead>
4555
4556 <tbody>
4557 <row>
4558 <entry role="func_table_entry"><para role="func_signature">
4559 <indexterm>
4560 <primary>bit_count</primary>
4561 </indexterm>
4562 <indexterm>
4563 <primary>popcount</primary>
4564 <see>bit_count</see>
4565 </indexterm>
4566 <function>bit_count</function> ( <parameter>bytes</parameter> <type>bytea</type> )
4567 <returnvalue>bigint</returnvalue>
4568 </para>
4569 <para>
4570 Returns the number of bits set in the binary string (also known as
4571 <quote>popcount</quote>).
4572 </para>
4573 <para>
4574 <literal>bit_count('\x1234567890'::bytea)</literal>
4575 <returnvalue>15</returnvalue>
4576 </para></entry>
4577 </row>
4578
4579 <row>
4580 <entry role="func_table_entry"><para role="func_signature">
4581 <indexterm>
4582 <primary>crc32</primary>
4583 </indexterm>
4584 <function>crc32</function> ( <type>bytea</type> )
4585 <returnvalue>bigint</returnvalue>
4586 </para>
4587 <para>
4588 Computes the CRC-32 value of the binary string.
4589 </para>
4590 <para>
4591 <literal>crc32('abc'::bytea)</literal>
4592 <returnvalue>891568578</returnvalue>
4593 </para></entry>
4594 </row>
4595
4596 <row>
4597 <entry role="func_table_entry"><para role="func_signature">
4598 <indexterm>
4599 <primary>crc32c</primary>
4600 </indexterm>
4601 <function>crc32c</function> ( <type>bytea</type> )
4602 <returnvalue>bigint</returnvalue>
4603 </para>
4604 <para>
4605 Computes the CRC-32C value of the binary string.
4606 </para>
4607 <para>
4608 <literal>crc32c('abc'::bytea)</literal>
4609 <returnvalue>910901175</returnvalue>
4610 </para></entry>
4611 </row>
4612
4613 <row>
4614 <entry role="func_table_entry"><para role="func_signature">
4615 <indexterm>
4616 <primary>get_bit</primary>
4617 </indexterm>
4618 <function>get_bit</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4619 <parameter>n</parameter> <type>bigint</type> )
4620 <returnvalue>integer</returnvalue>
4621 </para>
4622 <para>
4623 Extracts <link linkend="functions-zerobased-note">n'th</link> bit
4624 from binary string.
4625 </para>
4626 <para>
4627 <literal>get_bit('\x1234567890'::bytea, 30)</literal>
4628 <returnvalue>1</returnvalue>
4629 </para></entry>
4630 </row>
4631
4632 <row>
4633 <entry role="func_table_entry"><para role="func_signature">
4634 <indexterm>
4635 <primary>get_byte</primary>
4636 </indexterm>
4637 <function>get_byte</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4638 <parameter>n</parameter> <type>integer</type> )
4639 <returnvalue>integer</returnvalue>
4640 </para>
4641 <para>
4642 Extracts <link linkend="functions-zerobased-note">n'th</link> byte
4643 from binary string.
4644 </para>
4645 <para>
4646 <literal>get_byte('\x1234567890'::bytea, 4)</literal>
4647 <returnvalue>144</returnvalue>
4648 </para></entry>
4649 </row>
4650
4651 <row>
4652 <entry role="func_table_entry"><para role="func_signature">
4653 <indexterm>
4654 <primary>length</primary>
4655 </indexterm>
4656 <indexterm>
4657 <primary>binary string</primary>
4658 <secondary>length</secondary>
4659 </indexterm>
4660 <indexterm>
4661 <primary>length</primary>
4662 <secondary sortas="binary string">of a binary string</secondary>
4663 <see>binary strings, length</see>
4664 </indexterm>
4665 <function>length</function> ( <type>bytea</type> )
4666 <returnvalue>integer</returnvalue>
4667 </para>
4668 <para>
4669 Returns the number of bytes in the binary string.
4670 </para>
4671 <para>
4672 <literal>length('\x1234567890'::bytea)</literal>
4673 <returnvalue>5</returnvalue>
4674 </para></entry>
4675 </row>
4676
4677 <row>
4678 <entry role="func_table_entry"><para role="func_signature">
4679 <function>length</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4680 <parameter>encoding</parameter> <type>name</type> )
4681 <returnvalue>integer</returnvalue>
4682 </para>
4683 <para>
4684 Returns the number of characters in the binary string, assuming
4685 that it is text in the given <parameter>encoding</parameter>.
4686 </para>
4687 <para>
4688 <literal>length('jose'::bytea, 'UTF8')</literal>
4689 <returnvalue>4</returnvalue>
4690 </para></entry>
4691 </row>
4692
4693 <row>
4694 <entry role="func_table_entry"><para role="func_signature">
4695 <indexterm>
4696 <primary>md5</primary>
4697 </indexterm>
4698 <function>md5</function> ( <type>bytea</type> )
4699 <returnvalue>text</returnvalue>
4700 </para>
4701 <para>
4702 Computes the MD5 <link linkend="functions-hash-note">hash</link> of
4703 the binary string, with the result written in hexadecimal.
4704 </para>
4705 <para>
4706 <literal>md5('Th\000omas'::bytea)</literal>
4707 <returnvalue>8ab2d3c9689aaf18&zwsp;b4958c334c82d8b1</returnvalue>
4708 </para></entry>
4709 </row>
4710
4711 <row>
4712 <entry role="func_table_entry"><para role="func_signature">
4713 <indexterm>
4714 <primary>reverse</primary>
4715 </indexterm>
4716 <function>reverse</function> ( <type>bytea</type> )
4717 <returnvalue>bytea</returnvalue>
4718 </para>
4719 <para>
4720 Reverses the order of the bytes in the binary string.
4721 </para>
4722 <para>
4723 <literal>reverse('\xabcd'::bytea)</literal>
4724 <returnvalue>\xcdab</returnvalue>
4725 </para></entry>
4726 </row>
4727
4728 <row>
4729 <entry role="func_table_entry"><para role="func_signature">
4730 <indexterm>
4731 <primary>set_bit</primary>
4732 </indexterm>
4733 <function>set_bit</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4734 <parameter>n</parameter> <type>bigint</type>,
4735 <parameter>newvalue</parameter> <type>integer</type> )
4736 <returnvalue>bytea</returnvalue>
4737 </para>
4738 <para>
4739 Sets <link linkend="functions-zerobased-note">n'th</link> bit in
4740 binary string to <parameter>newvalue</parameter>.
4741 </para>
4742 <para>
4743 <literal>set_bit('\x1234567890'::bytea, 30, 0)</literal>
4744 <returnvalue>\x1234563890</returnvalue>
4745 </para></entry>
4746 </row>
4747
4748 <row>
4749 <entry role="func_table_entry"><para role="func_signature">
4750 <indexterm>
4751 <primary>set_byte</primary>
4752 </indexterm>
4753 <function>set_byte</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4754 <parameter>n</parameter> <type>integer</type>,
4755 <parameter>newvalue</parameter> <type>integer</type> )
4756 <returnvalue>bytea</returnvalue>
4757 </para>
4758 <para>
4759 Sets <link linkend="functions-zerobased-note">n'th</link> byte in
4760 binary string to <parameter>newvalue</parameter>.
4761 </para>
4762 <para>
4763 <literal>set_byte('\x1234567890'::bytea, 4, 64)</literal>
4764 <returnvalue>\x1234567840</returnvalue>
4765 </para></entry>
4766 </row>
4767
4768 <row>
4769 <entry role="func_table_entry"><para role="func_signature">
4770 <indexterm>
4771 <primary>sha224</primary>
4772 </indexterm>
4773 <function>sha224</function> ( <type>bytea</type> )
4774 <returnvalue>bytea</returnvalue>
4775 </para>
4776 <para>
4777 Computes the SHA-224 <link linkend="functions-hash-note">hash</link>
4778 of the binary string.
4779 </para>
4780 <para>
4781 <literal>sha224('abc'::bytea)</literal>
4782 <returnvalue>\x23097d223405d8228642a477bda2&zwsp;55b32aadbce4bda0b3f7e36c9da7</returnvalue>
4783 </para></entry>
4784 </row>
4785
4786 <row>
4787 <entry role="func_table_entry"><para role="func_signature">
4788 <indexterm>
4789 <primary>sha256</primary>
4790 </indexterm>
4791 <function>sha256</function> ( <type>bytea</type> )
4792 <returnvalue>bytea</returnvalue>
4793 </para>
4794 <para>
4795 Computes the SHA-256 <link linkend="functions-hash-note">hash</link>
4796 of the binary string.
4797 </para>
4798 <para>
4799 <literal>sha256('abc'::bytea)</literal>
4800 <returnvalue>\xba7816bf8f01cfea414140de5dae2223&zwsp;b00361a396177a9cb410ff61f20015ad</returnvalue>
4801 </para></entry>
4802 </row>
4803
4804 <row>
4805 <entry role="func_table_entry"><para role="func_signature">
4806 <indexterm>
4807 <primary>sha384</primary>
4808 </indexterm>
4809 <function>sha384</function> ( <type>bytea</type> )
4810 <returnvalue>bytea</returnvalue>
4811 </para>
4812 <para>
4813 Computes the SHA-384 <link linkend="functions-hash-note">hash</link>
4814 of the binary string.
4815 </para>
4816 <para>
4817 <literal>sha384('abc'::bytea)</literal>
4818 <returnvalue>\xcb00753f45a35e8bb5a03d699ac65007&zwsp;272c32ab0eded1631a8b605a43ff5bed&zwsp;8086072ba1e7cc2358baeca134c825a7</returnvalue>
4819 </para></entry>
4820 </row>
4821
4822 <row>
4823 <entry role="func_table_entry"><para role="func_signature">
4824 <indexterm>
4825 <primary>sha512</primary>
4826 </indexterm>
4827 <function>sha512</function> ( <type>bytea</type> )
4828 <returnvalue>bytea</returnvalue>
4829 </para>
4830 <para>
4831 Computes the SHA-512 <link linkend="functions-hash-note">hash</link>
4832 of the binary string.
4833 </para>
4834 <para>
4835 <literal>sha512('abc'::bytea)</literal>
4836 <returnvalue>\xddaf35a193617abacc417349ae204131&zwsp;12e6fa4e89a97ea20a9eeee64b55d39a&zwsp;2192992a274fc1a836ba3c23a3feebbd&zwsp;454d4423643ce80e2a9ac94fa54ca49f</returnvalue>
4837 </para></entry>
4838 </row>
4839
4840 <row>
4841 <entry role="func_table_entry"><para role="func_signature">
4842 <indexterm>
4843 <primary>substr</primary>
4844 </indexterm>
4845 <function>substr</function> ( <parameter>bytes</parameter> <type>bytea</type>, <parameter>start</parameter> <type>integer</type> <optional>, <parameter>count</parameter> <type>integer</type> </optional> )
4846 <returnvalue>bytea</returnvalue>
4847 </para>
4848 <para>
4849 Extracts the substring of <parameter>bytes</parameter> starting at
4850 the <parameter>start</parameter>'th byte,
4851 and extending for <parameter>count</parameter> bytes if that is
4852 specified. (Same
4853 as <literal>substring(<parameter>bytes</parameter>
4854 from <parameter>start</parameter>
4855 for <parameter>count</parameter>)</literal>.)
4856 </para>
4857 <para>
4858 <literal>substr('\x1234567890'::bytea, 3, 2)</literal>
4859 <returnvalue>\x5678</returnvalue>
4860 </para></entry>
4861 </row>
4862 </tbody>
4863 </tgroup>
4864 </table>
4865
4866 <para id="functions-zerobased-note">
4867 Functions <function>get_byte</function> and <function>set_byte</function>
4868 number the first byte of a binary string as byte 0.
4869 Functions <function>get_bit</function> and <function>set_bit</function>
4870 number bits from the right within each byte; for example bit 0 is the least
4871 significant bit of the first byte, and bit 15 is the most significant bit
4872 of the second byte.
4873 </para>
4874
4875 <para id="functions-hash-note">
4876 For historical reasons, the function <function>md5</function>
4877 returns a hex-encoded value of type <type>text</type> whereas the SHA-2
4878 functions return type <type>bytea</type>. Use the functions
4879 <link linkend="function-encode"><function>encode</function></link>
4880 and <link linkend="function-decode"><function>decode</function></link> to
4881 convert between the two. For example write <literal>encode(sha256('abc'),
4882 'hex')</literal> to get a hex-encoded text representation,
4883 or <literal>decode(md5('abc'), 'hex')</literal> to get
4884 a <type>bytea</type> value.
4885 </para>
4886
4887 <para>
4888 <indexterm>
4889 <primary>character string</primary>
4890 <secondary>converting to binary string</secondary>
4891 </indexterm>
4892 <indexterm>
4893 <primary>binary string</primary>
4894 <secondary>converting to character string</secondary>
4895 </indexterm>
4896 Functions for converting strings between different character sets
4897 (encodings), and for representing arbitrary binary data in textual
4898 form, are shown in
4899 <xref linkend="functions-binarystring-conversions"/>. For these
4900 functions, an argument or result of type <type>text</type> is expressed
4901 in the database's default encoding, while arguments or results of
4902 type <type>bytea</type> are in an encoding named by another argument.
4903 </para>
4904
4905 <table id="functions-binarystring-conversions">
4906 <title>Text/Binary String Conversion Functions</title>
4907 <tgroup cols="1">
4908 <thead>
4909 <row>
4910 <entry role="func_table_entry"><para role="func_signature">
4911 Function
4912 </para>
4913 <para>
4914 Description
4915 </para>
4916 <para>
4917 Example(s)
4918 </para></entry>
4919 </row>
4920 </thead>
4921
4922 <tbody>
4923 <row>
4924 <entry role="func_table_entry"><para role="func_signature">
4925 <indexterm>
4926 <primary>convert</primary>
4927 </indexterm>
4928 <function>convert</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4929 <parameter>src_encoding</parameter> <type>name</type>,
4930 <parameter>dest_encoding</parameter> <type>name</type> )
4931 <returnvalue>bytea</returnvalue>
4932 </para>
4933 <para>
4934 Converts a binary string representing text in
4935 encoding <parameter>src_encoding</parameter>
4936 to a binary string in encoding <parameter>dest_encoding</parameter>
4937 (see <xref linkend="multibyte-conversions-supported"/> for
4938 available conversions).
4939 </para>
4940 <para>
4941 <literal>convert('text_in_utf8', 'UTF8', 'LATIN1')</literal>
4942 <returnvalue>\x746578745f696e5f75746638</returnvalue>
4943 </para></entry>
4944 </row>
4945
4946 <row>
4947 <entry role="func_table_entry"><para role="func_signature">
4948 <indexterm>
4949 <primary>convert_from</primary>
4950 </indexterm>
4951 <function>convert_from</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4952 <parameter>src_encoding</parameter> <type>name</type> )
4953 <returnvalue>text</returnvalue>
4954 </para>
4955 <para>
4956 Converts a binary string representing text in
4957 encoding <parameter>src_encoding</parameter>
4958 to <type>text</type> in the database encoding
4959 (see <xref linkend="multibyte-conversions-supported"/> for
4960 available conversions).
4961 </para>
4962 <para>
4963 <literal>convert_from('text_in_utf8', 'UTF8')</literal>
4964 <returnvalue>text_in_utf8</returnvalue>
4965 </para></entry>
4966 </row>
4967
4968 <row>
4969 <entry role="func_table_entry"><para role="func_signature">
4970 <indexterm>
4971 <primary>convert_to</primary>
4972 </indexterm>
4973 <function>convert_to</function> ( <parameter>string</parameter> <type>text</type>,
4974 <parameter>dest_encoding</parameter> <type>name</type> )
4975 <returnvalue>bytea</returnvalue>
4976 </para>
4977 <para>
4978 Converts a <type>text</type> string (in the database encoding) to a
4979 binary string encoded in encoding <parameter>dest_encoding</parameter>
4980 (see <xref linkend="multibyte-conversions-supported"/> for
4981 available conversions).
4982 </para>
4983 <para>
4984 <literal>convert_to('some_text', 'UTF8')</literal>
4985 <returnvalue>\x736f6d655f74657874</returnvalue>
4986 </para></entry>
4987 </row>
4988
4989 <row>
4990 <entry role="func_table_entry"><para role="func_signature">
4991 <indexterm id="function-encode">
4992 <primary>encode</primary>
4993 </indexterm>
4994 <function>encode</function> ( <parameter>bytes</parameter> <type>bytea</type>,
4995 <parameter>format</parameter> <type>text</type> )
4996 <returnvalue>text</returnvalue>
4997 </para>
4998 <para>
4999 Encodes binary data into a textual representation; supported
5000 <parameter>format</parameter> values are:
5001 <link linkend="encode-format-base64"><literal>base64</literal></link>,
5002 <link linkend="encode-format-escape"><literal>escape</literal></link>,
5003 <link linkend="encode-format-hex"><literal>hex</literal></link>.
5004 </para>
5005 <para>
5006 <literal>encode('123\000\001', 'base64')</literal>
5007 <returnvalue>MTIzAAE=</returnvalue>
5008 </para></entry>
5009 </row>
5010
5011 <row>
5012 <entry role="func_table_entry"><para role="func_signature">
5013 <indexterm id="function-decode">
5014 <primary>decode</primary>
5015 </indexterm>
5016 <function>decode</function> ( <parameter>string</parameter> <type>text</type>,
5017 <parameter>format</parameter> <type>text</type> )
5018 <returnvalue>bytea</returnvalue>
5019 </para>
5020 <para>
5021 Decodes binary data from a textual representation; supported
5022 <parameter>format</parameter> values are the same as
5023 for <function>encode</function>.
5024 </para>
5025 <para>
5026 <literal>decode('MTIzAAE=', 'base64')</literal>
5027 <returnvalue>\x3132330001</returnvalue>
5028 </para></entry>
5029 </row>
5030 </tbody>
5031 </tgroup>
5032 </table>
5033
5034 <para>
5035 The <function>encode</function> and <function>decode</function>
5036 functions support the following textual formats:
5037
5038 <variablelist>
5039 <varlistentry id="encode-format-base64">
5040 <term>base64
5041 <indexterm>
5042 <primary>base64 format</primary>
5043 </indexterm></term>
5044 <listitem>
5045 <para>
5046 The <literal>base64</literal> format is that
5047 of <ulink url="https://datatracker.ietf.org/doc/html/rfc2045#section-6.8">RFC
5048 2045 Section 6.8</ulink>. As per the <acronym>RFC</acronym>, encoded lines are
5049 broken at 76 characters. However instead of the MIME CRLF
5050 end-of-line marker, only a newline is used for end-of-line.
5051 The <function>decode</function> function ignores carriage-return,
5052 newline, space, and tab characters. Otherwise, an error is
5053 raised when <function>decode</function> is supplied invalid
5054 base64 data &mdash; including when trailing padding is incorrect.
5055 </para>
5056 </listitem>
5057 </varlistentry>
5058
5059 <varlistentry id="encode-format-escape">
5060 <term>escape
5061 <indexterm>
5062 <primary>escape format</primary>
5063 </indexterm></term>
5064 <listitem>
5065 <para>
5066 The <literal>escape</literal> format converts zero bytes and
5067 bytes with the high bit set into octal escape sequences
5068 (<literal>\</literal><replaceable>nnn</replaceable>), and it doubles
5069 backslashes. Other byte values are represented literally.
5070 The <function>decode</function> function will raise an error if a
5071 backslash is not followed by either a second backslash or three
5072 octal digits; it accepts other byte values unchanged.
5073 </para>
5074 </listitem>
5075 </varlistentry>
5076
5077 <varlistentry id="encode-format-hex">
5078 <term>hex
5079 <indexterm>
5080 <primary>hex format</primary>
5081 </indexterm></term>
5082 <listitem>
5083 <para>
5084 The <literal>hex</literal> format represents each 4 bits of
5085 data as one hexadecimal digit, <literal>0</literal>
5086 through <literal>f</literal>, writing the higher-order digit of
5087 each byte first. The <function>encode</function> function outputs
5088 the <literal>a</literal>-<literal>f</literal> hex digits in lower
5089 case. Because the smallest unit of data is 8 bits, there are
5090 always an even number of characters returned
5091 by <function>encode</function>.
5092 The <function>decode</function> function
5093 accepts the <literal>a</literal>-<literal>f</literal> characters in
5094 either upper or lower case. An error is raised
5095 when <function>decode</function> is given invalid hex data
5096 &mdash; including when given an odd number of characters.
5097 </para>
5098 </listitem>
5099 </varlistentry>
5100 </variablelist>
5101 </para>
5102
5103 <para>
5104 In addition, it is possible to cast integral values to and from type
5105 <type>bytea</type>. Casting an integer to <type>bytea</type> produces
5106 2, 4, or 8 bytes, depending on the width of the integer type. The result
5107 is the two's complement representation of the integer, with the most
5108 significant byte first. Some examples:
5109 <programlisting>
5110 1234::smallint::bytea <lineannotation>\x04d2</lineannotation>
5111 cast(1234 as bytea) <lineannotation>\x000004d2</lineannotation>
5112 cast(-1234 as bytea) <lineannotation>\xfffffb2e</lineannotation>
5113 '\x8000'::bytea::smallint <lineannotation>-32768</lineannotation>
5114 '\x8000'::bytea::integer <lineannotation>32768</lineannotation>
5115 </programlisting>
5116 Casting a <type>bytea</type> to an integer will raise an error if the
5117 length of the <type>bytea</type> exceeds the width of the integer type.
5118 </para>
5119
5120 <para>
5121 See also the aggregate function <function>string_agg</function> in
5122 <xref linkend="functions-aggregate"/> and the large object functions
5123 in <xref linkend="lo-funcs"/>.
5124 </para>
5125 </sect1>
5126
5127
5128 <sect1 id="functions-bitstring">
5129 <title>Bit String Functions and Operators</title>
5130
5131 <indexterm zone="functions-bitstring">
5132 <primary>bit strings</primary>
5133 <secondary>functions</secondary>
5134 </indexterm>
5135
5136 <para>
5137 This section describes functions and operators for examining and
5138 manipulating bit strings, that is values of the types
5139 <type>bit</type> and <type>bit varying</type>. (While only
5140 type <type>bit</type> is mentioned in these tables, values of
5141 type <type>bit varying</type> can be used interchangeably.)
5142 Bit strings support the usual comparison operators shown in
5143 <xref linkend="functions-comparison-op-table"/>, as well as the
5144 operators shown in <xref linkend="functions-bit-string-op-table"/>.
5145 </para>
5146
5147 <table id="functions-bit-string-op-table">
5148 <title>Bit String Operators</title>
5149 <tgroup cols="1">
5150 <thead>
5151 <row>
5152 <entry role="func_table_entry"><para role="func_signature">
5153 Operator
5154 </para>
5155 <para>
5156 Description
5157 </para>
5158 <para>
5159 Example(s)
5160 </para></entry>
5161 </row>
5162 </thead>
5163
5164 <tbody>
5165 <row>
5166 <entry role="func_table_entry"><para role="func_signature">
5167 <type>bit</type> <literal>||</literal> <type>bit</type>
5168 <returnvalue>bit</returnvalue>
5169 </para>
5170 <para>
5171 Concatenation
5172 </para>
5173 <para>
5174 <literal>B'10001' || B'011'</literal>
5175 <returnvalue>10001011</returnvalue>
5176 </para></entry>
5177 </row>
5178
5179 <row>
5180 <entry role="func_table_entry"><para role="func_signature">
5181 <type>bit</type> <literal>&amp;</literal> <type>bit</type>
5182 <returnvalue>bit</returnvalue>
5183 </para>
5184 <para>
5185 Bitwise AND (inputs must be of equal length)
5186 </para>
5187 <para>
5188 <literal>B'10001' &amp; B'01101'</literal>
5189 <returnvalue>00001</returnvalue>
5190 </para></entry>
5191 </row>
5192
5193 <row>
5194 <entry role="func_table_entry"><para role="func_signature">
5195 <type>bit</type> <literal>|</literal> <type>bit</type>
5196 <returnvalue>bit</returnvalue>
5197 </para>
5198 <para>
5199 Bitwise OR (inputs must be of equal length)
5200 </para>
5201 <para>
5202 <literal>B'10001' | B'01101'</literal>
5203 <returnvalue>11101</returnvalue>
5204 </para></entry>
5205 </row>
5206
5207 <row>
5208 <entry role="func_table_entry"><para role="func_signature">
5209 <type>bit</type> <literal>#</literal> <type>bit</type>
5210 <returnvalue>bit</returnvalue>
5211 </para>
5212 <para>
5213 Bitwise exclusive OR (inputs must be of equal length)
5214 </para>
5215 <para>
5216 <literal>B'10001' # B'01101'</literal>
5217 <returnvalue>11100</returnvalue>
5218 </para></entry>
5219 </row>
5220
5221 <row>
5222 <entry role="func_table_entry"><para role="func_signature">
5223 <literal>~</literal> <type>bit</type>
5224 <returnvalue>bit</returnvalue>
5225 </para>
5226 <para>
5227 Bitwise NOT
5228 </para>
5229 <para>
5230 <literal>~ B'10001'</literal>
5231 <returnvalue>01110</returnvalue>
5232 </para></entry>
5233 </row>
5234
5235 <row>
5236 <entry role="func_table_entry"><para role="func_signature">
5237 <type>bit</type> <literal>&lt;&lt;</literal> <type>integer</type>
5238 <returnvalue>bit</returnvalue>
5239 </para>
5240 <para>
5241 Bitwise shift left
5242 (string length is preserved)
5243 </para>
5244 <para>
5245 <literal>B'10001' &lt;&lt; 3</literal>
5246 <returnvalue>01000</returnvalue>
5247 </para></entry>
5248 </row>
5249
5250 <row>
5251 <entry role="func_table_entry"><para role="func_signature">
5252 <type>bit</type> <literal>&gt;&gt;</literal> <type>integer</type>
5253 <returnvalue>bit</returnvalue>
5254 </para>
5255 <para>
5256 Bitwise shift right
5257 (string length is preserved)
5258 </para>
5259 <para>
5260 <literal>B'10001' &gt;&gt; 2</literal>
5261 <returnvalue>00100</returnvalue>
5262 </para></entry>
5263 </row>
5264 </tbody>
5265 </tgroup>
5266 </table>
5267
5268 <para>
5269 Some of the functions available for binary strings are also available
5270 for bit strings, as shown in <xref linkend="functions-bit-string-table"/>.
5271 </para>
5272
5273 <table id="functions-bit-string-table">
5274 <title>Bit String Functions</title>
5275 <tgroup cols="1">
5276 <thead>
5277 <row>
5278 <entry role="func_table_entry"><para role="func_signature">
5279 Function
5280 </para>
5281 <para>
5282 Description
5283 </para>
5284 <para>
5285 Example(s)
5286 </para></entry>
5287 </row>
5288 </thead>
5289
5290 <tbody>
5291 <row>
5292 <entry role="func_table_entry"><para role="func_signature">
5293 <indexterm>
5294 <primary>bit_count</primary>
5295 </indexterm>
5296 <function>bit_count</function> ( <type>bit</type> )
5297 <returnvalue>bigint</returnvalue>
5298 </para>
5299 <para>
5300 Returns the number of bits set in the bit string (also known as
5301 <quote>popcount</quote>).
5302 </para>
5303 <para>
5304 <literal>bit_count(B'10111')</literal>
5305 <returnvalue>4</returnvalue>
5306 </para></entry>
5307 </row>
5308
5309 <row>
5310 <entry role="func_table_entry"><para role="func_signature">
5311 <indexterm>
5312 <primary>bit_length</primary>
5313 </indexterm>
5314 <function>bit_length</function> ( <type>bit</type> )
5315 <returnvalue>integer</returnvalue>
5316 </para>
5317 <para>
5318 Returns number of bits in the bit string.
5319 </para>
5320 <para>
5321 <literal>bit_length(B'10111')</literal>
5322 <returnvalue>5</returnvalue>
5323 </para></entry>
5324 </row>
5325
5326 <row>
5327 <entry role="func_table_entry"><para role="func_signature">
5328 <indexterm>
5329 <primary>length</primary>
5330 </indexterm>
5331 <indexterm>
5332 <primary>bit string</primary>
5333 <secondary>length</secondary>
5334 </indexterm>
5335 <function>length</function> ( <type>bit</type> )
5336 <returnvalue>integer</returnvalue>
5337 </para>
5338 <para>
5339 Returns number of bits in the bit string.
5340 </para>
5341 <para>
5342 <literal>length(B'10111')</literal>
5343 <returnvalue>5</returnvalue>
5344 </para></entry>
5345 </row>
5346
5347 <row>
5348 <entry role="func_table_entry"><para role="func_signature">
5349 <indexterm>
5350 <primary>octet_length</primary>
5351 </indexterm>
5352 <function>octet_length</function> ( <type>bit</type> )
5353 <returnvalue>integer</returnvalue>
5354 </para>
5355 <para>
5356 Returns number of bytes in the bit string.
5357 </para>
5358 <para>
5359 <literal>octet_length(B'1011111011')</literal>
5360 <returnvalue>2</returnvalue>
5361 </para></entry>
5362 </row>
5363
5364 <row>
5365 <entry role="func_table_entry"><para role="func_signature">
5366 <indexterm>
5367 <primary>overlay</primary>
5368 </indexterm>
5369 <function>overlay</function> ( <parameter>bits</parameter> <type>bit</type> <literal>PLACING</literal> <parameter>newsubstring</parameter> <type>bit</type> <literal>FROM</literal> <parameter>start</parameter> <type>integer</type> <optional> <literal>FOR</literal> <parameter>count</parameter> <type>integer</type> </optional> )
5370 <returnvalue>bit</returnvalue>
5371 </para>
5372 <para>
5373 Replaces the substring of <parameter>bits</parameter> that starts at
5374 the <parameter>start</parameter>'th bit and extends
5375 for <parameter>count</parameter> bits
5376 with <parameter>newsubstring</parameter>.
5377 If <parameter>count</parameter> is omitted, it defaults to the length
5378 of <parameter>newsubstring</parameter>.
5379 </para>
5380 <para>
5381 <literal>overlay(B'01010101010101010' placing B'11111' from 2 for 3)</literal>
5382 <returnvalue>0111110101010101010</returnvalue>
5383 </para></entry>
5384 </row>
5385
5386 <row>
5387 <entry role="func_table_entry"><para role="func_signature">
5388 <indexterm>
5389 <primary>position</primary>
5390 </indexterm>
5391 <function>position</function> ( <parameter>substring</parameter> <type>bit</type> <literal>IN</literal> <parameter>bits</parameter> <type>bit</type> )
5392 <returnvalue>integer</returnvalue>
5393 </para>
5394 <para>
5395 Returns first starting index of the specified <parameter>substring</parameter>
5396 within <parameter>bits</parameter>, or zero if it's not present.
5397 </para>
5398 <para>
5399 <literal>position(B'010' in B'000001101011')</literal>
5400 <returnvalue>8</returnvalue>
5401 </para></entry>
5402 </row>
5403
5404 <row>
5405 <entry role="func_table_entry"><para role="func_signature">
5406 <indexterm>
5407 <primary>substring</primary>
5408 </indexterm>
5409 <function>substring</function> ( <parameter>bits</parameter> <type>bit</type> <optional> <literal>FROM</literal> <parameter>start</parameter> <type>integer</type> </optional> <optional> <literal>FOR</literal> <parameter>count</parameter> <type>integer</type> </optional> )
5410 <returnvalue>bit</returnvalue>
5411 </para>
5412 <para>
5413 Extracts the substring of <parameter>bits</parameter> starting at
5414 the <parameter>start</parameter>'th bit if that is specified,
5415 and stopping after <parameter>count</parameter> bits if that is
5416 specified. Provide at least one of <parameter>start</parameter>
5417 and <parameter>count</parameter>.
5418 </para>
5419 <para>
5420 <literal>substring(B'110010111111' from 3 for 2)</literal>
5421 <returnvalue>00</returnvalue>
5422 </para></entry>
5423 </row>
5424
5425 <row>
5426 <entry role="func_table_entry"><para role="func_signature">
5427 <indexterm>
5428 <primary>get_bit</primary>
5429 </indexterm>
5430 <function>get_bit</function> ( <parameter>bits</parameter> <type>bit</type>,
5431 <parameter>n</parameter> <type>integer</type> )
5432 <returnvalue>integer</returnvalue>
5433 </para>
5434 <para>
5435 Extracts <parameter>n</parameter>'th bit
5436 from bit string; the first (leftmost) bit is bit 0.
5437 </para>
5438 <para>
5439 <literal>get_bit(B'101010101010101010', 6)</literal>
5440 <returnvalue>1</returnvalue>
5441 </para></entry>
5442 </row>
5443
5444 <row>
5445 <entry role="func_table_entry"><para role="func_signature">
5446 <indexterm>
5447 <primary>set_bit</primary>
5448 </indexterm>
5449 <function>set_bit</function> ( <parameter>bits</parameter> <type>bit</type>,
5450 <parameter>n</parameter> <type>integer</type>,
5451 <parameter>newvalue</parameter> <type>integer</type> )
5452 <returnvalue>bit</returnvalue>
5453 </para>
5454 <para>
5455 Sets <parameter>n</parameter>'th bit in
5456 bit string to <parameter>newvalue</parameter>;
5457 the first (leftmost) bit is bit 0.
5458 </para>
5459 <para>
5460 <literal>set_bit(B'101010101010101010', 6, 0)</literal>
5461 <returnvalue>101010001010101010</returnvalue>
5462 </para></entry>
5463 </row>
5464 </tbody>
5465 </tgroup>
5466 </table>
5467
5468 <para>
5469 In addition, it is possible to cast integral values to and from type
5470 <type>bit</type>.
5471 Casting an integer to <type>bit(n)</type> copies the rightmost
5472 <literal>n</literal> bits. Casting an integer to a bit string width wider
5473 than the integer itself will sign-extend on the left.
5474 Some examples:
5475 <programlisting>
5476 44::bit(10) <lineannotation>0000101100</lineannotation>
5477 44::bit(3) <lineannotation>100</lineannotation>
5478 cast(-44 as bit(12)) <lineannotation>111111010100</lineannotation>
5479 '1110'::bit(4)::integer <lineannotation>14</lineannotation>
5480 </programlisting>
5481 Note that casting to just <quote>bit</quote> means casting to
5482 <literal>bit(1)</literal>, and so will deliver only the least significant
5483 bit of the integer.
5484 </para>
5485 </sect1>
5486
5487
5488 <sect1 id="functions-matching">
5489 <title>Pattern Matching</title>
5490
5491 <indexterm zone="functions-matching">
5492 <primary>pattern matching</primary>
5493 </indexterm>
5494
5495 <para>
5496 There are three separate approaches to pattern matching provided
5497 by <productname>PostgreSQL</productname>: the traditional
5498 <acronym>SQL</acronym> <function>LIKE</function> operator, the
5499 more recent <function>SIMILAR TO</function> operator (added in
5500 SQL:1999), and <acronym>POSIX</acronym>-style regular
5501 expressions. Aside from the basic <quote>does this string match
5502 this pattern?</quote> operators, functions are available to extract
5503 or replace matching substrings and to split a string at matching
5504 locations.
5505 </para>
5506
5507 <tip>
5508 <para>
5509 If you have pattern matching needs that go beyond this,
5510 consider writing a user-defined function in Perl or Tcl.
5511 </para>
5512 </tip>
5513
5514 <caution>
5515 <para>
5516 While most regular-expression searches can be executed very quickly,
5517 regular expressions can be contrived that take arbitrary amounts of
5518 time and memory to process. Be wary of accepting regular-expression
5519 search patterns from hostile sources. If you must do so, it is
5520 advisable to impose a statement timeout.
5521 </para>
5522
5523 <para>
5524 Searches using <function>SIMILAR TO</function> patterns have the same
5525 security hazards, since <function>SIMILAR TO</function> provides many
5526 of the same capabilities as <acronym>POSIX</acronym>-style regular
5527 expressions.
5528 </para>
5529
5530 <para>
5531 <function>LIKE</function> searches, being much simpler than the other
5532 two options, are safer to use with possibly-hostile pattern sources.
5533 </para>
5534 </caution>
5535
5536 <para>
5537 <function>SIMILAR TO</function> and <acronym>POSIX</acronym>-style regular
5538 expressions do not support nondeterministic collations. If required, use
5539 <function>LIKE</function> or apply a different collation to the expression
5540 to work around this limitation.
5541 </para>
5542
5543 <sect2 id="functions-like">
5544 <title><function>LIKE</function></title>
5545
5546 <indexterm>
5547 <primary>LIKE</primary>
5548 </indexterm>
5549
5550 <synopsis>
5551 <replaceable>string</replaceable> LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
5552 <replaceable>string</replaceable> NOT LIKE <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
5553 </synopsis>
5554
5555 <para>
5556 The <function>LIKE</function> expression returns true if the
5557 <replaceable>string</replaceable> matches the supplied
5558 <replaceable>pattern</replaceable>. (As
5559 expected, the <function>NOT LIKE</function> expression returns
5560 false if <function>LIKE</function> returns true, and vice versa.
5561 An equivalent expression is
5562 <literal>NOT (<replaceable>string</replaceable> LIKE
5563 <replaceable>pattern</replaceable>)</literal>.)
5564 </para>
5565
5566 <para>
5567 If <replaceable>pattern</replaceable> does not contain percent
5568 signs or underscores, then the pattern only represents the string
5569 itself; in that case <function>LIKE</function> acts like the
5570 equals operator. An underscore (<literal>_</literal>) in
5571 <replaceable>pattern</replaceable> stands for (matches) any single
5572 character; a percent sign (<literal>%</literal>) matches any sequence
5573 of zero or more characters.
5574 </para>
5575
5576 <para>
5577 Some examples:
5578 <programlisting>
5579 'abc' LIKE 'abc' <lineannotation>true</lineannotation>
5580 'abc' LIKE 'a%' <lineannotation>true</lineannotation>
5581 'abc' LIKE '_b_' <lineannotation>true</lineannotation>
5582 'abc' LIKE 'c' <lineannotation>false</lineannotation>
5583 </programlisting>
5584 </para>
5585
5586 <para>
5587 <function>LIKE</function> pattern matching supports nondeterministic
5588 collations (see <xref linkend="collation-nondeterministic"/>), such as
5589 case-insensitive collations or collations that, say, ignore punctuation.
5590 So with a case-insensitive collation, one could have:
5591 <programlisting>
5592 'AbC' LIKE 'abc' COLLATE case_insensitive <lineannotation>true</lineannotation>
5593 'AbC' LIKE 'a%' COLLATE case_insensitive <lineannotation>true</lineannotation>
5594 </programlisting>
5595 With collations that ignore certain characters or in general that consider
5596 strings of different lengths equal, the semantics can become a bit more
5597 complicated. Consider these examples:
5598 <programlisting>
5599 '.foo.' LIKE 'foo' COLLATE ign_punct <lineannotation>true</lineannotation>
5600 '.foo.' LIKE 'f_o' COLLATE ign_punct <lineannotation>true</lineannotation>
5601 '.foo.' LIKE '_oo' COLLATE ign_punct <lineannotation>false</lineannotation>
5602 </programlisting>
5603 The way the matching works is that the pattern is partitioned into
5604 sequences of wildcards and non-wildcard strings (wildcards being
5605 <literal>_</literal> and <literal>%</literal>). For example, the pattern
5606 <literal>f_o</literal> is partitioned into <literal>f, _, o</literal>, the
5607 pattern <literal>_oo</literal> is partitioned into <literal>_,
5608 oo</literal>. The input string matches the pattern if it can be
5609 partitioned in such a way that the wildcards match one character or any
5610 number of characters respectively and the non-wildcard partitions are
5611 equal under the applicable collation. So for example, <literal>'.foo.'
5612 LIKE 'f_o' COLLATE ign_punct</literal> is true because one can partition
5613 <literal>.foo.</literal> into <literal>.f, o, o.</literal>, and then
5614 <literal>'.f' = 'f' COLLATE ign_punct</literal>, <literal>'o'</literal>
5615 matches the <literal>_</literal> wildcard, and <literal>'o.' = 'o' COLLATE
5616 ign_punct</literal>. But <literal>'.foo.' LIKE '_oo' COLLATE
5617 ign_punct</literal> is false because <literal>.foo.</literal> cannot be
5618 partitioned in a way that the first character is any character and the
5619 rest of the string compares equal to <literal>oo</literal>. (Note that
5620 the single-character wildcard always matches exactly one character,
5621 independent of the collation. So in this example, the
5622 <literal>_</literal> would match <literal>.</literal>, but then the rest
5623 of the input string won't match the rest of the pattern.)
5624 </para>
5625
5626 <para>
5627 <function>LIKE</function> pattern matching always covers the entire
5628 string. Therefore, if it's desired to match a sequence anywhere within
5629 a string, the pattern must start and end with a percent sign.
5630 </para>
5631
5632 <para>
5633 To match a literal underscore or percent sign without matching
5634 other characters, the respective character in
5635 <replaceable>pattern</replaceable> must be
5636 preceded by the escape character. The default escape
5637 character is the backslash but a different one can be selected by
5638 using the <literal>ESCAPE</literal> clause. To match the escape
5639 character itself, write two escape characters.
5640 </para>
5641
5642 <note>
5643 <para>
5644 If you have <xref linkend="guc-standard-conforming-strings"/> turned off,
5645 any backslashes you write in literal string constants will need to be
5646 doubled. See <xref linkend="sql-syntax-strings"/> for more information.
5647 </para>
5648 </note>
5649
5650 <para>
5651 It's also possible to select no escape character by writing
5652 <literal>ESCAPE ''</literal>. This effectively disables the
5653 escape mechanism, which makes it impossible to turn off the
5654 special meaning of underscore and percent signs in the pattern.
5655 </para>
5656
5657 <para>
5658 According to the SQL standard, omitting <literal>ESCAPE</literal>
5659 means there is no escape character (rather than defaulting to a
5660 backslash), and a zero-length <literal>ESCAPE</literal> value is
5661 disallowed. <productname>PostgreSQL</productname>'s behavior in
5662 this regard is therefore slightly nonstandard.
5663 </para>
5664
5665 <para>
5666 The key word <token>ILIKE</token> can be used instead of
5667 <token>LIKE</token> to make the match case-insensitive according to the
5668 active locale. (But this does not support nondeterministic collations.)
5669 This is not in the <acronym>SQL</acronym> standard but is a
5670 <productname>PostgreSQL</productname> extension.
5671 </para>
5672
5673 <para>
5674 The operator <literal>~~</literal> is equivalent to
5675 <function>LIKE</function>, and <literal>~~*</literal> corresponds to
5676 <function>ILIKE</function>. There are also
5677 <literal>!~~</literal> and <literal>!~~*</literal> operators that
5678 represent <function>NOT LIKE</function> and <function>NOT
5679 ILIKE</function>, respectively. All of these operators are
5680 <productname>PostgreSQL</productname>-specific. You may see these
5681 operator names in <command>EXPLAIN</command> output and similar
5682 places, since the parser actually translates <function>LIKE</function>
5683 et al. to these operators.
5684 </para>
5685
5686 <para>
5687 The phrases <function>LIKE</function>, <function>ILIKE</function>,
5688 <function>NOT LIKE</function>, and <function>NOT ILIKE</function> are
5689 generally treated as operators
5690 in <productname>PostgreSQL</productname> syntax; for example they can
5691 be used in <replaceable>expression</replaceable>
5692 <replaceable>operator</replaceable> ANY
5693 (<replaceable>subquery</replaceable>) constructs, although
5694 an <literal>ESCAPE</literal> clause cannot be included there. In some
5695 obscure cases it may be necessary to use the underlying operator names
5696 instead.
5697 </para>
5698
5699 <para>
5700 Also see the starts-with operator <literal>^@</literal> and the
5701 corresponding <function>starts_with()</function> function, which are
5702 useful in cases where simply matching the beginning of a string is
5703 needed.
5704 </para>
5705 </sect2>
5706
5707
5708 <sect2 id="functions-similarto-regexp">
5709 <title><function>SIMILAR TO</function> Regular Expressions</title>
5710
5711 <indexterm>
5712 <primary>regular expression</primary>
5713 <!-- <seealso>pattern matching</seealso> breaks index build -->
5714 </indexterm>
5715
5716 <indexterm>
5717 <primary>SIMILAR TO</primary>
5718 </indexterm>
5719 <indexterm>
5720 <primary>substring</primary>
5721 </indexterm>
5722
5723 <synopsis>
5724 <replaceable>string</replaceable> SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
5725 <replaceable>string</replaceable> NOT SIMILAR TO <replaceable>pattern</replaceable> <optional>ESCAPE <replaceable>escape-character</replaceable></optional>
5726 </synopsis>
5727
5728 <para>
5729 The <function>SIMILAR TO</function> operator returns true or
5730 false depending on whether its pattern matches the given string.
5731 It is similar to <function>LIKE</function>, except that it
5732 interprets the pattern using the SQL standard's definition of a
5733 regular expression. SQL regular expressions are a curious cross
5734 between <function>LIKE</function> notation and common (POSIX) regular
5735 expression notation.
5736 </para>
5737
5738 <para>
5739 Like <function>LIKE</function>, the <function>SIMILAR TO</function>
5740 operator succeeds only if its pattern matches the entire string;
5741 this is unlike common regular expression behavior where the pattern
5742 can match any part of the string.
5743 Also like
5744 <function>LIKE</function>, <function>SIMILAR TO</function> uses
5745 <literal>_</literal> and <literal>%</literal> as wildcard characters denoting
5746 any single character and any string, respectively (these are
5747 comparable to <literal>.</literal> and <literal>.*</literal> in POSIX regular
5748 expressions).
5749 </para>
5750
5751 <para>
5752 In addition to these facilities borrowed from <function>LIKE</function>,
5753 <function>SIMILAR TO</function> supports these pattern-matching
5754 metacharacters borrowed from POSIX regular expressions:
5755
5756 <itemizedlist>
5757 <listitem>
5758 <para>
5759 <literal>|</literal> denotes alternation (either of two alternatives).
5760 </para>
5761 </listitem>
5762 <listitem>
5763 <para>
5764 <literal>*</literal> denotes repetition of the previous item zero
5765 or more times.
5766 </para>
5767 </listitem>
5768 <listitem>
5769 <para>
5770 <literal>+</literal> denotes repetition of the previous item one
5771 or more times.
5772 </para>
5773 </listitem>
5774 <listitem>
5775 <para>
5776 <literal>?</literal> denotes repetition of the previous item zero
5777 or one time.
5778 </para>
5779 </listitem>
5780 <listitem>
5781 <para>
5782 <literal>{</literal><replaceable>m</replaceable><literal>}</literal> denotes repetition
5783 of the previous item exactly <replaceable>m</replaceable> times.
5784 </para>
5785 </listitem>
5786 <listitem>
5787 <para>
5788 <literal>{</literal><replaceable>m</replaceable><literal>,}</literal> denotes repetition
5789 of the previous item <replaceable>m</replaceable> or more times.
5790 </para>
5791 </listitem>
5792 <listitem>
5793 <para>
5794 <literal>{</literal><replaceable>m</replaceable><literal>,</literal><replaceable>n</replaceable><literal>}</literal>
5795 denotes repetition of the previous item at least <replaceable>m</replaceable> and
5796 not more than <replaceable>n</replaceable> times.
5797 </para>
5798 </listitem>
5799 <listitem>
5800 <para>
5801 Parentheses <literal>()</literal> can be used to group items into
5802 a single logical item.
5803 </para>
5804 </listitem>
5805 <listitem>
5806 <para>
5807 A bracket expression <literal>[...]</literal> specifies a character
5808 class, just as in POSIX regular expressions.
5809 </para>
5810 </listitem>
5811 </itemizedlist>
5812
5813 Notice that the period (<literal>.</literal>) is not a metacharacter
5814 for <function>SIMILAR TO</function>.
5815 </para>
5816
5817 <para>
5818 As with <function>LIKE</function>, a backslash disables the special
5819 meaning of any of these metacharacters. A different escape character
5820 can be specified with <literal>ESCAPE</literal>, or the escape
5821 capability can be disabled by writing <literal>ESCAPE ''</literal>.
5822 </para>
5823
5824 <para>
5825 According to the SQL standard, omitting <literal>ESCAPE</literal>
5826 means there is no escape character (rather than defaulting to a
5827 backslash), and a zero-length <literal>ESCAPE</literal> value is
5828 disallowed. <productname>PostgreSQL</productname>'s behavior in
5829 this regard is therefore slightly nonstandard.
5830 </para>
5831
5832 <para>
5833 Another nonstandard extension is that following the escape character
5834 with a letter or digit provides access to the escape sequences
5835 defined for POSIX regular expressions; see
5836 <xref linkend="posix-character-entry-escapes-table"/>,
5837 <xref linkend="posix-class-shorthand-escapes-table"/>, and
5838 <xref linkend="posix-constraint-escapes-table"/> below.
5839 </para>
5840
5841 <para>
5842 Some examples:
5843 <programlisting>
5844 'abc' SIMILAR TO 'abc' <lineannotation>true</lineannotation>
5845 'abc' SIMILAR TO 'a' <lineannotation>false</lineannotation>
5846 'abc' SIMILAR TO '%(b|d)%' <lineannotation>true</lineannotation>
5847 'abc' SIMILAR TO '(b|c)%' <lineannotation>false</lineannotation>
5848 '-abc-' SIMILAR TO '%\mabc\M%' <lineannotation>true</lineannotation>
5849 'xabcy' SIMILAR TO '%\mabc\M%' <lineannotation>false</lineannotation>
5850 </programlisting>
5851 </para>
5852
5853 <para>
5854 The <function>substring</function> function with three parameters
5855 provides extraction of a substring that matches an SQL
5856 regular expression pattern. The function can be written according
5857 to standard SQL syntax:
5858 <synopsis>
5859 substring(<replaceable>string</replaceable> similar <replaceable>pattern</replaceable> escape <replaceable>escape-character</replaceable>)
5860 </synopsis>
5861 or using the now obsolete SQL:1999 syntax:
5862 <synopsis>
5863 substring(<replaceable>string</replaceable> from <replaceable>pattern</replaceable> for <replaceable>escape-character</replaceable>)
5864 </synopsis>
5865 or as a plain three-argument function:
5866 <synopsis>
5867 substring(<replaceable>string</replaceable>, <replaceable>pattern</replaceable>, <replaceable>escape-character</replaceable>)
5868 </synopsis>
5869 As with <literal>SIMILAR TO</literal>, the
5870 specified pattern must match the entire data string, or else the
5871 function fails and returns null. To indicate the part of the
5872 pattern for which the matching data sub-string is of interest,
5873 the pattern should contain
5874 two occurrences of the escape character followed by a double quote
5875 (<literal>"</literal>). <!-- " font-lock sanity -->
5876 The text matching the portion of the pattern
5877 between these separators is returned when the match is successful.
5878 </para>
5879
5880 <para>
5881 The escape-double-quote separators actually
5882 divide <function>substring</function>'s pattern into three independent
5883 regular expressions; for example, a vertical bar (<literal>|</literal>)
5884 in any of the three sections affects only that section. Also, the first
5885 and third of these regular expressions are defined to match the smallest
5886 possible amount of text, not the largest, when there is any ambiguity
5887 about how much of the data string matches which pattern. (In POSIX
5888 parlance, the first and third regular expressions are forced to be
5889 non-greedy.)
5890 </para>
5891
5892 <para>
5893 As an extension to the SQL standard, <productname>PostgreSQL</productname>
5894 allows there to be just one escape-double-quote separator, in which case
5895 the third regular expression is taken as empty; or no separators, in which
5896 case the first and third regular expressions are taken as empty.
5897 </para>
5898
5899 <para>
5900 Some examples, with <literal>#&quot;</literal> delimiting the return string:
5901 <programlisting>
5902 substring('foobar' similar '%#"o_b#"%' escape '#') <lineannotation>oob</lineannotation>
5903 substring('foobar' similar '#"o_b#"%' escape '#') <lineannotation>NULL</lineannotation>
5904 </programlisting>
5905 </para>
5906 </sect2>
5907
5908 <sect2 id="functions-posix-regexp">
5909 <title><acronym>POSIX</acronym> Regular Expressions</title>
5910
5911 <indexterm zone="functions-posix-regexp">
5912 <primary>regular expression</primary>
5913 <seealso>pattern matching</seealso>
5914 </indexterm>
5915 <indexterm>
5916 <primary>substring</primary>
5917 </indexterm>
5918 <indexterm>
5919 <primary>regexp_count</primary>
5920 </indexterm>
5921 <indexterm>
5922 <primary>regexp_instr</primary>
5923 </indexterm>
5924 <indexterm>
5925 <primary>regexp_like</primary>
5926 </indexterm>
5927 <indexterm>
5928 <primary>regexp_match</primary>
5929 </indexterm>
5930 <indexterm>
5931 <primary>regexp_matches</primary>
5932 </indexterm>
5933 <indexterm>
5934 <primary>regexp_replace</primary>
5935 </indexterm>
5936 <indexterm>
5937 <primary>regexp_split_to_table</primary>
5938 </indexterm>
5939 <indexterm>
5940 <primary>regexp_split_to_array</primary>
5941 </indexterm>
5942 <indexterm>
5943 <primary>regexp_substr</primary>
5944 </indexterm>
5945
5946 <para>
5947 <xref linkend="functions-posix-table"/> lists the available
5948 operators for pattern matching using POSIX regular expressions.
5949 </para>
5950
5951 <table id="functions-posix-table">
5952 <title>Regular Expression Match Operators</title>
5953
5954 <tgroup cols="1">
5955 <thead>
5956 <row>
5957 <entry role="func_table_entry"><para role="func_signature">
5958 Operator
5959 </para>
5960 <para>
5961 Description
5962 </para>
5963 <para>
5964 Example(s)
5965 </para></entry>
5966 </row>
5967 </thead>
5968
5969 <tbody>
5970 <row>
5971 <entry role="func_table_entry"><para role="func_signature">
5972 <type>text</type> <literal>~</literal> <type>text</type>
5973 <returnvalue>boolean</returnvalue>
5974 </para>
5975 <para>
5976 String matches regular expression, case sensitively
5977 </para>
5978 <para>
5979 <literal>'thomas' ~ 't.*ma'</literal>
5980 <returnvalue>t</returnvalue>
5981 </para></entry>
5982 </row>
5983
5984 <row>
5985 <entry role="func_table_entry"><para role="func_signature">
5986 <type>text</type> <literal>~*</literal> <type>text</type>
5987 <returnvalue>boolean</returnvalue>
5988 </para>
5989 <para>
5990 String matches regular expression, case-insensitively
5991 </para>
5992 <para>
5993 <literal>'thomas' ~* 'T.*ma'</literal>
5994 <returnvalue>t</returnvalue>
5995 </para></entry>
5996 </row>
5997
5998 <row>
5999 <entry role="func_table_entry"><para role="func_signature">
6000 <type>text</type> <literal>!~</literal> <type>text</type>
6001 <returnvalue>boolean</returnvalue>
6002 </para>
6003 <para>
6004 String does not match regular expression, case sensitively
6005 </para>
6006 <para>
6007 <literal>'thomas' !~ 't.*max'</literal>
6008 <returnvalue>t</returnvalue>
6009 </para></entry>
6010 </row>
6011
6012 <row>
6013 <entry role="func_table_entry"><para role="func_signature">
6014 <type>text</type> <literal>!~*</literal> <type>text</type>
6015 <returnvalue>boolean</returnvalue>
6016 </para>
6017 <para>
6018 String does not match regular expression, case-insensitively
6019 </para>
6020 <para>
6021 <literal>'thomas' !~* 'T.*ma'</literal>
6022 <returnvalue>f</returnvalue>
6023 </para></entry>
6024 </row>
6025 </tbody>
6026 </tgroup>
6027 </table>
6028
6029 <para>
6030 <acronym>POSIX</acronym> regular expressions provide a more
6031 powerful means for pattern matching than the <function>LIKE</function> and
6032 <function>SIMILAR TO</function> operators.
6033 Many Unix tools such as <command>egrep</command>,
6034 <command>sed</command>, or <command>awk</command> use a pattern
6035 matching language that is similar to the one described here.
6036 </para>
6037
6038 <para>
6039 A regular expression is a character sequence that is an
6040 abbreviated definition of a set of strings (a <firstterm>regular
6041 set</firstterm>). A string is said to match a regular expression
6042 if it is a member of the regular set described by the regular
6043 expression. As with <function>LIKE</function>, pattern characters
6044 match string characters exactly unless they are special characters
6045 in the regular expression language &mdash; but regular expressions use
6046 different special characters than <function>LIKE</function> does.
6047 Unlike <function>LIKE</function> patterns, a
6048 regular expression is allowed to match anywhere within a string, unless
6049 the regular expression is explicitly anchored to the beginning or
6050 end of the string.
6051 </para>
6052
6053 <para>
6054 Some examples:
6055 <programlisting>
6056 'abcd' ~ 'bc' <lineannotation>true</lineannotation>
6057 'abcd' ~ 'a.c' <lineannotation>true &mdash; dot matches any character</lineannotation>
6058 'abcd' ~ 'a.*d' <lineannotation>true &mdash; <literal>*</literal> repeats the preceding pattern item</lineannotation>
6059 'abcd' ~ '(b|x)' <lineannotation>true &mdash; <literal>|</literal> means OR, parentheses group</lineannotation>
6060 'abcd' ~ '^a' <lineannotation>true &mdash; <literal>^</literal> anchors to start of string</lineannotation>
6061 'abcd' ~ '^(b|c)' <lineannotation>false &mdash; would match except for anchoring</lineannotation>
6062 </programlisting>
6063 </para>
6064
6065 <para>
6066 The <acronym>POSIX</acronym> pattern language is described in much
6067 greater detail below.
6068 </para>
6069
6070 <para>
6071 The <function>substring</function> function with two parameters,
6072 <function>substring(<replaceable>string</replaceable> from
6073 <replaceable>pattern</replaceable>)</function>, provides extraction of a
6074 substring
6075 that matches a POSIX regular expression pattern. It returns null if
6076 there is no match, otherwise the first portion of the text that matched the
6077 pattern. But if the pattern contains any parentheses, the portion
6078 of the text that matched the first parenthesized subexpression (the
6079 one whose left parenthesis comes first) is
6080 returned. You can put parentheses around the whole expression
6081 if you want to use parentheses within it without triggering this
6082 exception. If you need parentheses in the pattern before the
6083 subexpression you want to extract, see the non-capturing parentheses
6084 described below.
6085 </para>
6086
6087 <para>
6088 Some examples:
6089 <programlisting>
6090 substring('foobar' from 'o.b') <lineannotation>oob</lineannotation>
6091 substring('foobar' from 'o(.)b') <lineannotation>o</lineannotation>
6092 </programlisting>
6093 </para>
6094
6095 <para>
6096 The <function>regexp_count</function> function counts the number of
6097 places where a POSIX regular expression pattern matches a string.
6098 It has the syntax
6099 <function>regexp_count</function>(<replaceable>string</replaceable>,
6100 <replaceable>pattern</replaceable>
6101 <optional>, <replaceable>start</replaceable>
6102 <optional>, <replaceable>flags</replaceable>
6103 </optional></optional>).
6104 <replaceable>pattern</replaceable> is searched for
6105 in <replaceable>string</replaceable>, normally from the beginning of
6106 the string, but if the <replaceable>start</replaceable> parameter is
6107 provided then beginning from that character index.
6108 The <replaceable>flags</replaceable> parameter is an optional text
6109 string containing zero or more single-letter flags that change the
6110 function's behavior. For example, including <literal>i</literal> in
6111 <replaceable>flags</replaceable> specifies case-insensitive matching.
6112 Supported flags are described in
6113 <xref linkend="posix-embedded-options-table"/>.
6114 </para>
6115
6116 <para>
6117 Some examples:
6118 <programlisting>
6119 regexp_count('ABCABCAXYaxy', 'A.') <lineannotation>3</lineannotation>
6120 regexp_count('ABCABCAXYaxy', 'A.', 1, 'i') <lineannotation>4</lineannotation>
6121 </programlisting>
6122 </para>
6123
6124 <para>
6125 The <function>regexp_instr</function> function returns the starting or
6126 ending position of the <replaceable>N</replaceable>'th match of a
6127 POSIX regular expression pattern to a string, or zero if there is no
6128 such match. It has the syntax
6129 <function>regexp_instr</function>(<replaceable>string</replaceable>,
6130 <replaceable>pattern</replaceable>
6131 <optional>, <replaceable>start</replaceable>
6132 <optional>, <replaceable>N</replaceable>
6133 <optional>, <replaceable>endoption</replaceable>
6134 <optional>, <replaceable>flags</replaceable>
6135 <optional>, <replaceable>subexpr</replaceable>
6136 </optional></optional></optional></optional></optional>).
6137 <replaceable>pattern</replaceable> is searched for
6138 in <replaceable>string</replaceable>, normally from the beginning of
6139 the string, but if the <replaceable>start</replaceable> parameter is
6140 provided then beginning from that character index.
6141 If <replaceable>N</replaceable> is specified
6142 then the <replaceable>N</replaceable>'th match of the pattern
6143 is located, otherwise the first match is located.
6144 If the <replaceable>endoption</replaceable> parameter is omitted or
6145 specified as zero, the function returns the position of the first
6146 character of the match. Otherwise, <replaceable>endoption</replaceable>
6147 must be one, and the function returns the position of the character
6148 following the match.
6149 The <replaceable>flags</replaceable> parameter is an optional text
6150 string containing zero or more single-letter flags that change the
6151 function's behavior. Supported flags are described
6152 in <xref linkend="posix-embedded-options-table"/>.
6153 For a pattern containing parenthesized
6154 subexpressions, <replaceable>subexpr</replaceable> is an integer
6155 indicating which subexpression is of interest: the result identifies
6156 the position of the substring matching that subexpression.
6157 Subexpressions are numbered in the order of their leading parentheses.
6158 When <replaceable>subexpr</replaceable> is omitted or zero, the result
6159 identifies the position of the whole match regardless of
6160 parenthesized subexpressions.
6161 </para>
6162
6163 <para>
6164 Some examples:
6165 <programlisting>
6166 regexp_instr('number of your street, town zip, FR', '[^,]+', 1, 2)
6167 <lineannotation>23</lineannotation>
6168 regexp_instr(string=>'ABCDEFGHI', pattern=>'(c..)(...)', start=>1, "N"=>1, endoption=>0, flags=>'i', subexpr=>2)
6169 <lineannotation>6</lineannotation>
6170 </programlisting>
6171 </para>
6172
6173 <para>
6174 The <function>regexp_like</function> function checks whether a match
6175 of a POSIX regular expression pattern occurs within a string,
6176 returning boolean true or false. It has the syntax
6177 <function>regexp_like</function>(<replaceable>string</replaceable>,
6178 <replaceable>pattern</replaceable>
6179 <optional>, <replaceable>flags</replaceable> </optional>).
6180 The <replaceable>flags</replaceable> parameter is an optional text
6181 string containing zero or more single-letter flags that change the
6182 function's behavior. Supported flags are described
6183 in <xref linkend="posix-embedded-options-table"/>.
6184 This function has the same results as the <literal>~</literal>
6185 operator if no flags are specified. If only the <literal>i</literal>
6186 flag is specified, it has the same results as
6187 the <literal>~*</literal> operator.
6188 </para>
6189
6190 <para>
6191 Some examples:
6192 <programlisting>
6193 regexp_like('Hello World', 'world') <lineannotation>false</lineannotation>
6194 regexp_like('Hello World', 'world', 'i') <lineannotation>true</lineannotation>
6195 </programlisting>
6196 </para>
6197
6198 <para>
6199 The <function>regexp_match</function> function returns a text array of
6200 matching substring(s) within the first match of a POSIX
6201 regular expression pattern to a string. It has the syntax
6202 <function>regexp_match</function>(<replaceable>string</replaceable>,
6203 <replaceable>pattern</replaceable> <optional>, <replaceable>flags</replaceable> </optional>).
6204 If there is no match, the result is <literal>NULL</literal>.
6205 If a match is found, and the <replaceable>pattern</replaceable> contains no
6206 parenthesized subexpressions, then the result is a single-element text
6207 array containing the substring matching the whole pattern.
6208 If a match is found, and the <replaceable>pattern</replaceable> contains
6209 parenthesized subexpressions, then the result is a text array
6210 whose <replaceable>n</replaceable>'th element is the substring matching
6211 the <replaceable>n</replaceable>'th parenthesized subexpression of
6212 the <replaceable>pattern</replaceable> (not counting <quote>non-capturing</quote>
6213 parentheses; see below for details).
6214 The <replaceable>flags</replaceable> parameter is an optional text string
6215 containing zero or more single-letter flags that change the function's
6216 behavior. Supported flags are described
6217 in <xref linkend="posix-embedded-options-table"/>.
6218 </para>
6219
6220 <para>
6221 Some examples:
6222 <programlisting>
6223 SELECT regexp_match('foobarbequebaz', 'bar.*que');
6224 regexp_match
6225 --------------
6226 {barbeque}
6227 (1 row)
6228
6229 SELECT regexp_match('foobarbequebaz', '(bar)(beque)');
6230 regexp_match
6231 --------------
6232 {bar,beque}
6233 (1 row)
6234 </programlisting>
6235 </para>
6236
6237 <tip>
6238 <para>
6239 In the common case where you just want the whole matching substring
6240 or <literal>NULL</literal> for no match, the best solution is to
6241 use <function>regexp_substr()</function>.
6242 However, <function>regexp_substr()</function> only exists
6243 in <productname>PostgreSQL</productname> version 15 and up. When
6244 working in older versions, you can extract the first element
6245 of <function>regexp_match()</function>'s result, for example:
6246 <programlisting>
6247 SELECT (regexp_match('foobarbequebaz', 'bar.*que'))[1];
6248 regexp_match
6249 --------------
6250 barbeque
6251 (1 row)
6252 </programlisting>
6253 </para>
6254 </tip>
6255
6256 <para>
6257 The <function>regexp_matches</function> function returns a set of text arrays
6258 of matching substring(s) within matches of a POSIX regular
6259 expression pattern to a string. It has the same syntax as
6260 <function>regexp_match</function>.
6261 This function returns no rows if there is no match, one row if there is
6262 a match and the <literal>g</literal> flag is not given, or <replaceable>N</replaceable>
6263 rows if there are <replaceable>N</replaceable> matches and the <literal>g</literal> flag
6264 is given. Each returned row is a text array containing the whole
6265 matched substring or the substrings matching parenthesized
6266 subexpressions of the <replaceable>pattern</replaceable>, just as described above
6267 for <function>regexp_match</function>.
6268 <function>regexp_matches</function> accepts all the flags shown
6269 in <xref linkend="posix-embedded-options-table"/>, plus
6270 the <literal>g</literal> flag which commands it to return all matches, not
6271 just the first one.
6272 </para>
6273
6274 <para>
6275 Some examples:
6276 <programlisting>
6277 SELECT regexp_matches('foo', 'not there');
6278 regexp_matches
6279 ----------------
6280 (0 rows)
6281
6282 SELECT regexp_matches('foobarbequebazilbarfbonk', '(b[^b]+)(b[^b]+)', 'g');
6283 regexp_matches
6284 ----------------
6285 {bar,beque}
6286 {bazil,barf}
6287 (2 rows)
6288 </programlisting>
6289 </para>
6290
6291 <tip>
6292 <para>
6293 In most cases <function>regexp_matches()</function> should be used with
6294 the <literal>g</literal> flag, since if you only want the first match, it's
6295 easier and more efficient to use <function>regexp_match()</function>.
6296 However, <function>regexp_match()</function> only exists
6297 in <productname>PostgreSQL</productname> version 10 and up. When working in older
6298 versions, a common trick is to place a <function>regexp_matches()</function>
6299 call in a sub-select, for example:
6300 <programlisting>
6301 SELECT col1, (SELECT regexp_matches(col2, '(bar)(beque)')) FROM tab;
6302 </programlisting>
6303 This produces a text array if there's a match, or <literal>NULL</literal> if
6304 not, the same as <function>regexp_match()</function> would do. Without the
6305 sub-select, this query would produce no output at all for table rows
6306 without a match, which is typically not the desired behavior.
6307 </para>
6308 </tip>
6309
6310 <para>
6311 The <function>regexp_replace</function> function provides substitution of
6312 new text for substrings that match POSIX regular expression patterns.
6313 It has the syntax
6314 <function>regexp_replace</function>(<replaceable>string</replaceable>,
6315 <replaceable>pattern</replaceable>, <replaceable>replacement</replaceable>
6316 <optional>, <replaceable>flags</replaceable> </optional>)
6317 or
6318 <function>regexp_replace</function>(<replaceable>string</replaceable>,
6319 <replaceable>pattern</replaceable>, <replaceable>replacement</replaceable>,
6320 <replaceable>start</replaceable>
6321 <optional>, <replaceable>N</replaceable>
6322 <optional>, <replaceable>flags</replaceable> </optional></optional>).
6323 The source <replaceable>string</replaceable> is returned unchanged if
6324 there is no match to the <replaceable>pattern</replaceable>. If there is a
6325 match, the <replaceable>string</replaceable> is returned with the
6326 <replaceable>replacement</replaceable> string substituted for the matching
6327 substring. The <replaceable>replacement</replaceable> string can contain
6328 <literal>\</literal><replaceable>n</replaceable>, where <replaceable>n</replaceable> is 1
6329 through 9, to indicate that the source substring matching the
6330 <replaceable>n</replaceable>'th parenthesized subexpression of the pattern should be
6331 inserted, and it can contain <literal>\&amp;</literal> to indicate that the
6332 substring matching the entire pattern should be inserted. Write
6333 <literal>\\</literal> if you need to put a literal backslash in the replacement
6334 text.
6335 <replaceable>pattern</replaceable> is searched for
6336 in <replaceable>string</replaceable>, normally from the beginning of
6337 the string, but if the <replaceable>start</replaceable> parameter is
6338 provided then beginning from that character index.
6339 By default, only the first match of the pattern is replaced.
6340 If <replaceable>N</replaceable> is specified and is greater than zero,
6341 then the <replaceable>N</replaceable>'th match of the pattern
6342 is replaced.
6343 If the <literal>g</literal> flag is given, or
6344 if <replaceable>N</replaceable> is specified and is zero, then all
6345 matches at or after the <replaceable>start</replaceable> position are
6346 replaced. (The <literal>g</literal> flag is ignored
6347 when <replaceable>N</replaceable> is specified.)
6348 The <replaceable>flags</replaceable> parameter is an optional text
6349 string containing zero or more single-letter flags that change the
6350 function's behavior. Supported flags (though
6351 not <literal>g</literal>) are
6352 described in <xref linkend="posix-embedded-options-table"/>.
6353 </para>
6354
6355 <para>
6356 Some examples:
6357 <programlisting>
6358 regexp_replace('foobarbaz', 'b..', 'X')
6359 <lineannotation>fooXbaz</lineannotation>
6360 regexp_replace('foobarbaz', 'b..', 'X', 'g')
6361 <lineannotation>fooXX</lineannotation>
6362 regexp_replace('foobarbaz', 'b(..)', 'X\1Y', 'g')
6363 <lineannotation>fooXarYXazY</lineannotation>
6364 regexp_replace('A PostgreSQL function', 'a|e|i|o|u', 'X', 1, 0, 'i')
6365 <lineannotation>X PXstgrXSQL fXnctXXn</lineannotation>
6366 regexp_replace(string=>'A PostgreSQL function', pattern=>'a|e|i|o|u', replacement=>'X', start=>1, "N"=>3, flags=>'i')
6367 <lineannotation>A PostgrXSQL function</lineannotation>
6368 </programlisting>
6369 </para>
6370
6371 <para>
6372 The <function>regexp_split_to_table</function> function splits a string using a POSIX
6373 regular expression pattern as a delimiter. It has the syntax
6374 <function>regexp_split_to_table</function>(<replaceable>string</replaceable>, <replaceable>pattern</replaceable>
6375 <optional>, <replaceable>flags</replaceable> </optional>).
6376 If there is no match to the <replaceable>pattern</replaceable>, the function returns the
6377 <replaceable>string</replaceable>. If there is at least one match, for each match it returns
6378 the text from the end of the last match (or the beginning of the string)
6379 to the beginning of the match. When there are no more matches, it
6380 returns the text from the end of the last match to the end of the string.
6381 The <replaceable>flags</replaceable> parameter is an optional text string containing
6382 zero or more single-letter flags that change the function's behavior.
6383 <function>regexp_split_to_table</function> supports the flags described in
6384 <xref linkend="posix-embedded-options-table"/>.
6385 </para>
6386
6387 <para>
6388 The <function>regexp_split_to_array</function> function behaves the same as
6389 <function>regexp_split_to_table</function>, except that <function>regexp_split_to_array</function>
6390 returns its result as an array of <type>text</type>. It has the syntax
6391 <function>regexp_split_to_array</function>(<replaceable>string</replaceable>, <replaceable>pattern</replaceable>
6392 <optional>, <replaceable>flags</replaceable> </optional>).
6393 The parameters are the same as for <function>regexp_split_to_table</function>.
6394 </para>
6395
6396 <para>
6397 Some examples:
6398 <programlisting>
6399 SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', '\s+') AS foo;
6400 foo
6401 -------
6402 the
6403 quick
6404 brown
6405 fox
6406 jumps
6407 over
6408 the
6409 lazy
6410 dog
6411 (9 rows)
6412
6413 SELECT regexp_split_to_array('the quick brown fox jumps over the lazy dog', '\s+');
6414 regexp_split_to_array
6415 -----------------------------------------------
6416 {the,quick,brown,fox,jumps,over,the,lazy,dog}
6417 (1 row)
6418
6419 SELECT foo FROM regexp_split_to_table('the quick brown fox', '\s*') AS foo;
6420 foo
6421 -----
6422 t
6423 h
6424 e
6425 q
6426 u
6427 i
6428 c
6429 k
6430 b
6431 r
6432 o
6433 w
6434 n
6435 f
6436 o
6437 x
6438 (16 rows)
6439 </programlisting>
6440 </para>
6441
6442 <para>
6443 As the last example demonstrates, the regexp split functions ignore
6444 zero-length matches that occur at the start or end of the string
6445 or immediately after a previous match. This is contrary to the strict
6446 definition of regexp matching that is implemented by
6447 the other regexp functions, but is usually the most convenient behavior
6448 in practice. Other software systems such as Perl use similar definitions.
6449 </para>
6450
6451 <para>
6452 The <function>regexp_substr</function> function returns the substring
6453 that matches a POSIX regular expression pattern,
6454 or <literal>NULL</literal> if there is no match. It has the syntax
6455 <function>regexp_substr</function>(<replaceable>string</replaceable>,
6456 <replaceable>pattern</replaceable>
6457 <optional>, <replaceable>start</replaceable>
6458 <optional>, <replaceable>N</replaceable>
6459 <optional>, <replaceable>flags</replaceable>
6460 <optional>, <replaceable>subexpr</replaceable>
6461 </optional></optional></optional></optional>).
6462 <replaceable>pattern</replaceable> is searched for
6463 in <replaceable>string</replaceable>, normally from the beginning of
6464 the string, but if the <replaceable>start</replaceable> parameter is
6465 provided then beginning from that character index.
6466 If <replaceable>N</replaceable> is specified
6467 then the <replaceable>N</replaceable>'th match of the pattern
6468 is returned, otherwise the first match is returned.
6469 The <replaceable>flags</replaceable> parameter is an optional text
6470 string containing zero or more single-letter flags that change the
6471 function's behavior. Supported flags are described
6472 in <xref linkend="posix-embedded-options-table"/>.
6473 For a pattern containing parenthesized
6474 subexpressions, <replaceable>subexpr</replaceable> is an integer
6475 indicating which subexpression is of interest: the result is the
6476 substring matching that subexpression.
6477 Subexpressions are numbered in the order of their leading parentheses.
6478 When <replaceable>subexpr</replaceable> is omitted or zero, the result
6479 is the whole match regardless of parenthesized subexpressions.
6480 </para>
6481
6482 <para>
6483 Some examples:
6484 <programlisting>
6485 regexp_substr('number of your street, town zip, FR', '[^,]+', 1, 2)
6486 <lineannotation> town zip</lineannotation>
6487 regexp_substr('ABCDEFGHI', '(c..)(...)', 1, 1, 'i', 2)
6488 <lineannotation>FGH</lineannotation>
6489 </programlisting>
6490 </para>
6491
6492 <!-- derived from the re_syntax.n man page -->
6493
6494 <sect3 id="posix-syntax-details">
6495 <title>Regular Expression Details</title>
6496
6497 <para>
6498 <productname>PostgreSQL</productname>'s regular expressions are implemented
6499 using a software package written by Henry Spencer. Much of
6500 the description of regular expressions below is copied verbatim from his
6501 manual.
6502 </para>
6503
6504 <para>
6505 Regular expressions (<acronym>RE</acronym>s), as defined in
6506 <acronym>POSIX</acronym> 1003.2, come in two forms:
6507 <firstterm>extended</firstterm> <acronym>RE</acronym>s or <acronym>ERE</acronym>s
6508 (roughly those of <command>egrep</command>), and
6509 <firstterm>basic</firstterm> <acronym>RE</acronym>s or <acronym>BRE</acronym>s
6510 (roughly those of <command>ed</command>).
6511 <productname>PostgreSQL</productname> supports both forms, and
6512 also implements some extensions
6513 that are not in the POSIX standard, but have become widely used
6514 due to their availability in programming languages such as Perl and Tcl.
6515 <acronym>RE</acronym>s using these non-POSIX extensions are called
6516 <firstterm>advanced</firstterm> <acronym>RE</acronym>s or <acronym>ARE</acronym>s
6517 in this documentation. AREs are almost an exact superset of EREs,
6518 but BREs have several notational incompatibilities (as well as being
6519 much more limited).
6520 We first describe the ARE and ERE forms, noting features that apply
6521 only to AREs, and then describe how BREs differ.
6522 </para>
6523
6524 <note>
6525 <para>
6526 <productname>PostgreSQL</productname> always initially presumes that a regular
6527 expression follows the ARE rules. However, the more limited ERE or
6528 BRE rules can be chosen by prepending an <firstterm>embedded option</firstterm>
6529 to the RE pattern, as described in <xref linkend="posix-metasyntax"/>.
6530 This can be useful for compatibility with applications that expect
6531 exactly the <acronym>POSIX</acronym> 1003.2 rules.
6532 </para>
6533 </note>
6534
6535 <para>
6536 A regular expression is defined as one or more
6537 <firstterm>branches</firstterm>, separated by
6538 <literal>|</literal>. It matches anything that matches one of the
6539 branches.
6540 </para>
6541
6542 <para>
6543 A branch is zero or more <firstterm>quantified atoms</firstterm> or
6544 <firstterm>constraints</firstterm>, concatenated.
6545 It matches a match for the first, followed by a match for the second, etc.;
6546 an empty branch matches the empty string.
6547 </para>
6548
6549 <para>
6550 A quantified atom is an <firstterm>atom</firstterm> possibly followed
6551 by a single <firstterm>quantifier</firstterm>.
6552 Without a quantifier, it matches a match for the atom.
6553 With a quantifier, it can match some number of matches of the atom.
6554 An <firstterm>atom</firstterm> can be any of the possibilities
6555 shown in <xref linkend="posix-atoms-table"/>.
6556 The possible quantifiers and their meanings are shown in
6557 <xref linkend="posix-quantifiers-table"/>.
6558 </para>
6559
6560 <para>
6561 A <firstterm>constraint</firstterm> matches an empty string, but matches only when
6562 specific conditions are met. A constraint can be used where an atom
6563 could be used, except it cannot be followed by a quantifier.
6564 The simple constraints are shown in
6565 <xref linkend="posix-constraints-table"/>;
6566 some more constraints are described later.
6567 </para>
6568
6569
6570 <table id="posix-atoms-table">
6571 <title>Regular Expression Atoms</title>
6572
6573 <tgroup cols="2">
6574 <thead>
6575 <row>
6576 <entry>Atom</entry>
6577 <entry>Description</entry>
6578 </row>
6579 </thead>
6580
6581 <tbody>
6582 <row>
6583 <entry> <literal>(</literal><replaceable>re</replaceable><literal>)</literal> </entry>
6584 <entry> (where <replaceable>re</replaceable> is any regular expression)
6585 matches a match for
6586 <replaceable>re</replaceable>, with the match noted for possible reporting </entry>
6587 </row>
6588
6589 <row>
6590 <entry> <literal>(?:</literal><replaceable>re</replaceable><literal>)</literal> </entry>
6591 <entry> as above, but the match is not noted for reporting
6592 (a <quote>non-capturing</quote> set of parentheses)
6593 (AREs only) </entry>
6594 </row>
6595
6596 <row>
6597 <entry> <literal>.</literal> </entry>
6598 <entry> matches any single character </entry>
6599 </row>
6600
6601 <row>
6602 <entry> <literal>[</literal><replaceable>chars</replaceable><literal>]</literal> </entry>
6603 <entry> a <firstterm>bracket expression</firstterm>,
6604 matching any one of the <replaceable>chars</replaceable> (see
6605 <xref linkend="posix-bracket-expressions"/> for more detail) </entry>
6606 </row>
6607
6608 <row>
6609 <entry> <literal>\</literal><replaceable>k</replaceable> </entry>
6610 <entry> (where <replaceable>k</replaceable> is a non-alphanumeric character)
6611 matches that character taken as an ordinary character,
6612 e.g., <literal>\\</literal> matches a backslash character </entry>
6613 </row>
6614
6615 <row>
6616 <entry> <literal>\</literal><replaceable>c</replaceable> </entry>
6617 <entry> where <replaceable>c</replaceable> is alphanumeric
6618 (possibly followed by other characters)
6619 is an <firstterm>escape</firstterm>, see <xref linkend="posix-escape-sequences"/>
6620 (AREs only; in EREs and BREs, this matches <replaceable>c</replaceable>) </entry>
6621 </row>
6622
6623 <row>
6624 <entry> <literal>{</literal> </entry>
6625 <entry> when followed by a character other than a digit,
6626 matches the left-brace character <literal>{</literal>;
6627 when followed by a digit, it is the beginning of a
6628 <replaceable>bound</replaceable> (see below) </entry>
6629 </row>
6630
6631 <row>
6632 <entry> <replaceable>x</replaceable> </entry>
6633 <entry> where <replaceable>x</replaceable> is a single character with no other
6634 significance, matches that character </entry>
6635 </row>
6636 </tbody>
6637 </tgroup>
6638 </table>
6639
6640 <para>
6641 An RE cannot end with a backslash (<literal>\</literal>).
6642 </para>
6643
6644 <note>
6645 <para>
6646 If you have <xref linkend="guc-standard-conforming-strings"/> turned off,
6647 any backslashes you write in literal string constants will need to be
6648 doubled. See <xref linkend="sql-syntax-strings"/> for more information.
6649 </para>
6650 </note>
6651
6652 <table id="posix-quantifiers-table">
6653 <title>Regular Expression Quantifiers</title>
6654
6655 <tgroup cols="2">
6656 <thead>
6657 <row>
6658 <entry>Quantifier</entry>
6659 <entry>Matches</entry>
6660 </row>
6661 </thead>
6662
6663 <tbody>
6664 <row>
6665 <entry> <literal>*</literal> </entry>
6666 <entry> a sequence of 0 or more matches of the atom </entry>
6667 </row>
6668
6669 <row>
6670 <entry> <literal>+</literal> </entry>
6671 <entry> a sequence of 1 or more matches of the atom </entry>
6672 </row>
6673
6674 <row>
6675 <entry> <literal>?</literal> </entry>
6676 <entry> a sequence of 0 or 1 matches of the atom </entry>
6677 </row>
6678
6679 <row>
6680 <entry> <literal>{</literal><replaceable>m</replaceable><literal>}</literal> </entry>
6681 <entry> a sequence of exactly <replaceable>m</replaceable> matches of the atom </entry>
6682 </row>
6683
6684 <row>
6685 <entry> <literal>{</literal><replaceable>m</replaceable><literal>,}</literal> </entry>
6686 <entry> a sequence of <replaceable>m</replaceable> or more matches of the atom </entry>
6687 </row>
6688
6689 <row>
6690 <entry>
6691 <literal>{</literal><replaceable>m</replaceable><literal>,</literal><replaceable>n</replaceable><literal>}</literal> </entry>
6692 <entry> a sequence of <replaceable>m</replaceable> through <replaceable>n</replaceable>
6693 (inclusive) matches of the atom; <replaceable>m</replaceable> cannot exceed
6694 <replaceable>n</replaceable> </entry>
6695 </row>
6696
6697 <row>
6698 <entry> <literal>*?</literal> </entry>
6699 <entry> non-greedy version of <literal>*</literal> </entry>
6700 </row>
6701
6702 <row>
6703 <entry> <literal>+?</literal> </entry>
6704 <entry> non-greedy version of <literal>+</literal> </entry>
6705 </row>
6706
6707 <row>
6708 <entry> <literal>??</literal> </entry>
6709 <entry> non-greedy version of <literal>?</literal> </entry>
6710 </row>
6711
6712 <row>
6713 <entry> <literal>{</literal><replaceable>m</replaceable><literal>}?</literal> </entry>
6714 <entry> non-greedy version of <literal>{</literal><replaceable>m</replaceable><literal>}</literal> </entry>
6715 </row>
6716
6717 <row>
6718 <entry> <literal>{</literal><replaceable>m</replaceable><literal>,}?</literal> </entry>
6719 <entry> non-greedy version of <literal>{</literal><replaceable>m</replaceable><literal>,}</literal> </entry>
6720 </row>
6721
6722 <row>
6723 <entry>
6724 <literal>{</literal><replaceable>m</replaceable><literal>,</literal><replaceable>n</replaceable><literal>}?</literal> </entry>
6725 <entry> non-greedy version of <literal>{</literal><replaceable>m</replaceable><literal>,</literal><replaceable>n</replaceable><literal>}</literal> </entry>
6726 </row>
6727 </tbody>
6728 </tgroup>
6729 </table>
6730
6731 <para>
6732 The forms using <literal>{</literal><replaceable>...</replaceable><literal>}</literal>
6733 are known as <firstterm>bounds</firstterm>.
6734 The numbers <replaceable>m</replaceable> and <replaceable>n</replaceable> within a bound are
6735 unsigned decimal integers with permissible values from 0 to 255 inclusive.
6736 </para>
6737
6738 <para>
6739 <firstterm>Non-greedy</firstterm> quantifiers (available in AREs only) match the
6740 same possibilities as their corresponding normal (<firstterm>greedy</firstterm>)
6741 counterparts, but prefer the smallest number rather than the largest
6742 number of matches.
6743 See <xref linkend="posix-matching-rules"/> for more detail.
6744 </para>
6745
6746 <note>
6747 <para>
6748 A quantifier cannot immediately follow another quantifier, e.g.,
6749 <literal>**</literal> is invalid.
6750 A quantifier cannot
6751 begin an expression or subexpression or follow
6752 <literal>^</literal> or <literal>|</literal>.
6753 </para>
6754 </note>
6755
6756 <table id="posix-constraints-table">
6757 <title>Regular Expression Constraints</title>
6758
6759 <tgroup cols="2">
6760 <thead>
6761 <row>
6762 <entry>Constraint</entry>
6763 <entry>Description</entry>
6764 </row>
6765 </thead>
6766
6767 <tbody>
6768 <row>
6769 <entry> <literal>^</literal> </entry>
6770 <entry> matches at the beginning of the string </entry>
6771 </row>
6772
6773 <row>
6774 <entry> <literal>$</literal> </entry>
6775 <entry> matches at the end of the string </entry>
6776 </row>
6777
6778 <row>
6779 <entry> <literal>(?=</literal><replaceable>re</replaceable><literal>)</literal> </entry>
6780 <entry> <firstterm>positive lookahead</firstterm> matches at any point
6781 where a substring matching <replaceable>re</replaceable> begins
6782 (AREs only) </entry>
6783 </row>
6784
6785 <row>
6786 <entry> <literal>(?!</literal><replaceable>re</replaceable><literal>)</literal> </entry>
6787 <entry> <firstterm>negative lookahead</firstterm> matches at any point
6788 where no substring matching <replaceable>re</replaceable> begins
6789 (AREs only) </entry>
6790 </row>
6791
6792 <row>
6793 <entry> <literal>(?&lt;=</literal><replaceable>re</replaceable><literal>)</literal> </entry>
6794 <entry> <firstterm>positive lookbehind</firstterm> matches at any point
6795 where a substring matching <replaceable>re</replaceable> ends
6796 (AREs only) </entry>
6797 </row>
6798
6799 <row>
6800 <entry> <literal>(?&lt;!</literal><replaceable>re</replaceable><literal>)</literal> </entry>
6801 <entry> <firstterm>negative lookbehind</firstterm> matches at any point
6802 where no substring matching <replaceable>re</replaceable> ends
6803 (AREs only) </entry>
6804 </row>
6805 </tbody>
6806 </tgroup>
6807 </table>
6808
6809 <para>
6810 Lookahead and lookbehind constraints cannot contain <firstterm>back
6811 references</firstterm> (see <xref linkend="posix-escape-sequences"/>),
6812 and all parentheses within them are considered non-capturing.
6813 </para>
6814 </sect3>
6815
6816 <sect3 id="posix-bracket-expressions">
6817 <title>Bracket Expressions</title>
6818
6819 <para>
6820 A <firstterm>bracket expression</firstterm> is a list of
6821 characters enclosed in <literal>[]</literal>. It normally matches
6822 any single character from the list (but see below). If the list
6823 begins with <literal>^</literal>, it matches any single character
6824 <emphasis>not</emphasis> from the rest of the list.
6825 If two characters
6826 in the list are separated by <literal>-</literal>, this is
6827 shorthand for the full range of characters between those two
6828 (inclusive) in the collating sequence,
6829 e.g., <literal>[0-9]</literal> in <acronym>ASCII</acronym> matches
6830 any decimal digit. It is illegal for two ranges to share an
6831 endpoint, e.g., <literal>a-c-e</literal>. Ranges are very
6832 collating-sequence-dependent, so portable programs should avoid
6833 relying on them.
6834 </para>
6835
6836 <para>
6837 To include a literal <literal>]</literal> in the list, make it the
6838 first character (after <literal>^</literal>, if that is used). To
6839 include a literal <literal>-</literal>, make it the first or last
6840 character, or the second endpoint of a range. To use a literal
6841 <literal>-</literal> as the first endpoint of a range, enclose it
6842 in <literal>[.</literal> and <literal>.]</literal> to make it a
6843 collating element (see below). With the exception of these characters,
6844 some combinations using <literal>[</literal>
6845 (see next paragraphs), and escapes (AREs only), all other special
6846 characters lose their special significance within a bracket expression.
6847 In particular, <literal>\</literal> is not special when following
6848 ERE or BRE rules, though it is special (as introducing an escape)
6849 in AREs.
6850 </para>
6851
6852 <para>
6853 Within a bracket expression, a collating element (a character, a
6854 multiple-character sequence that collates as if it were a single
6855 character, or a collating-sequence name for either) enclosed in
6856 <literal>[.</literal> and <literal>.]</literal> stands for the
6857 sequence of characters of that collating element. The sequence is
6858 treated as a single element of the bracket expression's list. This
6859 allows a bracket
6860 expression containing a multiple-character collating element to
6861 match more than one character, e.g., if the collating sequence
6862 includes a <literal>ch</literal> collating element, then the RE
6863 <literal>[[.ch.]]*c</literal> matches the first five characters of
6864 <literal>chchcc</literal>.
6865 </para>
6866
6867 <note>
6868 <para>
6869 <productname>PostgreSQL</productname> currently does not support multi-character collating
6870 elements. This information describes possible future behavior.
6871 </para>
6872 </note>
6873
6874 <para>
6875 Within a bracket expression, a collating element enclosed in
6876 <literal>[=</literal> and <literal>=]</literal> is an <firstterm>equivalence
6877 class</firstterm>, standing for the sequences of characters of all collating
6878 elements equivalent to that one, including itself. (If there are
6879 no other equivalent collating elements, the treatment is as if the
6880 enclosing delimiters were <literal>[.</literal> and
6881 <literal>.]</literal>.) For example, if <literal>o</literal> and
6882 <literal>^</literal> are the members of an equivalence class, then
6883 <literal>[[=o=]]</literal>, <literal>[[=^=]]</literal>, and
6884 <literal>[o^]</literal> are all synonymous. An equivalence class
6885 cannot be an endpoint of a range.
6886 </para>
6887
6888 <para>
6889 Within a bracket expression, the name of a character class
6890 enclosed in <literal>[:</literal> and <literal>:]</literal> stands
6891 for the list of all characters belonging to that class. A character
6892 class cannot be used as an endpoint of a range.
6893 The <acronym>POSIX</acronym> standard defines these character class
6894 names:
6895 <literal>alnum</literal> (letters and numeric digits),
6896 <literal>alpha</literal> (letters),
6897 <literal>blank</literal> (space and tab),
6898 <literal>cntrl</literal> (control characters),
6899 <literal>digit</literal> (numeric digits),
6900 <literal>graph</literal> (printable characters except space),
6901 <literal>lower</literal> (lower-case letters),
6902 <literal>print</literal> (printable characters including space),
6903 <literal>punct</literal> (punctuation),
6904 <literal>space</literal> (any white space),
6905 <literal>upper</literal> (upper-case letters),
6906 and <literal>xdigit</literal> (hexadecimal digits).
6907 The behavior of these standard character classes is generally
6908 consistent across platforms for characters in the 7-bit ASCII set.
6909 Whether a given non-ASCII character is considered to belong to one
6910 of these classes depends on the <firstterm>collation</firstterm>
6911 that is used for the regular-expression function or operator
6912 (see <xref linkend="collation"/>), or by default on the
6913 database's <envar>LC_CTYPE</envar> locale setting (see
6914 <xref linkend="locale"/>). The classification of non-ASCII
6915 characters can vary across platforms even in similarly-named
6916 locales. (But the <literal>C</literal> locale never considers any
6917 non-ASCII characters to belong to any of these classes.)
6918 In addition to these standard character
6919 classes, <productname>PostgreSQL</productname> defines
6920 the <literal>word</literal> character class, which is the same as
6921 <literal>alnum</literal> plus the underscore (<literal>_</literal>)
6922 character, and
6923 the <literal>ascii</literal> character class, which contains exactly
6924 the 7-bit ASCII set.
6925 </para>
6926
6927 <para>
6928 There are two special cases of bracket expressions: the bracket
6929 expressions <literal>[[:&lt;:]]</literal> and
6930 <literal>[[:&gt;:]]</literal> are constraints,
6931 matching empty strings at the beginning
6932 and end of a word respectively. A word is defined as a sequence
6933 of word characters that is neither preceded nor followed by word
6934 characters. A word character is any character belonging to the
6935 <literal>word</literal> character class, that is, any letter, digit,
6936 or underscore. This is an extension, compatible with but not
6937 specified by <acronym>POSIX</acronym> 1003.2, and should be used with
6938 caution in software intended to be portable to other systems.
6939 The constraint escapes described below are usually preferable; they
6940 are no more standard, but are easier to type.
6941 </para>
6942 </sect3>
6943
6944 <sect3 id="posix-escape-sequences">
6945 <title>Regular Expression Escapes</title>
6946
6947 <para>
6948 <firstterm>Escapes</firstterm> are special sequences beginning with <literal>\</literal>
6949 followed by an alphanumeric character. Escapes come in several varieties:
6950 character entry, class shorthands, constraint escapes, and back references.
6951 A <literal>\</literal> followed by an alphanumeric character but not constituting
6952 a valid escape is illegal in AREs.
6953 In EREs, there are no escapes: outside a bracket expression,
6954 a <literal>\</literal> followed by an alphanumeric character merely stands for
6955 that character as an ordinary character, and inside a bracket expression,
6956 <literal>\</literal> is an ordinary character.
6957 (The latter is the one actual incompatibility between EREs and AREs.)
6958 </para>
6959
6960 <para>
6961 <firstterm>Character-entry escapes</firstterm> exist to make it easier to specify
6962 non-printing and other inconvenient characters in REs. They are
6963 shown in <xref linkend="posix-character-entry-escapes-table"/>.
6964 </para>
6965
6966 <para>
6967 <firstterm>Class-shorthand escapes</firstterm> provide shorthands for certain
6968 commonly-used character classes. They are
6969 shown in <xref linkend="posix-class-shorthand-escapes-table"/>.
6970 </para>
6971
6972 <para>
6973 A <firstterm>constraint escape</firstterm> is a constraint,
6974 matching the empty string if specific conditions are met,
6975 written as an escape. They are
6976 shown in <xref linkend="posix-constraint-escapes-table"/>.
6977 </para>
6978
6979 <para>
6980 A <firstterm>back reference</firstterm> (<literal>\</literal><replaceable>n</replaceable>) matches the
6981 same string matched by the previous parenthesized subexpression specified
6982 by the number <replaceable>n</replaceable>
6983 (see <xref linkend="posix-constraint-backref-table"/>). For example,
6984 <literal>([bc])\1</literal> matches <literal>bb</literal> or <literal>cc</literal>
6985 but not <literal>bc</literal> or <literal>cb</literal>.
6986 The subexpression must entirely precede the back reference in the RE.
6987 Subexpressions are numbered in the order of their leading parentheses.
6988 Non-capturing parentheses do not define subexpressions.
6989 The back reference considers only the string characters matched by the
6990 referenced subexpression, not any constraints contained in it. For
6991 example, <literal>(^\d)\1</literal> will match <literal>22</literal>.
6992 </para>
6993
6994 <table id="posix-character-entry-escapes-table">
6995 <title>Regular Expression Character-Entry Escapes</title>
6996
6997 <tgroup cols="2">
6998 <thead>
6999 <row>
7000 <entry>Escape</entry>
7001 <entry>Description</entry>
7002 </row>
7003 </thead>
7004
7005 <tbody>
7006 <row>
7007 <entry> <literal>\a</literal> </entry>
7008 <entry> alert (bell) character, as in C </entry>
7009 </row>
7010
7011 <row>
7012 <entry> <literal>\b</literal> </entry>
7013 <entry> backspace, as in C </entry>
7014 </row>
7015
7016 <row>
7017 <entry> <literal>\B</literal> </entry>
7018 <entry> synonym for backslash (<literal>\</literal>) to help reduce the need for backslash
7019 doubling </entry>
7020 </row>
7021
7022 <row>
7023 <entry> <literal>\c</literal><replaceable>X</replaceable> </entry>
7024 <entry> (where <replaceable>X</replaceable> is any character) the character whose
7025 low-order 5 bits are the same as those of
7026 <replaceable>X</replaceable>, and whose other bits are all zero </entry>
7027 </row>
7028
7029 <row>
7030 <entry> <literal>\e</literal> </entry>
7031 <entry> the character whose collating-sequence name
7032 is <literal>ESC</literal>,
7033 or failing that, the character with octal value <literal>033</literal> </entry>
7034 </row>
7035
7036 <row>
7037 <entry> <literal>\f</literal> </entry>
7038 <entry> form feed, as in C </entry>
7039 </row>
7040
7041 <row>
7042 <entry> <literal>\n</literal> </entry>
7043 <entry> newline, as in C </entry>
7044 </row>
7045
7046 <row>
7047 <entry> <literal>\r</literal> </entry>
7048 <entry> carriage return, as in C </entry>
7049 </row>
7050
7051 <row>
7052 <entry> <literal>\t</literal> </entry>
7053 <entry> horizontal tab, as in C </entry>
7054 </row>
7055
7056 <row>
7057 <entry> <literal>\u</literal><replaceable>wxyz</replaceable> </entry>
7058 <entry> (where <replaceable>wxyz</replaceable> is exactly four hexadecimal digits)
7059 the character whose hexadecimal value is
7060 <literal>0x</literal><replaceable>wxyz</replaceable>
7061 </entry>
7062 </row>
7063
7064 <row>
7065 <entry> <literal>\U</literal><replaceable>stuvwxyz</replaceable> </entry>
7066 <entry> (where <replaceable>stuvwxyz</replaceable> is exactly eight hexadecimal
7067 digits)
7068 the character whose hexadecimal value is
7069 <literal>0x</literal><replaceable>stuvwxyz</replaceable>
7070 </entry>
7071 </row>
7072
7073 <row>
7074 <entry> <literal>\v</literal> </entry>
7075 <entry> vertical tab, as in C </entry>
7076 </row>
7077
7078 <row>
7079 <entry> <literal>\x</literal><replaceable>hhh</replaceable> </entry>
7080 <entry> (where <replaceable>hhh</replaceable> is any sequence of hexadecimal
7081 digits)
7082 the character whose hexadecimal value is
7083 <literal>0x</literal><replaceable>hhh</replaceable>
7084 (a single character no matter how many hexadecimal digits are used)
7085 </entry>
7086 </row>
7087
7088 <row>
7089 <entry> <literal>\0</literal> </entry>
7090 <entry> the character whose value is <literal>0</literal> (the null byte)</entry>
7091 </row>
7092
7093 <row>
7094 <entry> <literal>\</literal><replaceable>xy</replaceable> </entry>
7095 <entry> (where <replaceable>xy</replaceable> is exactly two octal digits,
7096 and is not a <firstterm>back reference</firstterm>)
7097 the character whose octal value is
7098 <literal>0</literal><replaceable>xy</replaceable> </entry>
7099 </row>
7100
7101 <row>
7102 <entry> <literal>\</literal><replaceable>xyz</replaceable> </entry>
7103 <entry> (where <replaceable>xyz</replaceable> is exactly three octal digits,
7104 and is not a <firstterm>back reference</firstterm>)
7105 the character whose octal value is
7106 <literal>0</literal><replaceable>xyz</replaceable> </entry>
7107 </row>
7108 </tbody>
7109 </tgroup>
7110 </table>
7111
7112 <para>
7113 Hexadecimal digits are <literal>0</literal>-<literal>9</literal>,
7114 <literal>a</literal>-<literal>f</literal>, and <literal>A</literal>-<literal>F</literal>.
7115 Octal digits are <literal>0</literal>-<literal>7</literal>.
7116 </para>
7117
7118 <para>
7119 Numeric character-entry escapes specifying values outside the ASCII range
7120 (0&ndash;127) have meanings dependent on the database encoding. When the
7121 encoding is UTF-8, escape values are equivalent to Unicode code points,
7122 for example <literal>\u1234</literal> means the character <literal>U+1234</literal>.
7123 For other multibyte encodings, character-entry escapes usually just
7124 specify the concatenation of the byte values for the character. If the
7125 escape value does not correspond to any legal character in the database
7126 encoding, no error will be raised, but it will never match any data.
7127 </para>
7128
7129 <para>
7130 The character-entry escapes are always taken as ordinary characters.
7131 For example, <literal>\135</literal> is <literal>]</literal> in ASCII, but
7132 <literal>\135</literal> does not terminate a bracket expression.
7133 </para>
7134
7135 <table id="posix-class-shorthand-escapes-table">
7136 <title>Regular Expression Class-Shorthand Escapes</title>
7137
7138 <tgroup cols="2">
7139 <thead>
7140 <row>
7141 <entry>Escape</entry>
7142 <entry>Description</entry>
7143 </row>
7144 </thead>
7145
7146 <tbody>
7147 <row>
7148 <entry> <literal>\d</literal> </entry>
7149 <entry> matches any digit, like
7150 <literal>[[:digit:]]</literal> </entry>
7151 </row>
7152
7153 <row>
7154 <entry> <literal>\s</literal> </entry>
7155 <entry> matches any whitespace character, like
7156 <literal>[[:space:]]</literal> </entry>
7157 </row>
7158
7159 <row>
7160 <entry> <literal>\w</literal> </entry>
7161 <entry> matches any word character, like
7162 <literal>[[:word:]]</literal> </entry>
7163 </row>
7164
7165 <row>
7166 <entry> <literal>\D</literal> </entry>
7167 <entry> matches any non-digit, like
7168 <literal>[^[:digit:]]</literal> </entry>
7169 </row>
7170
7171 <row>
7172 <entry> <literal>\S</literal> </entry>
7173 <entry> matches any non-whitespace character, like
7174 <literal>[^[:space:]]</literal> </entry>
7175 </row>
7176
7177 <row>
7178 <entry> <literal>\W</literal> </entry>
7179 <entry> matches any non-word character, like
7180 <literal>[^[:word:]]</literal> </entry>
7181 </row>
7182 </tbody>
7183 </tgroup>
7184 </table>
7185
7186 <para>
7187 The class-shorthand escapes also work within bracket expressions,
7188 although the definitions shown above are not quite syntactically
7189 valid in that context.
7190 For example, <literal>[a-c\d]</literal> is equivalent to
7191 <literal>[a-c[:digit:]]</literal>.
7192 </para>
7193
7194 <table id="posix-constraint-escapes-table">
7195 <title>Regular Expression Constraint Escapes</title>
7196
7197 <tgroup cols="2">
7198 <thead>
7199 <row>
7200 <entry>Escape</entry>
7201 <entry>Description</entry>
7202 </row>
7203 </thead>
7204
7205 <tbody>
7206 <row>
7207 <entry> <literal>\A</literal> </entry>
7208 <entry> matches only at the beginning of the string
7209 (see <xref linkend="posix-matching-rules"/> for how this differs from
7210 <literal>^</literal>) </entry>
7211 </row>
7212
7213 <row>
7214 <entry> <literal>\m</literal> </entry>
7215 <entry> matches only at the beginning of a word </entry>
7216 </row>
7217
7218 <row>
7219 <entry> <literal>\M</literal> </entry>
7220 <entry> matches only at the end of a word </entry>
7221 </row>
7222
7223 <row>
7224 <entry> <literal>\y</literal> </entry>
7225 <entry> matches only at the beginning or end of a word </entry>
7226 </row>
7227
7228 <row>
7229 <entry> <literal>\Y</literal> </entry>
7230 <entry> matches only at a point that is not the beginning or end of a
7231 word </entry>
7232 </row>
7233
7234 <row>
7235 <entry> <literal>\Z</literal> </entry>
7236 <entry> matches only at the end of the string
7237 (see <xref linkend="posix-matching-rules"/> for how this differs from
7238 <literal>$</literal>) </entry>
7239 </row>
7240 </tbody>
7241 </tgroup>
7242 </table>
7243
7244 <para>
7245 A word is defined as in the specification of
7246 <literal>[[:&lt;:]]</literal> and <literal>[[:&gt;:]]</literal> above.
7247 Constraint escapes are illegal within bracket expressions.
7248 </para>
7249
7250 <table id="posix-constraint-backref-table">
7251 <title>Regular Expression Back References</title>
7252
7253 <tgroup cols="2">
7254 <thead>
7255 <row>
7256 <entry>Escape</entry>
7257 <entry>Description</entry>
7258 </row>
7259 </thead>
7260
7261 <tbody>
7262 <row>
7263 <entry> <literal>\</literal><replaceable>m</replaceable> </entry>
7264 <entry> (where <replaceable>m</replaceable> is a nonzero digit)
7265 a back reference to the <replaceable>m</replaceable>'th subexpression </entry>
7266 </row>
7267
7268 <row>
7269 <entry> <literal>\</literal><replaceable>mnn</replaceable> </entry>
7270 <entry> (where <replaceable>m</replaceable> is a nonzero digit, and
7271 <replaceable>nn</replaceable> is some more digits, and the decimal value
7272 <replaceable>mnn</replaceable> is not greater than the number of closing capturing
7273 parentheses seen so far)
7274 a back reference to the <replaceable>mnn</replaceable>'th subexpression </entry>
7275 </row>
7276 </tbody>
7277 </tgroup>
7278 </table>
7279
7280 <note>
7281 <para>
7282 There is an inherent ambiguity between octal character-entry
7283 escapes and back references, which is resolved by the following heuristics,
7284 as hinted at above.
7285 A leading zero always indicates an octal escape.
7286 A single non-zero digit, not followed by another digit,
7287 is always taken as a back reference.
7288 A multi-digit sequence not starting with a zero is taken as a back
7289 reference if it comes after a suitable subexpression
7290 (i.e., the number is in the legal range for a back reference),
7291 and otherwise is taken as octal.
7292 </para>
7293 </note>
7294 </sect3>
7295
7296 <sect3 id="posix-metasyntax">
7297 <title>Regular Expression Metasyntax</title>
7298
7299 <para>
7300 In addition to the main syntax described above, there are some special
7301 forms and miscellaneous syntactic facilities available.
7302 </para>
7303
7304 <para>
7305 An RE can begin with one of two special <firstterm>director</firstterm> prefixes.
7306 If an RE begins with <literal>***:</literal>,
7307 the rest of the RE is taken as an ARE. (This normally has no effect in
7308 <productname>PostgreSQL</productname>, since REs are assumed to be AREs;
7309 but it does have an effect if ERE or BRE mode had been specified by
7310 the <replaceable>flags</replaceable> parameter to a regex function.)
7311 If an RE begins with <literal>***=</literal>,
7312 the rest of the RE is taken to be a literal string,
7313 with all characters considered ordinary characters.
7314 </para>
7315
7316 <para>
7317 An ARE can begin with <firstterm>embedded options</firstterm>:
7318 a sequence <literal>(?</literal><replaceable>xyz</replaceable><literal>)</literal>
7319 (where <replaceable>xyz</replaceable> is one or more alphabetic characters)
7320 specifies options affecting the rest of the RE.
7321 These options override any previously determined options &mdash;
7322 in particular, they can override the case-sensitivity behavior implied by
7323 a regex operator, or the <replaceable>flags</replaceable> parameter to a regex
7324 function.
7325 The available option letters are
7326 shown in <xref linkend="posix-embedded-options-table"/>.
7327 Note that these same option letters are used in the <replaceable>flags</replaceable>
7328 parameters of regex functions.
7329 </para>
7330
7331 <table id="posix-embedded-options-table">
7332 <title>ARE Embedded-Option Letters</title>
7333
7334 <tgroup cols="2">
7335 <thead>
7336 <row>
7337 <entry>Option</entry>
7338 <entry>Description</entry>
7339 </row>
7340 </thead>
7341
7342 <tbody>
7343 <row>
7344 <entry> <literal>b</literal> </entry>
7345 <entry> rest of RE is a BRE </entry>
7346 </row>
7347
7348 <row>
7349 <entry> <literal>c</literal> </entry>
7350 <entry> case-sensitive matching (overrides operator type) </entry>
7351 </row>
7352
7353 <row>
7354 <entry> <literal>e</literal> </entry>
7355 <entry> rest of RE is an ERE </entry>
7356 </row>
7357
7358 <row>
7359 <entry> <literal>i</literal> </entry>
7360 <entry> case-insensitive matching (see
7361 <xref linkend="posix-matching-rules"/>) (overrides operator type) </entry>
7362 </row>
7363
7364 <row>
7365 <entry> <literal>m</literal> </entry>
7366 <entry> historical synonym for <literal>n</literal> </entry>
7367 </row>
7368
7369 <row>
7370 <entry> <literal>n</literal> </entry>
7371 <entry> newline-sensitive matching (see
7372 <xref linkend="posix-matching-rules"/>) </entry>
7373 </row>
7374
7375 <row>
7376 <entry> <literal>p</literal> </entry>
7377 <entry> partial newline-sensitive matching (see
7378 <xref linkend="posix-matching-rules"/>) </entry>
7379 </row>
7380
7381 <row>
7382 <entry> <literal>q</literal> </entry>
7383 <entry> rest of RE is a literal (<quote>quoted</quote>) string, all ordinary
7384 characters </entry>
7385 </row>
7386
7387 <row>
7388 <entry> <literal>s</literal> </entry>
7389 <entry> non-newline-sensitive matching (default) </entry>
7390 </row>
7391
7392 <row>
7393 <entry> <literal>t</literal> </entry>
7394 <entry> tight syntax (default; see below) </entry>
7395 </row>
7396
7397 <row>
7398 <entry> <literal>w</literal> </entry>
7399 <entry> inverse partial newline-sensitive (<quote>weird</quote>) matching
7400 (see <xref linkend="posix-matching-rules"/>) </entry>
7401 </row>
7402
7403 <row>
7404 <entry> <literal>x</literal> </entry>
7405 <entry> expanded syntax (see below) </entry>
7406 </row>
7407 </tbody>
7408 </tgroup>
7409 </table>
7410
7411 <para>
7412 Embedded options take effect at the <literal>)</literal> terminating the sequence.
7413 They can appear only at the start of an ARE (after the
7414 <literal>***:</literal> director if any).
7415 </para>
7416
7417 <para>
7418 In addition to the usual (<firstterm>tight</firstterm>) RE syntax, in which all
7419 characters are significant, there is an <firstterm>expanded</firstterm> syntax,
7420 available by specifying the embedded <literal>x</literal> option.
7421 In the expanded syntax,
7422 white-space characters in the RE are ignored, as are
7423 all characters between a <literal>#</literal>
7424 and the following newline (or the end of the RE). This
7425 permits paragraphing and commenting a complex RE.
7426 There are three exceptions to that basic rule:
7427
7428 <itemizedlist>
7429 <listitem>
7430 <para>
7431 a white-space character or <literal>#</literal> preceded by <literal>\</literal> is
7432 retained
7433 </para>
7434 </listitem>
7435 <listitem>
7436 <para>
7437 white space or <literal>#</literal> within a bracket expression is retained
7438 </para>
7439 </listitem>
7440 <listitem>
7441 <para>
7442 white space and comments cannot appear within multi-character symbols,
7443 such as <literal>(?:</literal>
7444 </para>
7445 </listitem>
7446 </itemizedlist>
7447
7448 For this purpose, white-space characters are blank, tab, newline, and
7449 any character that belongs to the <replaceable>space</replaceable> character class.
7450 </para>
7451
7452 <para>
7453 Finally, in an ARE, outside bracket expressions, the sequence
7454 <literal>(?#</literal><replaceable>ttt</replaceable><literal>)</literal>
7455 (where <replaceable>ttt</replaceable> is any text not containing a <literal>)</literal>)
7456 is a comment, completely ignored.
7457 Again, this is not allowed between the characters of
7458 multi-character symbols, like <literal>(?:</literal>.
7459 Such comments are more a historical artifact than a useful facility,
7460 and their use is deprecated; use the expanded syntax instead.
7461 </para>
7462
7463 <para>
7464 <emphasis>None</emphasis> of these metasyntax extensions is available if
7465 an initial <literal>***=</literal> director
7466 has specified that the user's input be treated as a literal string
7467 rather than as an RE.
7468 </para>
7469 </sect3>
7470
7471 <sect3 id="posix-matching-rules">
7472 <title>Regular Expression Matching Rules</title>
7473
7474 <para>
7475 In the event that an RE could match more than one substring of a given
7476 string, the RE matches the one starting earliest in the string.
7477 If the RE could match more than one substring starting at that point,
7478 either the longest possible match or the shortest possible match will
7479 be taken, depending on whether the RE is <firstterm>greedy</firstterm> or
7480 <firstterm>non-greedy</firstterm>.
7481 </para>
7482
7483 <para>
7484 Whether an RE is greedy or not is determined by the following rules:
7485 <itemizedlist>
7486 <listitem>
7487 <para>
7488 Most atoms, and all constraints, have no greediness attribute (because
7489 they cannot match variable amounts of text anyway).
7490 </para>
7491 </listitem>
7492 <listitem>
7493 <para>
7494 Adding parentheses around an RE does not change its greediness.
7495 </para>
7496 </listitem>
7497 <listitem>
7498 <para>
7499 A quantified atom with a fixed-repetition quantifier
7500 (<literal>{</literal><replaceable>m</replaceable><literal>}</literal>
7501 or
7502 <literal>{</literal><replaceable>m</replaceable><literal>}?</literal>)
7503 has the same greediness (possibly none) as the atom itself.
7504 </para>
7505 </listitem>
7506 <listitem>
7507 <para>
7508 A quantified atom with other normal quantifiers (including
7509 <literal>{</literal><replaceable>m</replaceable><literal>,</literal><replaceable>n</replaceable><literal>}</literal>
7510 with <replaceable>m</replaceable> equal to <replaceable>n</replaceable>)
7511 is greedy (prefers longest match).
7512 </para>
7513 </listitem>
7514 <listitem>
7515 <para>
7516 A quantified atom with a non-greedy quantifier (including
7517 <literal>{</literal><replaceable>m</replaceable><literal>,</literal><replaceable>n</replaceable><literal>}?</literal>
7518 with <replaceable>m</replaceable> equal to <replaceable>n</replaceable>)
7519 is non-greedy (prefers shortest match).
7520 </para>
7521 </listitem>
7522 <listitem>
7523 <para>
7524 A branch &mdash; that is, an RE that has no top-level
7525 <literal>|</literal> operator &mdash; has the same greediness as the first
7526 quantified atom in it that has a greediness attribute.
7527 </para>
7528 </listitem>
7529 <listitem>
7530 <para>
7531 An RE consisting of two or more branches connected by the
7532 <literal>|</literal> operator is always greedy.
7533 </para>
7534 </listitem>
7535 </itemizedlist>
7536 </para>
7537
7538 <para>
7539 The above rules associate greediness attributes not only with individual
7540 quantified atoms, but with branches and entire REs that contain quantified
7541 atoms. What that means is that the matching is done in such a way that
7542 the branch, or whole RE, matches the longest or shortest possible
7543 substring <emphasis>as a whole</emphasis>. Once the length of the entire match
7544 is determined, the part of it that matches any particular subexpression
7545 is determined on the basis of the greediness attribute of that
7546 subexpression, with subexpressions starting earlier in the RE taking
7547 priority over ones starting later.
7548 </para>
7549
7550 <para>
7551 An example of what this means:
7552 <screen>
7553 SELECT SUBSTRING('XY1234Z', 'Y*([0-9]{1,3})');
7554 <lineannotation>Result: </lineannotation><computeroutput>123</computeroutput>
7555 SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{1,3})');
7556 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
7557 </screen>
7558 In the first case, the RE as a whole is greedy because <literal>Y*</literal>
7559 is greedy. It can match beginning at the <literal>Y</literal>, and it matches
7560 the longest possible string starting there, i.e., <literal>Y123</literal>.
7561 The output is the parenthesized part of that, or <literal>123</literal>.
7562 In the second case, the RE as a whole is non-greedy because <literal>Y*?</literal>
7563 is non-greedy. It can match beginning at the <literal>Y</literal>, and it matches
7564 the shortest possible string starting there, i.e., <literal>Y1</literal>.
7565 The subexpression <literal>[0-9]{1,3}</literal> is greedy but it cannot change
7566 the decision as to the overall match length; so it is forced to match
7567 just <literal>1</literal>.
7568 </para>
7569
7570 <para>
7571 In short, when an RE contains both greedy and non-greedy subexpressions,
7572 the total match length is either as long as possible or as short as
7573 possible, according to the attribute assigned to the whole RE. The
7574 attributes assigned to the subexpressions only affect how much of that
7575 match they are allowed to <quote>eat</quote> relative to each other.
7576 </para>
7577
7578 <para>
7579 The quantifiers <literal>{1,1}</literal> and <literal>{1,1}?</literal>
7580 can be used to force greediness or non-greediness, respectively,
7581 on a subexpression or a whole RE.
7582 This is useful when you need the whole RE to have a greediness attribute
7583 different from what's deduced from its elements. As an example,
7584 suppose that we are trying to separate a string containing some digits
7585 into the digits and the parts before and after them. We might try to
7586 do that like this:
7587 <screen>
7588 SELECT regexp_match('abc01234xyz', '(.*)(\d+)(.*)');
7589 <lineannotation>Result: </lineannotation><computeroutput>{abc0123,4,xyz}</computeroutput>
7590 </screen>
7591 That didn't work: the first <literal>.*</literal> is greedy so
7592 it <quote>eats</quote> as much as it can, leaving the <literal>\d+</literal> to
7593 match at the last possible place, the last digit. We might try to fix
7594 that by making it non-greedy:
7595 <screen>
7596 SELECT regexp_match('abc01234xyz', '(.*?)(\d+)(.*)');
7597 <lineannotation>Result: </lineannotation><computeroutput>{abc,0,""}</computeroutput>
7598 </screen>
7599 That didn't work either, because now the RE as a whole is non-greedy
7600 and so it ends the overall match as soon as possible. We can get what
7601 we want by forcing the RE as a whole to be greedy:
7602 <screen>
7603 SELECT regexp_match('abc01234xyz', '(?:(.*?)(\d+)(.*)){1,1}');
7604 <lineannotation>Result: </lineannotation><computeroutput>{abc,01234,xyz}</computeroutput>
7605 </screen>
7606 Controlling the RE's overall greediness separately from its components'
7607 greediness allows great flexibility in handling variable-length patterns.
7608 </para>
7609
7610 <para>
7611 When deciding what is a longer or shorter match,
7612 match lengths are measured in characters, not collating elements.
7613 An empty string is considered longer than no match at all.
7614 For example:
7615 <literal>bb*</literal>
7616 matches the three middle characters of <literal>abbbc</literal>;
7617 <literal>(week|wee)(night|knights)</literal>
7618 matches all ten characters of <literal>weeknights</literal>;
7619 when <literal>(.*).*</literal>
7620 is matched against <literal>abc</literal> the parenthesized subexpression
7621 matches all three characters; and when
7622 <literal>(a*)*</literal> is matched against <literal>bc</literal>
7623 both the whole RE and the parenthesized
7624 subexpression match an empty string.
7625 </para>
7626
7627 <para>
7628 If case-independent matching is specified,
7629 the effect is much as if all case distinctions had vanished from the
7630 alphabet.
7631 When an alphabetic that exists in multiple cases appears as an
7632 ordinary character outside a bracket expression, it is effectively
7633 transformed into a bracket expression containing both cases,
7634 e.g., <literal>x</literal> becomes <literal>[xX]</literal>.
7635 When it appears inside a bracket expression, all case counterparts
7636 of it are added to the bracket expression, e.g.,
7637 <literal>[x]</literal> becomes <literal>[xX]</literal>
7638 and <literal>[^x]</literal> becomes <literal>[^xX]</literal>.
7639 </para>
7640
7641 <para>
7642 If newline-sensitive matching is specified, <literal>.</literal>
7643 and bracket expressions using <literal>^</literal>
7644 will never match the newline character
7645 (so that matches will not cross lines unless the RE
7646 explicitly includes a newline)
7647 and <literal>^</literal> and <literal>$</literal>
7648 will match the empty string after and before a newline
7649 respectively, in addition to matching at beginning and end of string
7650 respectively.
7651 But the ARE escapes <literal>\A</literal> and <literal>\Z</literal>
7652 continue to match beginning or end of string <emphasis>only</emphasis>.
7653 Also, the character class shorthands <literal>\D</literal>
7654 and <literal>\W</literal> will match a newline regardless of this mode.
7655 (Before <productname>PostgreSQL</productname> 14, they did not match
7656 newlines when in newline-sensitive mode.
7657 Write <literal>[^[:digit:]]</literal>
7658 or <literal>[^[:word:]]</literal> to get the old behavior.)
7659 </para>
7660
7661 <para>
7662 If partial newline-sensitive matching is specified,
7663 this affects <literal>.</literal> and bracket expressions
7664 as with newline-sensitive matching, but not <literal>^</literal>
7665 and <literal>$</literal>.
7666 </para>
7667
7668 <para>
7669 If inverse partial newline-sensitive matching is specified,
7670 this affects <literal>^</literal> and <literal>$</literal>
7671 as with newline-sensitive matching, but not <literal>.</literal>
7672 and bracket expressions.
7673 This isn't very useful but is provided for symmetry.
7674 </para>
7675 </sect3>
7676
7677 <sect3 id="posix-limits-compatibility">
7678 <title>Limits and Compatibility</title>
7679
7680 <para>
7681 No particular limit is imposed on the length of REs in this
7682 implementation. However,
7683 programs intended to be highly portable should not employ REs longer
7684 than 256 bytes,
7685 as a POSIX-compliant implementation can refuse to accept such REs.
7686 </para>
7687
7688 <para>
7689 The only feature of AREs that is actually incompatible with
7690 POSIX EREs is that <literal>\</literal> does not lose its special
7691 significance inside bracket expressions.
7692 All other ARE features use syntax which is illegal or has
7693 undefined or unspecified effects in POSIX EREs;
7694 the <literal>***</literal> syntax of directors likewise is outside the POSIX
7695 syntax for both BREs and EREs.
7696 </para>
7697
7698 <para>
7699 Many of the ARE extensions are borrowed from Perl, but some have
7700 been changed to clean them up, and a few Perl extensions are not present.
7701 Incompatibilities of note include <literal>\b</literal>, <literal>\B</literal>,
7702 the lack of special treatment for a trailing newline,
7703 the addition of complemented bracket expressions to the things
7704 affected by newline-sensitive matching,
7705 the restrictions on parentheses and back references in lookahead/lookbehind
7706 constraints, and the longest/shortest-match (rather than first-match)
7707 matching semantics.
7708 </para>
7709 </sect3>
7710
7711 <sect3 id="posix-basic-regexes">
7712 <title>Basic Regular Expressions</title>
7713
7714 <para>
7715 BREs differ from EREs in several respects.
7716 In BREs, <literal>|</literal>, <literal>+</literal>, and <literal>?</literal>
7717 are ordinary characters and there is no equivalent
7718 for their functionality.
7719 The delimiters for bounds are
7720 <literal>\{</literal> and <literal>\}</literal>,
7721 with <literal>{</literal> and <literal>}</literal>
7722 by themselves ordinary characters.
7723 The parentheses for nested subexpressions are
7724 <literal>\(</literal> and <literal>\)</literal>,
7725 with <literal>(</literal> and <literal>)</literal> by themselves ordinary characters.
7726 <literal>^</literal> is an ordinary character except at the beginning of the
7727 RE or the beginning of a parenthesized subexpression,
7728 <literal>$</literal> is an ordinary character except at the end of the
7729 RE or the end of a parenthesized subexpression,
7730 and <literal>*</literal> is an ordinary character if it appears at the beginning
7731 of the RE or the beginning of a parenthesized subexpression
7732 (after a possible leading <literal>^</literal>).
7733 Finally, single-digit back references are available, and
7734 <literal>\&lt;</literal> and <literal>\&gt;</literal>
7735 are synonyms for
7736 <literal>[[:&lt;:]]</literal> and <literal>[[:&gt;:]]</literal>
7737 respectively; no other escapes are available in BREs.
7738 </para>
7739 </sect3>
7740
7741 <!-- end re_syntax.n man page -->
7742
7743 <sect3 id="posix-vs-xquery">
7744 <title>Differences from SQL Standard and XQuery</title>
7745
7746 <indexterm zone="posix-vs-xquery">
7747 <primary>LIKE_REGEX</primary>
7748 </indexterm>
7749
7750 <indexterm zone="posix-vs-xquery">
7751 <primary>OCCURRENCES_REGEX</primary>
7752 </indexterm>
7753
7754 <indexterm zone="posix-vs-xquery">
7755 <primary>POSITION_REGEX</primary>
7756 </indexterm>
7757
7758 <indexterm zone="posix-vs-xquery">
7759 <primary>SUBSTRING_REGEX</primary>
7760 </indexterm>
7761
7762 <indexterm zone="posix-vs-xquery">
7763 <primary>TRANSLATE_REGEX</primary>
7764 </indexterm>
7765
7766 <indexterm zone="posix-vs-xquery">
7767 <primary>XQuery regular expressions</primary>
7768 </indexterm>
7769
7770 <para>
7771 Since SQL:2008, the SQL standard includes regular expression operators
7772 and functions that performs pattern
7773 matching according to the XQuery regular expression
7774 standard:
7775 <itemizedlist>
7776 <listitem><para><literal>LIKE_REGEX</literal></para></listitem>
7777 <listitem><para><literal>OCCURRENCES_REGEX</literal></para></listitem>
7778 <listitem><para><literal>POSITION_REGEX</literal></para></listitem>
7779 <listitem><para><literal>SUBSTRING_REGEX</literal></para></listitem>
7780 <listitem><para><literal>TRANSLATE_REGEX</literal></para></listitem>
7781 </itemizedlist>
7782 <productname>PostgreSQL</productname> does not currently implement these
7783 operators and functions. You can get approximately equivalent
7784 functionality in each case as shown in <xref
7785 linkend="functions-regexp-sql-table"/>. (Various optional clauses on
7786 both sides have been omitted in this table.)
7787 </para>
7788
7789 <table id="functions-regexp-sql-table">
7790 <title>Regular Expression Functions Equivalencies</title>
7791
7792 <tgroup cols="2">
7793 <thead>
7794 <row>
7795 <entry>SQL standard</entry>
7796 <entry><productname>PostgreSQL</productname></entry>
7797 </row>
7798 </thead>
7799
7800 <tbody>
7801 <row>
7802 <entry><literal><replaceable>string</replaceable> LIKE_REGEX <replaceable>pattern</replaceable></literal></entry>
7803 <entry><literal>regexp_like(<replaceable>string</replaceable>, <replaceable>pattern</replaceable>)</literal> or <literal><replaceable>string</replaceable> ~ <replaceable>pattern</replaceable></literal></entry>
7804 </row>
7805
7806 <row>
7807 <entry><literal>OCCURRENCES_REGEX(<replaceable>pattern</replaceable> IN <replaceable>string</replaceable>)</literal></entry>
7808 <entry><literal>regexp_count(<replaceable>string</replaceable>, <replaceable>pattern</replaceable>)</literal></entry>
7809 </row>
7810
7811 <row>
7812 <entry><literal>POSITION_REGEX(<replaceable>pattern</replaceable> IN <replaceable>string</replaceable>)</literal></entry>
7813 <entry><literal>regexp_instr(<replaceable>string</replaceable>, <replaceable>pattern</replaceable>)</literal></entry>
7814 </row>
7815
7816 <row>
7817 <entry><literal>SUBSTRING_REGEX(<replaceable>pattern</replaceable> IN <replaceable>string</replaceable>)</literal></entry>
7818 <entry><literal>regexp_substr(<replaceable>string</replaceable>, <replaceable>pattern</replaceable>)</literal></entry>
7819 </row>
7820
7821 <row>
7822 <entry><literal>TRANSLATE_REGEX(<replaceable>pattern</replaceable> IN <replaceable>string</replaceable> WITH <replaceable>replacement</replaceable>)</literal></entry>
7823 <entry><literal>regexp_replace(<replaceable>string</replaceable>, <replaceable>pattern</replaceable>, <replaceable>replacement</replaceable>)</literal></entry>
7824 </row>
7825 </tbody>
7826 </tgroup>
7827 </table>
7828
7829 <para>
7830 Regular expression functions similar to those provided by PostgreSQL are
7831 also available in a number of other SQL implementations, whereas the
7832 SQL-standard functions are not as widely implemented. Some of the
7833 details of the regular expression syntax will likely differ in each
7834 implementation.
7835 </para>
7836
7837 <para>
7838 The SQL-standard operators and functions use XQuery regular expressions,
7839 which are quite close to the ARE syntax described above.
7840 Notable differences between the existing POSIX-based
7841 regular-expression feature and XQuery regular expressions include:
7842
7843 <itemizedlist>
7844 <listitem>
7845 <para>
7846 XQuery character class subtraction is not supported. An example of
7847 this feature is using the following to match only English
7848 consonants: <literal>[a-z-[aeiou]]</literal>.
7849 </para>
7850 </listitem>
7851 <listitem>
7852 <para>
7853 XQuery character class shorthands <literal>\c</literal>,
7854 <literal>\C</literal>, <literal>\i</literal>,
7855 and <literal>\I</literal> are not supported.
7856 </para>
7857 </listitem>
7858 <listitem>
7859 <para>
7860 XQuery character class elements
7861 using <literal>\p{UnicodeProperty}</literal> or the
7862 inverse <literal>\P{UnicodeProperty}</literal> are not supported.
7863 </para>
7864 </listitem>
7865 <listitem>
7866 <para>
7867 POSIX interprets character classes such as <literal>\w</literal>
7868 (see <xref linkend="posix-class-shorthand-escapes-table"/>)
7869 according to the prevailing locale (which you can control by
7870 attaching a <literal>COLLATE</literal> clause to the operator or
7871 function). XQuery specifies these classes by reference to Unicode
7872 character properties, so equivalent behavior is obtained only with
7873 a locale that follows the Unicode rules.
7874 </para>
7875 </listitem>
7876 <listitem>
7877 <para>
7878 The SQL standard (not XQuery itself) attempts to cater for more
7879 variants of <quote>newline</quote> than POSIX does. The
7880 newline-sensitive matching options described above consider only
7881 ASCII NL (<literal>\n</literal>) to be a newline, but SQL would have
7882 us treat CR (<literal>\r</literal>), CRLF (<literal>\r\n</literal>)
7883 (a Windows-style newline), and some Unicode-only characters like
7884 LINE SEPARATOR (U+2028) as newlines as well.
7885 Notably, <literal>.</literal> and <literal>\s</literal> should
7886 count <literal>\r\n</literal> as one character not two according to
7887 SQL.
7888 </para>
7889 </listitem>
7890 <listitem>
7891 <para>
7892 Of the character-entry escapes described in
7893 <xref linkend="posix-character-entry-escapes-table"/>,
7894 XQuery supports only <literal>\n</literal>, <literal>\r</literal>,
7895 and <literal>\t</literal>.
7896 </para>
7897 </listitem>
7898 <listitem>
7899 <para>
7900 XQuery does not support
7901 the <literal>[:<replaceable>name</replaceable>:]</literal> syntax
7902 for character classes within bracket expressions.
7903 </para>
7904 </listitem>
7905 <listitem>
7906 <para>
7907 XQuery does not have lookahead or lookbehind constraints,
7908 nor any of the constraint escapes described in
7909 <xref linkend="posix-constraint-escapes-table"/>.
7910 </para>
7911 </listitem>
7912 <listitem>
7913 <para>
7914 The metasyntax forms described in <xref linkend="posix-metasyntax"/>
7915 do not exist in XQuery.
7916 </para>
7917 </listitem>
7918 <listitem>
7919 <para>
7920 The regular expression flag letters defined by XQuery are
7921 related to but not the same as the option letters for POSIX
7922 (<xref linkend="posix-embedded-options-table"/>). While the
7923 <literal>i</literal> and <literal>q</literal> options behave the
7924 same, others do not:
7925 <itemizedlist>
7926 <listitem>
7927 <para>
7928 XQuery's <literal>s</literal> (allow dot to match newline)
7929 and <literal>m</literal> (allow <literal>^</literal>
7930 and <literal>$</literal> to match at newlines) flags provide
7931 access to the same behaviors as
7932 POSIX's <literal>n</literal>, <literal>p</literal>
7933 and <literal>w</literal> flags, but they
7934 do <emphasis>not</emphasis> match the behavior of
7935 POSIX's <literal>s</literal> and <literal>m</literal> flags.
7936 Note in particular that dot-matches-newline is the default
7937 behavior in POSIX but not XQuery.
7938 </para>
7939 </listitem>
7940 <listitem>
7941 <para>
7942 XQuery's <literal>x</literal> (ignore whitespace in pattern) flag
7943 is noticeably different from POSIX's expanded-mode flag.
7944 POSIX's <literal>x</literal> flag also
7945 allows <literal>#</literal> to begin a comment in the pattern,
7946 and POSIX will not ignore a whitespace character after a
7947 backslash.
7948 </para>
7949 </listitem>
7950 </itemizedlist>
7951 </para>
7952 </listitem>
7953 </itemizedlist>
7954 </para>
7955
7956 </sect3>
7957 </sect2>
7958 </sect1>
7959
7960
7961 <sect1 id="functions-formatting">
7962 <title>Data Type Formatting Functions</title>
7963
7964 <indexterm>
7965 <primary>formatting</primary>
7966 </indexterm>
7967
7968 <para>
7969 The <productname>PostgreSQL</productname> formatting functions
7970 provide a powerful set of tools for converting various data types
7971 (date/time, integer, floating point, numeric) to formatted strings
7972 and for converting from formatted strings to specific data types.
7973 <xref linkend="functions-formatting-table"/> lists them.
7974 These functions all follow a common calling convention: the first
7975 argument is the value to be formatted and the second argument is a
7976 template that defines the output or input format.
7977 </para>
7978
7979 <table id="functions-formatting-table">
7980 <title>Formatting Functions</title>
7981 <tgroup cols="1">
7982 <thead>
7983 <row>
7984 <entry role="func_table_entry"><para role="func_signature">
7985 Function
7986 </para>
7987 <para>
7988 Description
7989 </para>
7990 <para>
7991 Example(s)
7992 </para></entry>
7993 </row>
7994 </thead>
7995
7996 <tbody>
7997 <row>
7998 <entry role="func_table_entry"><para role="func_signature">
7999 <indexterm>
8000 <primary>to_char</primary>
8001 </indexterm>
8002 <function>to_char</function> ( <type>timestamp</type>, <type>text</type> )
8003 <returnvalue>text</returnvalue>
8004 </para>
8005 <para role="func_signature">
8006 <function>to_char</function> ( <type>timestamp with time zone</type>, <type>text</type> )
8007 <returnvalue>text</returnvalue>
8008 </para>
8009 <para>
8010 Converts time stamp to string according to the given format.
8011 </para>
8012 <para>
8013 <literal>to_char(timestamp '2002-04-20 17:31:12.66', 'HH12:MI:SS')</literal>
8014 <returnvalue>05:31:12</returnvalue>
8015 </para></entry>
8016 </row>
8017
8018 <row>
8019 <entry role="func_table_entry"><para role="func_signature">
8020 <function>to_char</function> ( <type>interval</type>, <type>text</type> )
8021 <returnvalue>text</returnvalue>
8022 </para>
8023 <para>
8024 Converts interval to string according to the given format.
8025 </para>
8026 <para>
8027 <literal>to_char(interval '15h 2m 12s', 'HH24:MI:SS')</literal>
8028 <returnvalue>15:02:12</returnvalue>
8029 </para></entry>
8030 </row>
8031
8032 <row>
8033 <entry role="func_table_entry"><para role="func_signature">
8034 <function>to_char</function> ( <replaceable>numeric_type</replaceable>, <type>text</type> )
8035 <returnvalue>text</returnvalue>
8036 </para>
8037 <para>
8038 Converts number to string according to the given format; available
8039 for <type>integer</type>, <type>bigint</type>, <type>numeric</type>,
8040 <type>real</type>, <type>double precision</type>.
8041 </para>
8042 <para>
8043 <literal>to_char(125, '999')</literal>
8044 <returnvalue>125</returnvalue>
8045 </para>
8046 <para>
8047 <literal>to_char(125.8::real, '999D9')</literal>
8048 <returnvalue>125.8</returnvalue>
8049 </para>
8050 <para>
8051 <literal>to_char(-125.8, '999D99S')</literal>
8052 <returnvalue>125.80-</returnvalue>
8053 </para></entry>
8054 </row>
8055
8056 <row>
8057 <entry role="func_table_entry"><para role="func_signature">
8058 <indexterm>
8059 <primary>to_date</primary>
8060 </indexterm>
8061 <function>to_date</function> ( <type>text</type>, <type>text</type> )
8062 <returnvalue>date</returnvalue>
8063 </para>
8064 <para>
8065 Converts string to date according to the given format.
8066 </para>
8067 <para>
8068 <literal>to_date('05 Dec 2000', 'DD Mon YYYY')</literal>
8069 <returnvalue>2000-12-05</returnvalue>
8070 </para></entry>
8071 </row>
8072
8073 <row>
8074 <entry role="func_table_entry"><para role="func_signature">
8075 <indexterm>
8076 <primary>to_number</primary>
8077 </indexterm>
8078 <function>to_number</function> ( <type>text</type>, <type>text</type> )
8079 <returnvalue>numeric</returnvalue>
8080 </para>
8081 <para>
8082 Converts string to numeric according to the given format.
8083 </para>
8084 <para>
8085 <literal>to_number('12,454.8-', '99G999D9S')</literal>
8086 <returnvalue>-12454.8</returnvalue>
8087 </para></entry>
8088 </row>
8089
8090 <row>
8091 <entry role="func_table_entry"><para role="func_signature">
8092 <indexterm>
8093 <primary>to_timestamp</primary>
8094 </indexterm>
8095 <function>to_timestamp</function> ( <type>text</type>, <type>text</type> )
8096 <returnvalue>timestamp with time zone</returnvalue>
8097 </para>
8098 <para>
8099 Converts string to time stamp according to the given format.
8100 (See also <function>to_timestamp(double precision)</function> in
8101 <xref linkend="functions-datetime-table"/>.)
8102 </para>
8103 <para>
8104 <literal>to_timestamp('05 Dec 2000', 'DD Mon YYYY')</literal>
8105 <returnvalue>2000-12-05 00:00:00-05</returnvalue>
8106 </para></entry>
8107 </row>
8108 </tbody>
8109 </tgroup>
8110 </table>
8111
8112 <tip>
8113 <para>
8114 <function>to_timestamp</function> and <function>to_date</function>
8115 exist to handle input formats that cannot be converted by
8116 simple casting. For most standard date/time formats, simply casting the
8117 source string to the required data type works, and is much easier.
8118 Similarly, <function>to_number</function> is unnecessary for standard numeric
8119 representations.
8120 </para>
8121 </tip>
8122
8123 <para>
8124 In a <function>to_char</function> output template string, there are certain
8125 patterns that are recognized and replaced with appropriately-formatted
8126 data based on the given value. Any text that is not a template pattern is
8127 simply copied verbatim. Similarly, in an input template string (for the
8128 other functions), template patterns identify the values to be supplied by
8129 the input data string. If there are characters in the template string
8130 that are not template patterns, the corresponding characters in the input
8131 data string are simply skipped over (whether or not they are equal to the
8132 template string characters).
8133 </para>
8134
8135 <para>
8136 <xref linkend="functions-formatting-datetime-table"/> shows the
8137 template patterns available for formatting date and time values.
8138 </para>
8139
8140 <table id="functions-formatting-datetime-table">
8141 <title>Template Patterns for Date/Time Formatting</title>
8142 <tgroup cols="2">
8143 <thead>
8144 <row>
8145 <entry>Pattern</entry>
8146 <entry>Description</entry>
8147 </row>
8148 </thead>
8149 <tbody>
8150 <row>
8151 <entry><literal>HH</literal></entry>
8152 <entry>hour of day (01&ndash;12)</entry>
8153 </row>
8154 <row>
8155 <entry><literal>HH12</literal></entry>
8156 <entry>hour of day (01&ndash;12)</entry>
8157 </row>
8158 <row>
8159 <entry><literal>HH24</literal></entry>
8160 <entry>hour of day (00&ndash;23)</entry>
8161 </row>
8162 <row>
8163 <entry><literal>MI</literal></entry>
8164 <entry>minute (00&ndash;59)</entry>
8165 </row>
8166 <row>
8167 <entry><literal>SS</literal></entry>
8168 <entry>second (00&ndash;59)</entry>
8169 </row>
8170 <row>
8171 <entry><literal>MS</literal></entry>
8172 <entry>millisecond (000&ndash;999)</entry>
8173 </row>
8174 <row>
8175 <entry><literal>US</literal></entry>
8176 <entry>microsecond (000000&ndash;999999)</entry>
8177 </row>
8178 <row>
8179 <entry><literal>FF1</literal></entry>
8180 <entry>tenth of second (0&ndash;9)</entry>
8181 </row>
8182 <row>
8183 <entry><literal>FF2</literal></entry>
8184 <entry>hundredth of second (00&ndash;99)</entry>
8185 </row>
8186 <row>
8187 <entry><literal>FF3</literal></entry>
8188 <entry>millisecond (000&ndash;999)</entry>
8189 </row>
8190 <row>
8191 <entry><literal>FF4</literal></entry>
8192 <entry>tenth of a millisecond (0000&ndash;9999)</entry>
8193 </row>
8194 <row>
8195 <entry><literal>FF5</literal></entry>
8196 <entry>hundredth of a millisecond (00000&ndash;99999)</entry>
8197 </row>
8198 <row>
8199 <entry><literal>FF6</literal></entry>
8200 <entry>microsecond (000000&ndash;999999)</entry>
8201 </row>
8202 <row>
8203 <entry><literal>SSSS</literal>, <literal>SSSSS</literal></entry>
8204 <entry>seconds past midnight (0&ndash;86399)</entry>
8205 </row>
8206 <row>
8207 <entry><literal>AM</literal>, <literal>am</literal>,
8208 <literal>PM</literal> or <literal>pm</literal></entry>
8209 <entry>meridiem indicator (without periods)</entry>
8210 </row>
8211 <row>
8212 <entry><literal>A.M.</literal>, <literal>a.m.</literal>,
8213 <literal>P.M.</literal> or <literal>p.m.</literal></entry>
8214 <entry>meridiem indicator (with periods)</entry>
8215 </row>
8216 <row>
8217 <entry><literal>Y,YYY</literal></entry>
8218 <entry>year (4 or more digits) with comma</entry>
8219 </row>
8220 <row>
8221 <entry><literal>YYYY</literal></entry>
8222 <entry>year (4 or more digits)</entry>
8223 </row>
8224 <row>
8225 <entry><literal>YYY</literal></entry>
8226 <entry>last 3 digits of year</entry>
8227 </row>
8228 <row>
8229 <entry><literal>YY</literal></entry>
8230 <entry>last 2 digits of year</entry>
8231 </row>
8232 <row>
8233 <entry><literal>Y</literal></entry>
8234 <entry>last digit of year</entry>
8235 </row>
8236 <row>
8237 <entry><literal>IYYY</literal></entry>
8238 <entry>ISO 8601 week-numbering year (4 or more digits)</entry>
8239 </row>
8240 <row>
8241 <entry><literal>IYY</literal></entry>
8242 <entry>last 3 digits of ISO 8601 week-numbering year</entry>
8243 </row>
8244 <row>
8245 <entry><literal>IY</literal></entry>
8246 <entry>last 2 digits of ISO 8601 week-numbering year</entry>
8247 </row>
8248 <row>
8249 <entry><literal>I</literal></entry>
8250 <entry>last digit of ISO 8601 week-numbering year</entry>
8251 </row>
8252 <row>
8253 <entry><literal>BC</literal>, <literal>bc</literal>,
8254 <literal>AD</literal> or <literal>ad</literal></entry>
8255 <entry>era indicator (without periods)</entry>
8256 </row>
8257 <row>
8258 <entry><literal>B.C.</literal>, <literal>b.c.</literal>,
8259 <literal>A.D.</literal> or <literal>a.d.</literal></entry>
8260 <entry>era indicator (with periods)</entry>
8261 </row>
8262 <row>
8263 <entry><literal>MONTH</literal></entry>
8264 <entry>full upper case month name (blank-padded to 9 chars)</entry>
8265 </row>
8266 <row>
8267 <entry><literal>Month</literal></entry>
8268 <entry>full capitalized month name (blank-padded to 9 chars)</entry>
8269 </row>
8270 <row>
8271 <entry><literal>month</literal></entry>
8272 <entry>full lower case month name (blank-padded to 9 chars)</entry>
8273 </row>
8274 <row>
8275 <entry><literal>MON</literal></entry>
8276 <entry>abbreviated upper case month name (3 chars in English, localized lengths vary)</entry>
8277 </row>
8278 <row>
8279 <entry><literal>Mon</literal></entry>
8280 <entry>abbreviated capitalized month name (3 chars in English, localized lengths vary)</entry>
8281 </row>
8282 <row>
8283 <entry><literal>mon</literal></entry>
8284 <entry>abbreviated lower case month name (3 chars in English, localized lengths vary)</entry>
8285 </row>
8286 <row>
8287 <entry><literal>MM</literal></entry>
8288 <entry>month number (01&ndash;12)</entry>
8289 </row>
8290 <row>
8291 <entry><literal>DAY</literal></entry>
8292 <entry>full upper case day name (blank-padded to 9 chars)</entry>
8293 </row>
8294 <row>
8295 <entry><literal>Day</literal></entry>
8296 <entry>full capitalized day name (blank-padded to 9 chars)</entry>
8297 </row>
8298 <row>
8299 <entry><literal>day</literal></entry>
8300 <entry>full lower case day name (blank-padded to 9 chars)</entry>
8301 </row>
8302 <row>
8303 <entry><literal>DY</literal></entry>
8304 <entry>abbreviated upper case day name (3 chars in English, localized lengths vary)</entry>
8305 </row>
8306 <row>
8307 <entry><literal>Dy</literal></entry>
8308 <entry>abbreviated capitalized day name (3 chars in English, localized lengths vary)</entry>
8309 </row>
8310 <row>
8311 <entry><literal>dy</literal></entry>
8312 <entry>abbreviated lower case day name (3 chars in English, localized lengths vary)</entry>
8313 </row>
8314 <row>
8315 <entry><literal>DDD</literal></entry>
8316 <entry>day of year (001&ndash;366)</entry>
8317 </row>
8318 <row>
8319 <entry><literal>IDDD</literal></entry>
8320 <entry>day of ISO 8601 week-numbering year (001&ndash;371; day 1 of the year is Monday of the first ISO week)</entry>
8321 </row>
8322 <row>
8323 <entry><literal>DD</literal></entry>
8324 <entry>day of month (01&ndash;31)</entry>
8325 </row>
8326 <row>
8327 <entry><literal>D</literal></entry>
8328 <entry>day of the week, Sunday (<literal>1</literal>) to Saturday (<literal>7</literal>)</entry>
8329 </row>
8330 <row>
8331 <entry><literal>ID</literal></entry>
8332 <entry>ISO 8601 day of the week, Monday (<literal>1</literal>) to Sunday (<literal>7</literal>)</entry>
8333 </row>
8334 <row>
8335 <entry><literal>W</literal></entry>
8336 <entry>week of month (1&ndash;5) (the first week starts on the first day of the month)</entry>
8337 </row>
8338 <row>
8339 <entry><literal>WW</literal></entry>
8340 <entry>week number of year (1&ndash;53) (the first week starts on the first day of the year)</entry>
8341 </row>
8342 <row>
8343 <entry><literal>IW</literal></entry>
8344 <entry>week number of ISO 8601 week-numbering year (01&ndash;53; the first Thursday of the year is in week 1)</entry>
8345 </row>
8346 <row>
8347 <entry><literal>CC</literal></entry>
8348 <entry>century (2 digits) (the twenty-first century starts on 2001-01-01)</entry>
8349 </row>
8350 <row>
8351 <entry><literal>J</literal></entry>
8352 <entry>Julian Date (integer days since November 24, 4714 BC at local
8353 midnight; see <xref linkend="datetime-julian-dates"/>)</entry>
8354 </row>
8355 <row>
8356 <entry><literal>Q</literal></entry>
8357 <entry>quarter</entry>
8358 </row>
8359 <row>
8360 <entry><literal>RM</literal></entry>
8361 <entry>month in upper case Roman numerals (I&ndash;XII; I=January)</entry>
8362 </row>
8363 <row>
8364 <entry><literal>rm</literal></entry>
8365 <entry>month in lower case Roman numerals (i&ndash;xii; i=January)</entry>
8366 </row>
8367 <row>
8368 <entry><literal>TZ</literal></entry>
8369 <entry>upper case time-zone abbreviation</entry>
8370 </row>
8371 <row>
8372 <entry><literal>tz</literal></entry>
8373 <entry>lower case time-zone abbreviation</entry>
8374 </row>
8375 <row>
8376 <entry><literal>TZH</literal></entry>
8377 <entry>time-zone hours</entry>
8378 </row>
8379 <row>
8380 <entry><literal>TZM</literal></entry>
8381 <entry>time-zone minutes</entry>
8382 </row>
8383 <row>
8384 <entry><literal>OF</literal></entry>
8385 <entry>time-zone offset from UTC (<replaceable>HH</replaceable>
8386 or <replaceable>HH</replaceable><literal>:</literal><replaceable>MM</replaceable>)</entry>
8387 </row>
8388 </tbody>
8389 </tgroup>
8390 </table>
8391
8392 <para>
8393 Modifiers can be applied to any template pattern to alter its
8394 behavior. For example, <literal>FMMonth</literal>
8395 is the <literal>Month</literal> pattern with the
8396 <literal>FM</literal> modifier.
8397 <xref linkend="functions-formatting-datetimemod-table"/> shows the
8398 modifier patterns for date/time formatting.
8399 </para>
8400
8401 <table id="functions-formatting-datetimemod-table">
8402 <title>Template Pattern Modifiers for Date/Time Formatting</title>
8403 <tgroup cols="3">
8404 <thead>
8405 <row>
8406 <entry>Modifier</entry>
8407 <entry>Description</entry>
8408 <entry>Example</entry>
8409 </row>
8410 </thead>
8411 <tbody>
8412 <row>
8413 <entry><literal>FM</literal> prefix</entry>
8414 <entry>fill mode (suppress leading zeroes and padding blanks)</entry>
8415 <entry><literal>FMMonth</literal></entry>
8416 </row>
8417 <row>
8418 <entry><literal>TH</literal> suffix</entry>
8419 <entry>upper case ordinal number suffix</entry>
8420 <entry><literal>DDTH</literal>, e.g., <literal>12TH</literal></entry>
8421 </row>
8422 <row>
8423 <entry><literal>th</literal> suffix</entry>
8424 <entry>lower case ordinal number suffix</entry>
8425 <entry><literal>DDth</literal>, e.g., <literal>12th</literal></entry>
8426 </row>
8427 <row>
8428 <entry><literal>FX</literal> prefix</entry>
8429 <entry>fixed format global option (see usage notes)</entry>
8430 <entry><literal>FX&nbsp;Month&nbsp;DD&nbsp;Day</literal></entry>
8431 </row>
8432 <row>
8433 <entry><literal>TM</literal> prefix</entry>
8434 <entry>translation mode (use localized day and month names based on
8435 <xref linkend="guc-lc-time"/>)</entry>
8436 <entry><literal>TMMonth</literal></entry>
8437 </row>
8438 <row>
8439 <entry><literal>SP</literal> suffix</entry>
8440 <entry>spell mode (not implemented)</entry>
8441 <entry><literal>DDSP</literal></entry>
8442 </row>
8443 </tbody>
8444 </tgroup>
8445 </table>
8446
8447 <para>
8448 Usage notes for date/time formatting:
8449
8450 <itemizedlist>
8451 <listitem>
8452 <para>
8453 <literal>FM</literal> suppresses leading zeroes and trailing blanks
8454 that would otherwise be added to make the output of a pattern be
8455 fixed-width. In <productname>PostgreSQL</productname>,
8456 <literal>FM</literal> modifies only the next specification, while in
8457 Oracle <literal>FM</literal> affects all subsequent
8458 specifications, and repeated <literal>FM</literal> modifiers
8459 toggle fill mode on and off.
8460 </para>
8461 </listitem>
8462
8463 <listitem>
8464 <para>
8465 <literal>TM</literal> suppresses trailing blanks whether or
8466 not <literal>FM</literal> is specified.
8467 </para>
8468 </listitem>
8469
8470 <listitem>
8471 <para>
8472 <function>to_timestamp</function> and <function>to_date</function>
8473 ignore letter case in the input; so for
8474 example <literal>MON</literal>, <literal>Mon</literal>,
8475 and <literal>mon</literal> all accept the same strings. When using
8476 the <literal>TM</literal> modifier, case-folding is done according to
8477 the rules of the function's input collation (see
8478 <xref linkend="collation"/>).
8479 </para>
8480 </listitem>
8481
8482 <listitem>
8483 <para>
8484 <function>to_timestamp</function> and <function>to_date</function>
8485 skip multiple blank spaces at the beginning of the input string and
8486 around date and time values unless the <literal>FX</literal> option is used. For example,
8487 <literal>to_timestamp('&nbsp;2000&nbsp;&nbsp;&nbsp;&nbsp;JUN', 'YYYY MON')</literal> and
8488 <literal>to_timestamp('2000 - JUN', 'YYYY-MON')</literal> work, but
8489 <literal>to_timestamp('2000&nbsp;&nbsp;&nbsp;&nbsp;JUN', 'FXYYYY MON')</literal> returns an error
8490 because <function>to_timestamp</function> expects only a single space.
8491 <literal>FX</literal> must be specified as the first item in
8492 the template.
8493 </para>
8494 </listitem>
8495
8496 <listitem>
8497 <para>
8498 A separator (a space or non-letter/non-digit character) in the template string of
8499 <function>to_timestamp</function> and <function>to_date</function>
8500 matches any single separator in the input string or is skipped,
8501 unless the <literal>FX</literal> option is used.
8502 For example, <literal>to_timestamp('2000JUN', 'YYYY///MON')</literal> and
8503 <literal>to_timestamp('2000/JUN', 'YYYY MON')</literal> work, but
8504 <literal>to_timestamp('2000//JUN', 'YYYY/MON')</literal>
8505 returns an error because the number of separators in the input string
8506 exceeds the number of separators in the template.
8507 </para>
8508 <para>
8509 If <literal>FX</literal> is specified, a separator in the template string
8510 matches exactly one character in the input string. But note that the
8511 input string character is not required to be the same as the separator from the template string.
8512 For example, <literal>to_timestamp('2000/JUN', 'FXYYYY MON')</literal>
8513 works, but <literal>to_timestamp('2000/JUN', 'FXYYYY&nbsp;&nbsp;MON')</literal>
8514 returns an error because the second space in the template string consumes
8515 the letter <literal>J</literal> from the input string.
8516 </para>
8517 </listitem>
8518
8519 <listitem>
8520 <para>
8521 A <literal>TZH</literal> template pattern can match a signed number.
8522 Without the <literal>FX</literal> option, minus signs may be ambiguous,
8523 and could be interpreted as a separator.
8524 This ambiguity is resolved as follows: If the number of separators before
8525 <literal>TZH</literal> in the template string is less than the number of
8526 separators before the minus sign in the input string, the minus sign
8527 is interpreted as part of <literal>TZH</literal>.
8528 Otherwise, the minus sign is considered to be a separator between values.
8529 For example, <literal>to_timestamp('2000 -10', 'YYYY TZH')</literal> matches
8530 <literal>-10</literal> to <literal>TZH</literal>, but
8531 <literal>to_timestamp('2000 -10', 'YYYY&nbsp;&nbsp;TZH')</literal>
8532 matches <literal>10</literal> to <literal>TZH</literal>.
8533 </para>
8534 </listitem>
8535
8536 <listitem>
8537 <para>
8538 Ordinary text is allowed in <function>to_char</function>
8539 templates and will be output literally. You can put a substring
8540 in double quotes to force it to be interpreted as literal text
8541 even if it contains template patterns. For example, in
8542 <literal>'"Hello Year "YYYY'</literal>, the <literal>YYYY</literal>
8543 will be replaced by the year data, but the single <literal>Y</literal> in <literal>Year</literal>
8544 will not be.
8545 In <function>to_date</function>, <function>to_number</function>,
8546 and <function>to_timestamp</function>, literal text and double-quoted
8547 strings result in skipping the number of characters contained in the
8548 string; for example <literal>"XX"</literal> skips two input characters
8549 (whether or not they are <literal>XX</literal>).
8550 </para>
8551 <tip>
8552 <para>
8553 Prior to <productname>PostgreSQL</productname> 12, it was possible to
8554 skip arbitrary text in the input string using non-letter or non-digit
8555 characters. For example,
8556 <literal>to_timestamp('2000y6m1d', 'yyyy-MM-DD')</literal> used to
8557 work. Now you can only use letter characters for this purpose. For example,
8558 <literal>to_timestamp('2000y6m1d', 'yyyytMMtDDt')</literal> and
8559 <literal>to_timestamp('2000y6m1d', 'yyyy"y"MM"m"DD"d"')</literal>
8560 skip <literal>y</literal>, <literal>m</literal>, and
8561 <literal>d</literal>.
8562 </para>
8563 </tip>
8564 </listitem>
8565
8566 <listitem>
8567 <para>
8568 If you want to have a double quote in the output you must
8569 precede it with a backslash, for example <literal>'\"YYYY
8570 Month\"'</literal>. <!-- "" font-lock sanity :-) -->
8571 Backslashes are not otherwise special outside of double-quoted
8572 strings. Within a double-quoted string, a backslash causes the
8573 next character to be taken literally, whatever it is (but this
8574 has no special effect unless the next character is a double quote
8575 or another backslash).
8576 </para>
8577 </listitem>
8578
8579 <listitem>
8580 <para>
8581 In <function>to_timestamp</function> and <function>to_date</function>,
8582 if the year format specification is less than four digits, e.g.,
8583 <literal>YYY</literal>, and the supplied year is less than four digits,
8584 the year will be adjusted to be nearest to the year 2020, e.g.,
8585 <literal>95</literal> becomes 1995.
8586 </para>
8587 </listitem>
8588
8589 <listitem>
8590 <para>
8591 In <function>to_timestamp</function> and <function>to_date</function>,
8592 negative years are treated as signifying BC. If you write both a
8593 negative year and an explicit <literal>BC</literal> field, you get AD
8594 again. An input of year zero is treated as 1 BC.
8595 </para>
8596 </listitem>
8597
8598 <listitem>
8599 <para>
8600 In <function>to_timestamp</function> and <function>to_date</function>,
8601 the <literal>YYYY</literal> conversion has a restriction when
8602 processing years with more than 4 digits. You must
8603 use some non-digit character or template after <literal>YYYY</literal>,
8604 otherwise the year is always interpreted as 4 digits. For example
8605 (with the year 20000):
8606 <literal>to_date('200001130', 'YYYYMMDD')</literal> will be
8607 interpreted as a 4-digit year; instead use a non-digit
8608 separator after the year, like
8609 <literal>to_date('20000-1130', 'YYYY-MMDD')</literal> or
8610 <literal>to_date('20000Nov30', 'YYYYMonDD')</literal>.
8611 </para>
8612 </listitem>
8613
8614 <listitem>
8615 <para>
8616 In <function>to_timestamp</function> and <function>to_date</function>,
8617 the <literal>CC</literal> (century) field is accepted but ignored
8618 if there is a <literal>YYY</literal>, <literal>YYYY</literal> or
8619 <literal>Y,YYY</literal> field. If <literal>CC</literal> is used with
8620 <literal>YY</literal> or <literal>Y</literal> then the result is
8621 computed as that year in the specified century. If the century is
8622 specified but the year is not, the first year of the century
8623 is assumed.
8624 </para>
8625 </listitem>
8626
8627 <listitem>
8628 <para>
8629 In <function>to_timestamp</function> and <function>to_date</function>,
8630 weekday names or numbers (<literal>DAY</literal>, <literal>D</literal>,
8631 and related field types) are accepted but are ignored for purposes of
8632 computing the result. The same is true for quarter
8633 (<literal>Q</literal>) fields.
8634 </para>
8635 </listitem>
8636
8637 <listitem>
8638 <para>
8639 In <function>to_timestamp</function> and <function>to_date</function>,
8640 an ISO 8601 week-numbering date (as distinct from a Gregorian date)
8641 can be specified in one of two ways:
8642 <itemizedlist>
8643 <listitem>
8644 <para>
8645 Year, week number, and weekday: for
8646 example <literal>to_date('2006-42-4', 'IYYY-IW-ID')</literal>
8647 returns the date <literal>2006-10-19</literal>.
8648 If you omit the weekday it is assumed to be 1 (Monday).
8649 </para>
8650 </listitem>
8651 <listitem>
8652 <para>
8653 Year and day of year: for example <literal>to_date('2006-291',
8654 'IYYY-IDDD')</literal> also returns <literal>2006-10-19</literal>.
8655 </para>
8656 </listitem>
8657 </itemizedlist>
8658 </para>
8659 <para>
8660 Attempting to enter a date using a mixture of ISO 8601 week-numbering
8661 fields and Gregorian date fields is nonsensical, and will cause an
8662 error. In the context of an ISO 8601 week-numbering year, the
8663 concept of a <quote>month</quote> or <quote>day of month</quote> has no
8664 meaning. In the context of a Gregorian year, the ISO week has no
8665 meaning.
8666 </para>
8667 <caution>
8668 <para>
8669 While <function>to_date</function> will reject a mixture of
8670 Gregorian and ISO week-numbering date
8671 fields, <function>to_char</function> will not, since output format
8672 specifications like <literal>YYYY-MM-DD (IYYY-IDDD)</literal> can be
8673 useful. But avoid writing something like <literal>IYYY-MM-DD</literal>;
8674 that would yield surprising results near the start of the year.
8675 (See <xref linkend="functions-datetime-extract"/> for more
8676 information.)
8677 </para>
8678 </caution>
8679 </listitem>
8680
8681 <listitem>
8682 <para>
8683 In <function>to_timestamp</function>, millisecond
8684 (<literal>MS</literal>) or microsecond (<literal>US</literal>)
8685 fields are used as the
8686 seconds digits after the decimal point. For example
8687 <literal>to_timestamp('12.3', 'SS.MS')</literal> is not 3 milliseconds,
8688 but 300, because the conversion treats it as 12 + 0.3 seconds.
8689 So, for the format <literal>SS.MS</literal>, the input values
8690 <literal>12.3</literal>, <literal>12.30</literal>,
8691 and <literal>12.300</literal> specify the
8692 same number of milliseconds. To get three milliseconds, one must write
8693 <literal>12.003</literal>, which the conversion treats as
8694 12 + 0.003 = 12.003 seconds.
8695 </para>
8696
8697 <para>
8698 Here is a more
8699 complex example:
8700 <literal>to_timestamp('15:12:02.020.001230', 'HH24:MI:SS.MS.US')</literal>
8701 is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds +
8702 1230 microseconds = 2.021230 seconds.
8703 </para>
8704 </listitem>
8705
8706 <listitem>
8707 <para>
8708 <function>to_char(..., 'ID')</function>'s day of the week numbering
8709 matches the <function>extract(isodow from ...)</function> function, but
8710 <function>to_char(..., 'D')</function>'s does not match
8711 <function>extract(dow from ...)</function>'s day numbering.
8712 </para>
8713 </listitem>
8714
8715 <listitem>
8716 <para>
8717 <function>to_char(interval)</function> formats <literal>HH</literal> and
8718 <literal>HH12</literal> as shown on a 12-hour clock, for example zero hours
8719 and 36 hours both output as <literal>12</literal>, while <literal>HH24</literal>
8720 outputs the full hour value, which can exceed 23 in
8721 an <type>interval</type> value.
8722 </para>
8723 </listitem>
8724
8725 </itemizedlist>
8726 </para>
8727
8728 <para>
8729 <xref linkend="functions-formatting-numeric-table"/> shows the
8730 template patterns available for formatting numeric values.
8731 </para>
8732
8733 <table id="functions-formatting-numeric-table">
8734 <title>Template Patterns for Numeric Formatting</title>
8735 <tgroup cols="2">
8736 <thead>
8737 <row>
8738 <entry>Pattern</entry>
8739 <entry>Description</entry>
8740 </row>
8741 </thead>
8742 <tbody>
8743 <row>
8744 <entry><literal>9</literal></entry>
8745 <entry>digit position (can be dropped if insignificant)</entry>
8746 </row>
8747 <row>
8748 <entry><literal>0</literal></entry>
8749 <entry>digit position (will not be dropped, even if insignificant)</entry>
8750 </row>
8751 <row>
8752 <entry><literal>.</literal> (period)</entry>
8753 <entry>decimal point</entry>
8754 </row>
8755 <row>
8756 <entry><literal>,</literal> (comma)</entry>
8757 <entry>group (thousands) separator</entry>
8758 </row>
8759 <row>
8760 <entry><literal>PR</literal></entry>
8761 <entry>negative value in angle brackets</entry>
8762 </row>
8763 <row>
8764 <entry><literal>S</literal></entry>
8765 <entry>sign anchored to number (uses locale)</entry>
8766 </row>
8767 <row>
8768 <entry><literal>L</literal></entry>
8769 <entry>currency symbol (uses locale)</entry>
8770 </row>
8771 <row>
8772 <entry><literal>D</literal></entry>
8773 <entry>decimal point (uses locale)</entry>
8774 </row>
8775 <row>
8776 <entry><literal>G</literal></entry>
8777 <entry>group separator (uses locale)</entry>
8778 </row>
8779 <row>
8780 <entry><literal>MI</literal></entry>
8781 <entry>minus sign in specified position (if number &lt; 0)</entry>
8782 </row>
8783 <row>
8784 <entry><literal>PL</literal></entry>
8785 <entry>plus sign in specified position (if number &gt; 0)</entry>
8786 </row>
8787 <row>
8788 <entry><literal>SG</literal></entry>
8789 <entry>plus/minus sign in specified position</entry>
8790 </row>
8791 <row>
8792 <entry><literal>RN</literal> or <literal>rn</literal></entry>
8793 <entry>Roman numeral (values between 1 and 3999)</entry>
8794 </row>
8795 <row>
8796 <entry><literal>TH</literal> or <literal>th</literal></entry>
8797 <entry>ordinal number suffix</entry>
8798 </row>
8799 <row>
8800 <entry><literal>V</literal></entry>
8801 <entry>shift specified number of digits (see notes)</entry>
8802 </row>
8803 <row>
8804 <entry><literal>EEEE</literal></entry>
8805 <entry>exponent for scientific notation</entry>
8806 </row>
8807 </tbody>
8808 </tgroup>
8809 </table>
8810
8811 <para>
8812 Usage notes for numeric formatting:
8813
8814 <itemizedlist>
8815 <listitem>
8816 <para>
8817 <literal>0</literal> specifies a digit position that will always be printed,
8818 even if it contains a leading/trailing zero. <literal>9</literal> also
8819 specifies a digit position, but if it is a leading zero then it will
8820 be replaced by a space, while if it is a trailing zero and fill mode
8821 is specified then it will be deleted. (For <function>to_number()</function>,
8822 these two pattern characters are equivalent.)
8823 </para>
8824 </listitem>
8825
8826 <listitem>
8827 <para>
8828 If the format provides fewer fractional digits than the number being
8829 formatted, <function>to_char()</function> will round the number to
8830 the specified number of fractional digits.
8831 </para>
8832 </listitem>
8833
8834 <listitem>
8835 <para>
8836 The pattern characters <literal>S</literal>, <literal>L</literal>, <literal>D</literal>,
8837 and <literal>G</literal> represent the sign, currency symbol, decimal point,
8838 and thousands separator characters defined by the current locale
8839 (see <xref linkend="guc-lc-monetary"/>
8840 and <xref linkend="guc-lc-numeric"/>). The pattern characters period
8841 and comma represent those exact characters, with the meanings of
8842 decimal point and thousands separator, regardless of locale.
8843 </para>
8844 </listitem>
8845
8846 <listitem>
8847 <para>
8848 If no explicit provision is made for a sign
8849 in <function>to_char()</function>'s pattern, one column will be reserved for
8850 the sign, and it will be anchored to (appear just left of) the
8851 number. If <literal>S</literal> appears just left of some <literal>9</literal>'s,
8852 it will likewise be anchored to the number.
8853 </para>
8854 </listitem>
8855
8856 <listitem>
8857 <para>
8858 A sign formatted using <literal>SG</literal>, <literal>PL</literal>, or
8859 <literal>MI</literal> is not anchored to
8860 the number; for example,
8861 <literal>to_char(-12, 'MI9999')</literal> produces <literal>'-&nbsp;&nbsp;12'</literal>
8862 but <literal>to_char(-12, 'S9999')</literal> produces <literal>'&nbsp;&nbsp;-12'</literal>.
8863 (The Oracle implementation does not allow the use of
8864 <literal>MI</literal> before <literal>9</literal>, but rather
8865 requires that <literal>9</literal> precede
8866 <literal>MI</literal>.)
8867 </para>
8868 </listitem>
8869
8870 <listitem>
8871 <para>
8872 <literal>TH</literal> does not convert values less than zero
8873 and does not convert fractional numbers.
8874 </para>
8875 </listitem>
8876
8877 <listitem>
8878 <para>
8879 <literal>PL</literal>, <literal>SG</literal>, and
8880 <literal>TH</literal> are <productname>PostgreSQL</productname>
8881 extensions.
8882 </para>
8883 </listitem>
8884
8885 <listitem>
8886 <para>
8887 In <function>to_number</function>, if non-data template patterns such
8888 as <literal>L</literal> or <literal>TH</literal> are used, the
8889 corresponding number of input characters are skipped, whether or not
8890 they match the template pattern, unless they are data characters
8891 (that is, digits, sign, decimal point, or comma). For
8892 example, <literal>TH</literal> would skip two non-data characters.
8893 </para>
8894 </listitem>
8895
8896 <listitem>
8897 <para>
8898 <literal>V</literal> with <function>to_char</function>
8899 multiplies the input values by
8900 <literal>10^<replaceable>n</replaceable></literal>, where
8901 <replaceable>n</replaceable> is the number of digits following
8902 <literal>V</literal>. <literal>V</literal> with
8903 <function>to_number</function> divides in a similar manner.
8904 The <literal>V</literal> can be thought of as marking the position
8905 of an implicit decimal point in the input or output string.
8906 <function>to_char</function> and <function>to_number</function>
8907 do not support the use of
8908 <literal>V</literal> combined with a decimal point
8909 (e.g., <literal>99.9V99</literal> is not allowed).
8910 </para>
8911 </listitem>
8912
8913 <listitem>
8914 <para>
8915 <literal>EEEE</literal> (scientific notation) cannot be used in
8916 combination with any of the other formatting patterns or
8917 modifiers other than digit and decimal point patterns, and must be at the end of the format string
8918 (e.g., <literal>9.99EEEE</literal> is a valid pattern).
8919 </para>
8920 </listitem>
8921
8922 <listitem>
8923 <para>
8924 In <function>to_number()</function>, the <literal>RN</literal>
8925 pattern converts Roman numerals (in standard form) to numbers.
8926 Input is case-insensitive, so <literal>RN</literal>
8927 and <literal>rn</literal> are equivalent. <literal>RN</literal>
8928 cannot be used in combination with any other formatting patterns or
8929 modifiers except <literal>FM</literal>, which is applicable only
8930 in <function>to_char()</function> and is ignored
8931 in <function>to_number()</function>.
8932 </para>
8933 </listitem>
8934 </itemizedlist>
8935 </para>
8936
8937 <para>
8938 Certain modifiers can be applied to any template pattern to alter its
8939 behavior. For example, <literal>FM99.99</literal>
8940 is the <literal>99.99</literal> pattern with the
8941 <literal>FM</literal> modifier.
8942 <xref linkend="functions-formatting-numericmod-table"/> shows the
8943 modifier patterns for numeric formatting.
8944 </para>
8945
8946 <table id="functions-formatting-numericmod-table">
8947 <title>Template Pattern Modifiers for Numeric Formatting</title>
8948 <tgroup cols="3">
8949 <thead>
8950 <row>
8951 <entry>Modifier</entry>
8952 <entry>Description</entry>
8953 <entry>Example</entry>
8954 </row>
8955 </thead>
8956 <tbody>
8957 <row>
8958 <entry><literal>FM</literal> prefix</entry>
8959 <entry>fill mode (suppress trailing zeroes and padding blanks)</entry>
8960 <entry><literal>FM99.99</literal></entry>
8961 </row>
8962 <row>
8963 <entry><literal>TH</literal> suffix</entry>
8964 <entry>upper case ordinal number suffix</entry>
8965 <entry><literal>999TH</literal></entry>
8966 </row>
8967 <row>
8968 <entry><literal>th</literal> suffix</entry>
8969 <entry>lower case ordinal number suffix</entry>
8970 <entry><literal>999th</literal></entry>
8971 </row>
8972 </tbody>
8973 </tgroup>
8974 </table>
8975
8976 <para>
8977 <xref linkend="functions-formatting-examples-table"/> shows some
8978 examples of the use of the <function>to_char</function> function.
8979 </para>
8980
8981 <table id="functions-formatting-examples-table">
8982 <title><function>to_char</function> Examples</title>
8983 <tgroup cols="2">
8984 <thead>
8985 <row>
8986 <entry>Expression</entry>
8987 <entry>Result</entry>
8988 </row>
8989 </thead>
8990 <tbody>
8991 <row>
8992 <entry><literal>to_char(current_timestamp, 'Day,&nbsp;DD&nbsp;&nbsp;HH12:MI:SS')</literal></entry>
8993 <entry><literal>'Tuesday&nbsp;&nbsp;,&nbsp;06&nbsp;&nbsp;05:39:18'</literal></entry>
8994 </row>
8995 <row>
8996 <entry><literal>to_char(current_timestamp, 'FMDay,&nbsp;FMDD&nbsp;&nbsp;HH12:MI:SS')</literal></entry>
8997 <entry><literal>'Tuesday,&nbsp;6&nbsp;&nbsp;05:39:18'</literal></entry>
8998 </row>
8999 <row>
9000 <entry><literal>to_char(current_timestamp AT TIME ZONE
9001 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')</literal></entry>
9002 <entry><literal>'2022-12-06T05:39:18Z'</literal>,
9003 <acronym>ISO</acronym> 8601 extended format</entry>
9004 </row>
9005 <row>
9006 <entry><literal>to_char(-0.1, '99.99')</literal></entry>
9007 <entry><literal>'&nbsp;&nbsp;-.10'</literal></entry>
9008 </row>
9009 <row>
9010 <entry><literal>to_char(-0.1, 'FM9.99')</literal></entry>
9011 <entry><literal>'-.1'</literal></entry>
9012 </row>
9013 <row>
9014 <entry><literal>to_char(-0.1, 'FM90.99')</literal></entry>
9015 <entry><literal>'-0.1'</literal></entry>
9016 </row>
9017 <row>
9018 <entry><literal>to_char(0.1, '0.9')</literal></entry>
9019 <entry><literal>'&nbsp;0.1'</literal></entry>
9020 </row>
9021 <row>
9022 <entry><literal>to_char(12, '9990999.9')</literal></entry>
9023 <entry><literal>'&nbsp;&nbsp;&nbsp;&nbsp;0012.0'</literal></entry>
9024 </row>
9025 <row>
9026 <entry><literal>to_char(12, 'FM9990999.9')</literal></entry>
9027 <entry><literal>'0012.'</literal></entry>
9028 </row>
9029 <row>
9030 <entry><literal>to_char(485, '999')</literal></entry>
9031 <entry><literal>'&nbsp;485'</literal></entry>
9032 </row>
9033 <row>
9034 <entry><literal>to_char(-485, '999')</literal></entry>
9035 <entry><literal>'-485'</literal></entry>
9036 </row>
9037 <row>
9038 <entry><literal>to_char(485, '9&nbsp;9&nbsp;9')</literal></entry>
9039 <entry><literal>'&nbsp;4&nbsp;8&nbsp;5'</literal></entry>
9040 </row>
9041 <row>
9042 <entry><literal>to_char(1485, '9,999')</literal></entry>
9043 <entry><literal>'&nbsp;1,485'</literal></entry>
9044 </row>
9045 <row>
9046 <entry><literal>to_char(1485, '9G999')</literal></entry>
9047 <entry><literal>'&nbsp;1&nbsp;485'</literal></entry>
9048 </row>
9049 <row>
9050 <entry><literal>to_char(148.5, '999.999')</literal></entry>
9051 <entry><literal>'&nbsp;148.500'</literal></entry>
9052 </row>
9053 <row>
9054 <entry><literal>to_char(148.5, 'FM999.999')</literal></entry>
9055 <entry><literal>'148.5'</literal></entry>
9056 </row>
9057 <row>
9058 <entry><literal>to_char(148.5, 'FM999.990')</literal></entry>
9059 <entry><literal>'148.500'</literal></entry>
9060 </row>
9061 <row>
9062 <entry><literal>to_char(148.5, '999D999')</literal></entry>
9063 <entry><literal>'&nbsp;148,500'</literal></entry>
9064 </row>
9065 <row>
9066 <entry><literal>to_char(3148.5, '9G999D999')</literal></entry>
9067 <entry><literal>'&nbsp;3&nbsp;148,500'</literal></entry>
9068 </row>
9069 <row>
9070 <entry><literal>to_char(-485, '999S')</literal></entry>
9071 <entry><literal>'485-'</literal></entry>
9072 </row>
9073 <row>
9074 <entry><literal>to_char(-485, '999MI')</literal></entry>
9075 <entry><literal>'485-'</literal></entry>
9076 </row>
9077 <row>
9078 <entry><literal>to_char(485, '999MI')</literal></entry>
9079 <entry><literal>'485&nbsp;'</literal></entry>
9080 </row>
9081 <row>
9082 <entry><literal>to_char(485, 'FM999MI')</literal></entry>
9083 <entry><literal>'485'</literal></entry>
9084 </row>
9085 <row>
9086 <entry><literal>to_char(485, 'PL999')</literal></entry>
9087 <entry><literal>'+485'</literal></entry>
9088 </row>
9089 <row>
9090 <entry><literal>to_char(485, 'SG999')</literal></entry>
9091 <entry><literal>'+485'</literal></entry>
9092 </row>
9093 <row>
9094 <entry><literal>to_char(-485, 'SG999')</literal></entry>
9095 <entry><literal>'-485'</literal></entry>
9096 </row>
9097 <row>
9098 <entry><literal>to_char(-485, '9SG99')</literal></entry>
9099 <entry><literal>'4-85'</literal></entry>
9100 </row>
9101 <row>
9102 <entry><literal>to_char(-485, '999PR')</literal></entry>
9103 <entry><literal>'&lt;485&gt;'</literal></entry>
9104 </row>
9105 <row>
9106 <entry><literal>to_char(485, 'L999')</literal></entry>
9107 <entry><literal>'DM&nbsp;485'</literal></entry>
9108 </row>
9109 <row>
9110 <entry><literal>to_char(485, 'RN')</literal></entry>
9111 <entry><literal>'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CDLXXXV'</literal></entry>
9112 </row>
9113 <row>
9114 <entry><literal>to_char(485, 'FMRN')</literal></entry>
9115 <entry><literal>'CDLXXXV'</literal></entry>
9116 </row>
9117 <row>
9118 <entry><literal>to_char(5.2, 'FMRN')</literal></entry>
9119 <entry><literal>'V'</literal></entry>
9120 </row>
9121 <row>
9122 <entry><literal>to_char(482, '999th')</literal></entry>
9123 <entry><literal>'&nbsp;482nd'</literal></entry>
9124 </row>
9125 <row>
9126 <entry><literal>to_char(485, '"Good&nbsp;number:"999')</literal></entry>
9127 <entry><literal>'Good&nbsp;number:&nbsp;485'</literal></entry>
9128 </row>
9129 <row>
9130 <entry><literal>to_char(485.8, '"Pre:"999"&nbsp;Post:"&nbsp;.999')</literal></entry>
9131 <entry><literal>'Pre:&nbsp;485&nbsp;Post:&nbsp;.800'</literal></entry>
9132 </row>
9133 <row>
9134 <entry><literal>to_char(12, '99V999')</literal></entry>
9135 <entry><literal>'&nbsp;12000'</literal></entry>
9136 </row>
9137 <row>
9138 <entry><literal>to_char(12.4, '99V999')</literal></entry>
9139 <entry><literal>'&nbsp;12400'</literal></entry>
9140 </row>
9141 <row>
9142 <entry><literal>to_char(12.45, '99V9')</literal></entry>
9143 <entry><literal>'&nbsp;125'</literal></entry>
9144 </row>
9145 <row>
9146 <entry><literal>to_char(0.0004859, '9.99EEEE')</literal></entry>
9147 <entry><literal>' 4.86e-04'</literal></entry>
9148 </row>
9149 </tbody>
9150 </tgroup>
9151 </table>
9152
9153 </sect1>
9154
9155
9156 <sect1 id="functions-datetime">
9157 <title>Date/Time Functions and Operators</title>
9158
9159 <para>
9160 <xref linkend="functions-datetime-table"/> shows the available
9161 functions for date/time value processing, with details appearing in
9162 the following subsections. <xref
9163 linkend="operators-datetime-table"/> illustrates the behaviors of
9164 the basic arithmetic operators (<literal>+</literal>,
9165 <literal>*</literal>, etc.). For formatting functions, refer to
9166 <xref linkend="functions-formatting"/>. You should be familiar with
9167 the background information on date/time data types from <xref
9168 linkend="datatype-datetime"/>.
9169 </para>
9170
9171 <para>
9172 In addition, the usual comparison operators shown in
9173 <xref linkend="functions-comparison-op-table"/> are available for the
9174 date/time types. Dates and timestamps (with or without time zone) are
9175 all comparable, while times (with or without time zone) and intervals
9176 can only be compared to other values of the same data type. When
9177 comparing a timestamp without time zone to a timestamp with time zone,
9178 the former value is assumed to be given in the time zone specified by
9179 the <xref linkend="guc-timezone"/> configuration parameter, and is
9180 rotated to UTC for comparison to the latter value (which is already
9181 in UTC internally). Similarly, a date value is assumed to represent
9182 midnight in the <varname>TimeZone</varname> zone when comparing it
9183 to a timestamp.
9184 </para>
9185
9186 <para>
9187 All the functions and operators described below that take <type>time</type> or <type>timestamp</type>
9188 inputs actually come in two variants: one that takes <type>time with time zone</type> or <type>timestamp
9189 with time zone</type>, and one that takes <type>time without time zone</type> or <type>timestamp without time zone</type>.
9190 For brevity, these variants are not shown separately. Also, the
9191 <literal>+</literal> and <literal>*</literal> operators come in commutative pairs (for
9192 example both <type>date</type> <literal>+</literal> <type>integer</type>
9193 and <type>integer</type> <literal>+</literal> <type>date</type>); we show
9194 only one of each such pair.
9195 </para>
9196
9197 <table id="operators-datetime-table">
9198 <title>Date/Time Operators</title>
9199
9200 <tgroup cols="1">
9201 <thead>
9202 <row>
9203 <entry role="func_table_entry"><para role="func_signature">
9204 Operator
9205 </para>
9206 <para>
9207 Description
9208 </para>
9209 <para>
9210 Example(s)
9211 </para></entry>
9212 </row>
9213 </thead>
9214
9215 <tbody>
9216 <row>
9217 <entry role="func_table_entry"><para role="func_signature">
9218 <type>date</type> <literal>+</literal> <type>integer</type>
9219 <returnvalue>date</returnvalue>
9220 </para>
9221 <para>
9222 Add a number of days to a date
9223 </para>
9224 <para>
9225 <literal>date '2001-09-28' + 7</literal>
9226 <returnvalue>2001-10-05</returnvalue>
9227 </para></entry>
9228 </row>
9229
9230 <row>
9231 <entry role="func_table_entry"><para role="func_signature">
9232 <type>date</type> <literal>+</literal> <type>interval</type>
9233 <returnvalue>timestamp</returnvalue>
9234 </para>
9235 <para>
9236 Add an interval to a date
9237 </para>
9238 <para>
9239 <literal>date '2001-09-28' + interval '1 hour'</literal>
9240 <returnvalue>2001-09-28 01:00:00</returnvalue>
9241 </para></entry>
9242 </row>
9243
9244 <row>
9245 <entry role="func_table_entry"><para role="func_signature">
9246 <type>date</type> <literal>+</literal> <type>time</type>
9247 <returnvalue>timestamp</returnvalue>
9248 </para>
9249 <para>
9250 Add a time-of-day to a date
9251 </para>
9252 <para>
9253 <literal>date '2001-09-28' + time '03:00'</literal>
9254 <returnvalue>2001-09-28 03:00:00</returnvalue>
9255 </para></entry>
9256 </row>
9257
9258 <row>
9259 <entry role="func_table_entry"><para role="func_signature">
9260 <type>interval</type> <literal>+</literal> <type>interval</type>
9261 <returnvalue>interval</returnvalue>
9262 </para>
9263 <para>
9264 Add intervals
9265 </para>
9266 <para>
9267 <literal>interval '1 day' + interval '1 hour'</literal>
9268 <returnvalue>1 day 01:00:00</returnvalue>
9269 </para></entry>
9270 </row>
9271
9272 <row>
9273 <entry role="func_table_entry"><para role="func_signature">
9274 <type>timestamp</type> <literal>+</literal> <type>interval</type>
9275 <returnvalue>timestamp</returnvalue>
9276 </para>
9277 <para>
9278 Add an interval to a timestamp
9279 </para>
9280 <para>
9281 <literal>timestamp '2001-09-28 01:00' + interval '23 hours'</literal>
9282 <returnvalue>2001-09-29 00:00:00</returnvalue>
9283 </para></entry>
9284 </row>
9285
9286 <row>
9287 <entry role="func_table_entry"><para role="func_signature">
9288 <type>time</type> <literal>+</literal> <type>interval</type>
9289 <returnvalue>time</returnvalue>
9290 </para>
9291 <para>
9292 Add an interval to a time
9293 </para>
9294 <para>
9295 <literal>time '01:00' + interval '3 hours'</literal>
9296 <returnvalue>04:00:00</returnvalue>
9297 </para></entry>
9298 </row>
9299
9300 <row>
9301 <entry role="func_table_entry"><para role="func_signature">
9302 <literal>-</literal> <type>interval</type>
9303 <returnvalue>interval</returnvalue>
9304 </para>
9305 <para>
9306 Negate an interval
9307 </para>
9308 <para>
9309 <literal>- interval '23 hours'</literal>
9310 <returnvalue>-23:00:00</returnvalue>
9311 </para></entry>
9312 </row>
9313
9314 <row>
9315 <entry role="func_table_entry"><para role="func_signature">
9316 <type>date</type> <literal>-</literal> <type>date</type>
9317 <returnvalue>integer</returnvalue>
9318 </para>
9319 <para>
9320 Subtract dates, producing the number of days elapsed
9321 </para>
9322 <para>
9323 <literal>date '2001-10-01' - date '2001-09-28'</literal>
9324 <returnvalue>3</returnvalue>
9325 </para></entry>
9326 </row>
9327
9328 <row>
9329 <entry role="func_table_entry"><para role="func_signature">
9330 <type>date</type> <literal>-</literal> <type>integer</type>
9331 <returnvalue>date</returnvalue>
9332 </para>
9333 <para>
9334 Subtract a number of days from a date
9335 </para>
9336 <para>
9337 <literal>date '2001-10-01' - 7</literal>
9338 <returnvalue>2001-09-24</returnvalue>
9339 </para></entry>
9340 </row>
9341
9342 <row>
9343 <entry role="func_table_entry"><para role="func_signature">
9344 <type>date</type> <literal>-</literal> <type>interval</type>
9345 <returnvalue>timestamp</returnvalue>
9346 </para>
9347 <para>
9348 Subtract an interval from a date
9349 </para>
9350 <para>
9351 <literal>date '2001-09-28' - interval '1 hour'</literal>
9352 <returnvalue>2001-09-27 23:00:00</returnvalue>
9353 </para></entry>
9354 </row>
9355
9356 <row>
9357 <entry role="func_table_entry"><para role="func_signature">
9358 <type>time</type> <literal>-</literal> <type>time</type>
9359 <returnvalue>interval</returnvalue>
9360 </para>
9361 <para>
9362 Subtract times
9363 </para>
9364 <para>
9365 <literal>time '05:00' - time '03:00'</literal>
9366 <returnvalue>02:00:00</returnvalue>
9367 </para></entry>
9368 </row>
9369
9370 <row>
9371 <entry role="func_table_entry"><para role="func_signature">
9372 <type>time</type> <literal>-</literal> <type>interval</type>
9373 <returnvalue>time</returnvalue>
9374 </para>
9375 <para>
9376 Subtract an interval from a time
9377 </para>
9378 <para>
9379 <literal>time '05:00' - interval '2 hours'</literal>
9380 <returnvalue>03:00:00</returnvalue>
9381 </para></entry>
9382 </row>
9383
9384 <row>
9385 <entry role="func_table_entry"><para role="func_signature">
9386 <type>timestamp</type> <literal>-</literal> <type>interval</type>
9387 <returnvalue>timestamp</returnvalue>
9388 </para>
9389 <para>
9390 Subtract an interval from a timestamp
9391 </para>
9392 <para>
9393 <literal>timestamp '2001-09-28 23:00' - interval '23 hours'</literal>
9394 <returnvalue>2001-09-28 00:00:00</returnvalue>
9395 </para></entry>
9396 </row>
9397
9398 <row>
9399 <entry role="func_table_entry"><para role="func_signature">
9400 <type>interval</type> <literal>-</literal> <type>interval</type>
9401 <returnvalue>interval</returnvalue>
9402 </para>
9403 <para>
9404 Subtract intervals
9405 </para>
9406 <para>
9407 <literal>interval '1 day' - interval '1 hour'</literal>
9408 <returnvalue>1 day -01:00:00</returnvalue>
9409 </para></entry>
9410 </row>
9411
9412 <row>
9413 <entry role="func_table_entry"><para role="func_signature">
9414 <type>timestamp</type> <literal>-</literal> <type>timestamp</type>
9415 <returnvalue>interval</returnvalue>
9416 </para>
9417 <para>
9418 Subtract timestamps (converting 24-hour intervals into days,
9419 similarly to <link
9420 linkend="function-justify-hours"><function>justify_hours()</function></link>)
9421 </para>
9422 <para>
9423 <literal>timestamp '2001-09-29 03:00' - timestamp '2001-07-27 12:00'</literal>
9424 <returnvalue>63 days 15:00:00</returnvalue>
9425 </para></entry>
9426 </row>
9427
9428 <row>
9429 <entry role="func_table_entry"><para role="func_signature">
9430 <type>interval</type> <literal>*</literal> <type>double precision</type>
9431 <returnvalue>interval</returnvalue>
9432 </para>
9433 <para>
9434 Multiply an interval by a scalar
9435 </para>
9436 <para>
9437 <literal>interval '1 second' * 900</literal>
9438 <returnvalue>00:15:00</returnvalue>
9439 </para>
9440 <para>
9441 <literal>interval '1 day' * 21</literal>
9442 <returnvalue>21 days</returnvalue>
9443 </para>
9444 <para>
9445 <literal>interval '1 hour' * 3.5</literal>
9446 <returnvalue>03:30:00</returnvalue>
9447 </para></entry>
9448 </row>
9449
9450 <row>
9451 <entry role="func_table_entry"><para role="func_signature">
9452 <type>interval</type> <literal>/</literal> <type>double precision</type>
9453 <returnvalue>interval</returnvalue>
9454 </para>
9455 <para>
9456 Divide an interval by a scalar
9457 </para>
9458 <para>
9459 <literal>interval '1 hour' / 1.5</literal>
9460 <returnvalue>00:40:00</returnvalue>
9461 </para></entry>
9462 </row>
9463 </tbody>
9464 </tgroup>
9465 </table>
9466
9467 <table id="functions-datetime-table">
9468 <title>Date/Time Functions</title>
9469 <tgroup cols="1">
9470 <thead>
9471 <row>
9472 <entry role="func_table_entry"><para role="func_signature">
9473 Function
9474 </para>
9475 <para>
9476 Description
9477 </para>
9478 <para>
9479 Example(s)
9480 </para></entry>
9481 </row>
9482 </thead>
9483
9484 <tbody>
9485 <row>
9486 <entry role="func_table_entry"><para role="func_signature">
9487 <indexterm>
9488 <primary>age</primary>
9489 </indexterm>
9490 <function>age</function> ( <type>timestamp</type>, <type>timestamp</type> )
9491 <returnvalue>interval</returnvalue>
9492 </para>
9493 <para>
9494 Subtract arguments, producing a <quote>symbolic</quote> result that
9495 uses years and months, rather than just days
9496 </para>
9497 <para>
9498 <literal>age(timestamp '2001-04-10', timestamp '1957-06-13')</literal>
9499 <returnvalue>43 years 9 mons 27 days</returnvalue>
9500 </para></entry>
9501 </row>
9502
9503 <row>
9504 <entry role="func_table_entry"><para role="func_signature">
9505 <function>age</function> ( <type>timestamp</type> )
9506 <returnvalue>interval</returnvalue>
9507 </para>
9508 <para>
9509 Subtract argument from <function>current_date</function> (at midnight)
9510 </para>
9511 <para>
9512 <literal>age(timestamp '1957-06-13')</literal>
9513 <returnvalue>62 years 6 mons 10 days</returnvalue>
9514 </para></entry>
9515 </row>
9516
9517 <row>
9518 <entry role="func_table_entry"><para role="func_signature">
9519 <indexterm>
9520 <primary>clock_timestamp</primary>
9521 </indexterm>
9522 <function>clock_timestamp</function> ( )
9523 <returnvalue>timestamp with time zone</returnvalue>
9524 </para>
9525 <para>
9526 Current date and time (changes during statement execution);
9527 see <xref linkend="functions-datetime-current"/>
9528 </para>
9529 <para>
9530 <literal>clock_timestamp()</literal>
9531 <returnvalue>2019-12-23 14:39:53.662522-05</returnvalue>
9532 </para></entry>
9533 </row>
9534
9535 <row>
9536 <entry role="func_table_entry"><para role="func_signature">
9537 <indexterm>
9538 <primary>current_date</primary>
9539 </indexterm>
9540 <function>current_date</function>
9541 <returnvalue>date</returnvalue>
9542 </para>
9543 <para>
9544 Current date; see <xref linkend="functions-datetime-current"/>
9545 </para>
9546 <para>
9547 <literal>current_date</literal>
9548 <returnvalue>2019-12-23</returnvalue>
9549 </para></entry>
9550 </row>
9551
9552 <row>
9553 <entry role="func_table_entry"><para role="func_signature">
9554 <indexterm>
9555 <primary>current_time</primary>
9556 </indexterm>
9557 <function>current_time</function>
9558 <returnvalue>time with time zone</returnvalue>
9559 </para>
9560 <para>
9561 Current time of day; see <xref linkend="functions-datetime-current"/>
9562 </para>
9563 <para>
9564 <literal>current_time</literal>
9565 <returnvalue>14:39:53.662522-05</returnvalue>
9566 </para></entry>
9567 </row>
9568
9569 <row>
9570 <entry role="func_table_entry"><para role="func_signature">
9571 <function>current_time</function> ( <type>integer</type> )
9572 <returnvalue>time with time zone</returnvalue>
9573 </para>
9574 <para>
9575 Current time of day, with limited precision;
9576 see <xref linkend="functions-datetime-current"/>
9577 </para>
9578 <para>
9579 <literal>current_time(2)</literal>
9580 <returnvalue>14:39:53.66-05</returnvalue>
9581 </para></entry>
9582 </row>
9583
9584 <row>
9585 <entry role="func_table_entry"><para role="func_signature">
9586 <indexterm>
9587 <primary>current_timestamp</primary>
9588 </indexterm>
9589 <function>current_timestamp</function>
9590 <returnvalue>timestamp with time zone</returnvalue>
9591 </para>
9592 <para>
9593 Current date and time (start of current transaction);
9594 see <xref linkend="functions-datetime-current"/>
9595 </para>
9596 <para>
9597 <literal>current_timestamp</literal>
9598 <returnvalue>2019-12-23 14:39:53.662522-05</returnvalue>
9599 </para></entry>
9600 </row>
9601
9602 <row>
9603 <entry role="func_table_entry"><para role="func_signature">
9604 <function>current_timestamp</function> ( <type>integer</type> )
9605 <returnvalue>timestamp with time zone</returnvalue>
9606 </para>
9607 <para>
9608 Current date and time (start of current transaction), with limited precision;
9609 see <xref linkend="functions-datetime-current"/>
9610 </para>
9611 <para>
9612 <literal>current_timestamp(0)</literal>
9613 <returnvalue>2019-12-23 14:39:53-05</returnvalue>
9614 </para></entry>
9615 </row>
9616
9617 <row>
9618 <entry role="func_table_entry"><para role="func_signature">
9619 <indexterm>
9620 <primary>date_add</primary>
9621 </indexterm>
9622 <function>date_add</function> ( <type>timestamp with time zone</type>, <type>interval</type> <optional>, <type>text</type> </optional> )
9623 <returnvalue>timestamp with time zone</returnvalue>
9624 </para>
9625 <para>
9626 Add an <type>interval</type> to a <type>timestamp with time
9627 zone</type>, computing times of day and daylight-savings adjustments
9628 according to the time zone named by the third argument, or the
9629 current <xref linkend="guc-timezone"/> setting if that is omitted.
9630 The form with two arguments is equivalent to the <type>timestamp with
9631 time zone</type> <literal>+</literal> <type>interval</type> operator.
9632 </para>
9633 <para>
9634 <literal>date_add('2021-10-31 00:00:00+02'::timestamptz, '1 day'::interval, 'Europe/Warsaw')</literal>
9635 <returnvalue>2021-10-31 23:00:00+00</returnvalue>
9636 </para></entry>
9637 </row>
9638
9639 <row>
9640 <entry role="func_table_entry"><para role="func_signature">
9641 <function>date_bin</function> ( <type>interval</type>, <type>timestamp</type>, <type>timestamp</type> )
9642 <returnvalue>timestamp</returnvalue>
9643 </para>
9644 <para>
9645 Bin input into specified interval aligned with specified origin; see <xref linkend="functions-datetime-bin"/>
9646 </para>
9647 <para>
9648 <literal>date_bin('15 minutes', timestamp '2001-02-16 20:38:40', timestamp '2001-02-16 20:05:00')</literal>
9649 <returnvalue>2001-02-16 20:35:00</returnvalue>
9650 </para></entry>
9651 </row>
9652
9653 <row>
9654 <entry role="func_table_entry"><para role="func_signature">
9655 <indexterm>
9656 <primary>date_part</primary>
9657 </indexterm>
9658 <function>date_part</function> ( <type>text</type>, <type>timestamp</type> )
9659 <returnvalue>double precision</returnvalue>
9660 </para>
9661 <para>
9662 Get timestamp subfield (equivalent to <function>extract</function>);
9663 see <xref linkend="functions-datetime-extract"/>
9664 </para>
9665 <para>
9666 <literal>date_part('hour', timestamp '2001-02-16 20:38:40')</literal>
9667 <returnvalue>20</returnvalue>
9668 </para></entry>
9669 </row>
9670
9671 <row>
9672 <entry role="func_table_entry"><para role="func_signature">
9673 <function>date_part</function> ( <type>text</type>, <type>interval</type> )
9674 <returnvalue>double precision</returnvalue>
9675 </para>
9676 <para>
9677 Get interval subfield (equivalent to <function>extract</function>);
9678 see <xref linkend="functions-datetime-extract"/>
9679 </para>
9680 <para>
9681 <literal>date_part('month', interval '2 years 3 months')</literal>
9682 <returnvalue>3</returnvalue>
9683 </para></entry>
9684 </row>
9685
9686 <row>
9687 <entry role="func_table_entry"><para role="func_signature">
9688 <indexterm>
9689 <primary>date_subtract</primary>
9690 </indexterm>
9691 <function>date_subtract</function> ( <type>timestamp with time zone</type>, <type>interval</type> <optional>, <type>text</type> </optional> )
9692 <returnvalue>timestamp with time zone</returnvalue>
9693 </para>
9694 <para>
9695 Subtract an <type>interval</type> from a <type>timestamp with time
9696 zone</type>, computing times of day and daylight-savings adjustments
9697 according to the time zone named by the third argument, or the
9698 current <xref linkend="guc-timezone"/> setting if that is omitted.
9699 The form with two arguments is equivalent to the <type>timestamp with
9700 time zone</type> <literal>-</literal> <type>interval</type> operator.
9701 </para>
9702 <para>
9703 <literal>date_subtract('2021-11-01 00:00:00+01'::timestamptz, '1 day'::interval, 'Europe/Warsaw')</literal>
9704 <returnvalue>2021-10-30 22:00:00+00</returnvalue>
9705 </para></entry>
9706 </row>
9707
9708 <row>
9709 <entry role="func_table_entry"><para role="func_signature">
9710 <indexterm>
9711 <primary>date_trunc</primary>
9712 </indexterm>
9713 <function>date_trunc</function> ( <type>text</type>, <type>timestamp</type> )
9714 <returnvalue>timestamp</returnvalue>
9715 </para>
9716 <para>
9717 Truncate to specified precision; see <xref linkend="functions-datetime-trunc"/>
9718 </para>
9719 <para>
9720 <literal>date_trunc('hour', timestamp '2001-02-16 20:38:40')</literal>
9721 <returnvalue>2001-02-16 20:00:00</returnvalue>
9722 </para></entry>
9723 </row>
9724
9725 <row>
9726 <entry role="func_table_entry"><para role="func_signature">
9727 <function>date_trunc</function> ( <type>text</type>, <type>timestamp with time zone</type>, <type>text</type> )
9728 <returnvalue>timestamp with time zone</returnvalue>
9729 </para>
9730 <para>
9731 Truncate to specified precision in the specified time zone; see
9732 <xref linkend="functions-datetime-trunc"/>
9733 </para>
9734 <para>
9735 <literal>date_trunc('day', timestamptz '2001-02-16 20:38:40+00', 'Australia/Sydney')</literal>
9736 <returnvalue>2001-02-16 13:00:00+00</returnvalue>
9737 </para></entry>
9738 </row>
9739
9740 <row>
9741 <entry role="func_table_entry"><para role="func_signature">
9742 <function>date_trunc</function> ( <type>text</type>, <type>interval</type> )
9743 <returnvalue>interval</returnvalue>
9744 </para>
9745 <para>
9746 Truncate to specified precision; see
9747 <xref linkend="functions-datetime-trunc"/>
9748 </para>
9749 <para>
9750 <literal>date_trunc('hour', interval '2 days 3 hours 40 minutes')</literal>
9751 <returnvalue>2 days 03:00:00</returnvalue>
9752 </para></entry>
9753 </row>
9754
9755 <row>
9756 <entry role="func_table_entry"><para role="func_signature">
9757 <indexterm>
9758 <primary>extract</primary>
9759 </indexterm>
9760 <function>extract</function> ( <parameter>field</parameter> <literal>from</literal> <type>timestamp</type> )
9761 <returnvalue>numeric</returnvalue>
9762 </para>
9763 <para>
9764 Get timestamp subfield; see <xref linkend="functions-datetime-extract"/>
9765 </para>
9766 <para>
9767 <literal>extract(hour from timestamp '2001-02-16 20:38:40')</literal>
9768 <returnvalue>20</returnvalue>
9769 </para></entry>
9770 </row>
9771
9772 <row>
9773 <entry role="func_table_entry"><para role="func_signature">
9774 <function>extract</function> ( <parameter>field</parameter> <literal>from</literal> <type>interval</type> )
9775 <returnvalue>numeric</returnvalue>
9776 </para>
9777 <para>
9778 Get interval subfield; see <xref linkend="functions-datetime-extract"/>
9779 </para>
9780 <para>
9781 <literal>extract(month from interval '2 years 3 months')</literal>
9782 <returnvalue>3</returnvalue>
9783 </para></entry>
9784 </row>
9785
9786 <row>
9787 <entry role="func_table_entry"><para role="func_signature">
9788 <indexterm>
9789 <primary>isfinite</primary>
9790 </indexterm>
9791 <function>isfinite</function> ( <type>date</type> )
9792 <returnvalue>boolean</returnvalue>
9793 </para>
9794 <para>
9795 Test for finite date (not +/-infinity)
9796 </para>
9797 <para>
9798 <literal>isfinite(date '2001-02-16')</literal>
9799 <returnvalue>true</returnvalue>
9800 </para></entry>
9801 </row>
9802
9803 <row>
9804 <entry role="func_table_entry"><para role="func_signature">
9805 <function>isfinite</function> ( <type>timestamp</type> )
9806 <returnvalue>boolean</returnvalue>
9807 </para>
9808 <para>
9809 Test for finite timestamp (not +/-infinity)
9810 </para>
9811 <para>
9812 <literal>isfinite(timestamp 'infinity')</literal>
9813 <returnvalue>false</returnvalue>
9814 </para></entry>
9815 </row>
9816
9817 <row>
9818 <entry role="func_table_entry"><para role="func_signature">
9819 <function>isfinite</function> ( <type>interval</type> )
9820 <returnvalue>boolean</returnvalue>
9821 </para>
9822 <para>
9823 Test for finite interval (not +/-infinity)
9824 </para>
9825 <para>
9826 <literal>isfinite(interval '4 hours')</literal>
9827 <returnvalue>true</returnvalue>
9828 </para></entry>
9829 </row>
9830
9831 <row>
9832 <entry role="func_table_entry"><para role="func_signature">
9833 <indexterm id="function-justify-days">
9834 <primary>justify_days</primary>
9835 </indexterm>
9836 <function>justify_days</function> ( <type>interval</type> )
9837 <returnvalue>interval</returnvalue>
9838 </para>
9839 <para>
9840 Adjust interval, converting 30-day time periods to months
9841 </para>
9842 <para>
9843 <literal>justify_days(interval '1 year 65 days')</literal>
9844 <returnvalue>1 year 2 mons 5 days</returnvalue>
9845 </para></entry>
9846 </row>
9847
9848 <row>
9849 <entry role="func_table_entry"><para role="func_signature">
9850 <indexterm id="function-justify-hours">
9851 <primary>justify_hours</primary>
9852 </indexterm>
9853 <function>justify_hours</function> ( <type>interval</type> )
9854 <returnvalue>interval</returnvalue>
9855 </para>
9856 <para>
9857 Adjust interval, converting 24-hour time periods to days
9858 </para>
9859 <para>
9860 <literal>justify_hours(interval '50 hours 10 minutes')</literal>
9861 <returnvalue>2 days 02:10:00</returnvalue>
9862 </para></entry>
9863 </row>
9864
9865 <row>
9866 <entry role="func_table_entry"><para role="func_signature">
9867 <indexterm>
9868 <primary>justify_interval</primary>
9869 </indexterm>
9870 <function>justify_interval</function> ( <type>interval</type> )
9871 <returnvalue>interval</returnvalue>
9872 </para>
9873 <para>
9874 Adjust interval using <function>justify_days</function>
9875 and <function>justify_hours</function>, with additional sign
9876 adjustments
9877 </para>
9878 <para>
9879 <literal>justify_interval(interval '1 mon -1 hour')</literal>
9880 <returnvalue>29 days 23:00:00</returnvalue>
9881 </para></entry>
9882 </row>
9883
9884 <row>
9885 <entry role="func_table_entry"><para role="func_signature">
9886 <indexterm>
9887 <primary>localtime</primary>
9888 </indexterm>
9889 <function>localtime</function>
9890 <returnvalue>time</returnvalue>
9891 </para>
9892 <para>
9893 Current time of day;
9894 see <xref linkend="functions-datetime-current"/>
9895 </para>
9896 <para>
9897 <literal>localtime</literal>
9898 <returnvalue>14:39:53.662522</returnvalue>
9899 </para></entry>
9900 </row>
9901
9902 <row>
9903 <entry role="func_table_entry"><para role="func_signature">
9904 <function>localtime</function> ( <type>integer</type> )
9905 <returnvalue>time</returnvalue>
9906 </para>
9907 <para>
9908 Current time of day, with limited precision;
9909 see <xref linkend="functions-datetime-current"/>
9910 </para>
9911 <para>
9912 <literal>localtime(0)</literal>
9913 <returnvalue>14:39:53</returnvalue>
9914 </para></entry>
9915 </row>
9916
9917 <row>
9918 <entry role="func_table_entry"><para role="func_signature">
9919 <indexterm>
9920 <primary>localtimestamp</primary>
9921 </indexterm>
9922 <function>localtimestamp</function>
9923 <returnvalue>timestamp</returnvalue>
9924 </para>
9925 <para>
9926 Current date and time (start of current transaction);
9927 see <xref linkend="functions-datetime-current"/>
9928 </para>
9929 <para>
9930 <literal>localtimestamp</literal>
9931 <returnvalue>2019-12-23 14:39:53.662522</returnvalue>
9932 </para></entry>
9933 </row>
9934
9935 <row>
9936 <entry role="func_table_entry"><para role="func_signature">
9937 <function>localtimestamp</function> ( <type>integer</type> )
9938 <returnvalue>timestamp</returnvalue>
9939 </para>
9940 <para>
9941 Current date and time (start of current
9942 transaction), with limited precision;
9943 see <xref linkend="functions-datetime-current"/>
9944 </para>
9945 <para>
9946 <literal>localtimestamp(2)</literal>
9947 <returnvalue>2019-12-23 14:39:53.66</returnvalue>
9948 </para></entry>
9949 </row>
9950
9951 <row>
9952 <entry role="func_table_entry"><para role="func_signature">
9953 <indexterm>
9954 <primary>make_date</primary>
9955 </indexterm>
9956 <function>make_date</function> ( <parameter>year</parameter> <type>int</type>,
9957 <parameter>month</parameter> <type>int</type>,
9958 <parameter>day</parameter> <type>int</type> )
9959 <returnvalue>date</returnvalue>
9960 </para>
9961 <para>
9962 Create date from year, month and day fields
9963 (negative years signify BC)
9964 </para>
9965 <para>
9966 <literal>make_date(2013, 7, 15)</literal>
9967 <returnvalue>2013-07-15</returnvalue>
9968 </para></entry>
9969 </row>
9970
9971 <row>
9972 <entry role="func_table_entry"><para role="func_signature"><indexterm>
9973 <primary>make_interval</primary>
9974 </indexterm>
9975 <function>make_interval</function> ( <optional> <parameter>years</parameter> <type>int</type>
9976 <optional>, <parameter>months</parameter> <type>int</type>
9977 <optional>, <parameter>weeks</parameter> <type>int</type>
9978 <optional>, <parameter>days</parameter> <type>int</type>
9979 <optional>, <parameter>hours</parameter> <type>int</type>
9980 <optional>, <parameter>mins</parameter> <type>int</type>
9981 <optional>, <parameter>secs</parameter> <type>double precision</type>
9982 </optional></optional></optional></optional></optional></optional></optional> )
9983 <returnvalue>interval</returnvalue>
9984 </para>
9985 <para>
9986 Create interval from years, months, weeks, days, hours, minutes and
9987 seconds fields, each of which can default to zero
9988 </para>
9989 <para>
9990 <literal>make_interval(days =&gt; 10)</literal>
9991 <returnvalue>10 days</returnvalue>
9992 </para></entry>
9993 </row>
9994
9995 <row>
9996 <entry role="func_table_entry"><para role="func_signature">
9997 <indexterm>
9998 <primary>make_time</primary>
9999 </indexterm>
10000 <function>make_time</function> ( <parameter>hour</parameter> <type>int</type>,
10001 <parameter>min</parameter> <type>int</type>,
10002 <parameter>sec</parameter> <type>double precision</type> )
10003 <returnvalue>time</returnvalue>
10004 </para>
10005 <para>
10006 Create time from hour, minute and seconds fields
10007 </para>
10008 <para>
10009 <literal>make_time(8, 15, 23.5)</literal>
10010 <returnvalue>08:15:23.5</returnvalue>
10011 </para></entry>
10012 </row>
10013
10014 <row>
10015 <entry role="func_table_entry"><para role="func_signature">
10016 <indexterm>
10017 <primary>make_timestamp</primary>
10018 </indexterm>
10019 <function>make_timestamp</function> ( <parameter>year</parameter> <type>int</type>,
10020 <parameter>month</parameter> <type>int</type>,
10021 <parameter>day</parameter> <type>int</type>,
10022 <parameter>hour</parameter> <type>int</type>,
10023 <parameter>min</parameter> <type>int</type>,
10024 <parameter>sec</parameter> <type>double precision</type> )
10025 <returnvalue>timestamp</returnvalue>
10026 </para>
10027 <para>
10028 Create timestamp from year, month, day, hour, minute and seconds fields
10029 (negative years signify BC)
10030 </para>
10031 <para>
10032 <literal>make_timestamp(2013, 7, 15, 8, 15, 23.5)</literal>
10033 <returnvalue>2013-07-15 08:15:23.5</returnvalue>
10034 </para></entry>
10035 </row>
10036
10037 <row>
10038 <entry role="func_table_entry"><para role="func_signature">
10039 <indexterm>
10040 <primary>make_timestamptz</primary>
10041 </indexterm>
10042 <function>make_timestamptz</function> ( <parameter>year</parameter> <type>int</type>,
10043 <parameter>month</parameter> <type>int</type>,
10044 <parameter>day</parameter> <type>int</type>,
10045 <parameter>hour</parameter> <type>int</type>,
10046 <parameter>min</parameter> <type>int</type>,
10047 <parameter>sec</parameter> <type>double precision</type>
10048 <optional>, <parameter>timezone</parameter> <type>text</type> </optional> )
10049 <returnvalue>timestamp with time zone</returnvalue>
10050 </para>
10051 <para>
10052 Create timestamp with time zone from year, month, day, hour, minute
10053 and seconds fields (negative years signify BC).
10054 If <parameter>timezone</parameter> is not
10055 specified, the current time zone is used; the examples assume the
10056 session time zone is <literal>Europe/London</literal>
10057 </para>
10058 <para>
10059 <literal>make_timestamptz(2013, 7, 15, 8, 15, 23.5)</literal>
10060 <returnvalue>2013-07-15 08:15:23.5+01</returnvalue>
10061 </para>
10062 <para>
10063 <literal>make_timestamptz(2013, 7, 15, 8, 15, 23.5, 'America/New_York')</literal>
10064 <returnvalue>2013-07-15 13:15:23.5+01</returnvalue>
10065 </para></entry>
10066 </row>
10067
10068 <row>
10069 <entry role="func_table_entry"><para role="func_signature">
10070 <indexterm>
10071 <primary>now</primary>
10072 </indexterm>
10073 <function>now</function> ( )
10074 <returnvalue>timestamp with time zone</returnvalue>
10075 </para>
10076 <para>
10077 Current date and time (start of current transaction);
10078 see <xref linkend="functions-datetime-current"/>
10079 </para>
10080 <para>
10081 <literal>now()</literal>
10082 <returnvalue>2019-12-23 14:39:53.662522-05</returnvalue>
10083 </para></entry>
10084 </row>
10085
10086 <row>
10087 <entry role="func_table_entry"><para role="func_signature">
10088 <indexterm>
10089 <primary>statement_timestamp</primary>
10090 </indexterm>
10091 <function>statement_timestamp</function> ( )
10092 <returnvalue>timestamp with time zone</returnvalue>
10093 </para>
10094 <para>
10095 Current date and time (start of current statement);
10096 see <xref linkend="functions-datetime-current"/>
10097 </para>
10098 <para>
10099 <literal>statement_timestamp()</literal>
10100 <returnvalue>2019-12-23 14:39:53.662522-05</returnvalue>
10101 </para></entry>
10102 </row>
10103
10104 <row>
10105 <entry role="func_table_entry"><para role="func_signature">
10106 <indexterm>
10107 <primary>timeofday</primary>
10108 </indexterm>
10109 <function>timeofday</function> ( )
10110 <returnvalue>text</returnvalue>
10111 </para>
10112 <para>
10113 Current date and time
10114 (like <function>clock_timestamp</function>, but as a <type>text</type> string);
10115 see <xref linkend="functions-datetime-current"/>
10116 </para>
10117 <para>
10118 <literal>timeofday()</literal>
10119 <returnvalue>Mon Dec 23 14:39:53.662522 2019 EST</returnvalue>
10120 </para></entry>
10121 </row>
10122
10123 <row>
10124 <entry role="func_table_entry"><para role="func_signature">
10125 <indexterm>
10126 <primary>transaction_timestamp</primary>
10127 </indexterm>
10128 <function>transaction_timestamp</function> ( )
10129 <returnvalue>timestamp with time zone</returnvalue>
10130 </para>
10131 <para>
10132 Current date and time (start of current transaction);
10133 see <xref linkend="functions-datetime-current"/>
10134 </para>
10135 <para>
10136 <literal>transaction_timestamp()</literal>
10137 <returnvalue>2019-12-23 14:39:53.662522-05</returnvalue>
10138 </para></entry>
10139 </row>
10140
10141 <row>
10142 <entry role="func_table_entry"><para role="func_signature">
10143 <indexterm>
10144 <primary>to_timestamp</primary>
10145 </indexterm>
10146 <function>to_timestamp</function> ( <type>double precision</type> )
10147 <returnvalue>timestamp with time zone</returnvalue>
10148 </para>
10149 <para>
10150 Convert Unix epoch (seconds since 1970-01-01 00:00:00+00) to
10151 timestamp with time zone
10152 </para>
10153 <para>
10154 <literal>to_timestamp(1284352323)</literal>
10155 <returnvalue>2010-09-13 04:32:03+00</returnvalue>
10156 </para></entry>
10157 </row>
10158 </tbody>
10159 </tgroup>
10160 </table>
10161
10162 <para>
10163 <indexterm>
10164 <primary>OVERLAPS</primary>
10165 </indexterm>
10166 In addition to these functions, the SQL <literal>OVERLAPS</literal> operator is
10167 supported:
10168 <synopsis>
10169 (<replaceable>start1</replaceable>, <replaceable>end1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>end2</replaceable>)
10170 (<replaceable>start1</replaceable>, <replaceable>length1</replaceable>) OVERLAPS (<replaceable>start2</replaceable>, <replaceable>length2</replaceable>)
10171 </synopsis>
10172 This expression yields true when two time periods (defined by their
10173 endpoints) overlap, false when they do not overlap. The endpoints
10174 can be specified as pairs of dates, times, or time stamps; or as
10175 a date, time, or time stamp followed by an interval. When a pair
10176 of values is provided, either the start or the end can be written
10177 first; <literal>OVERLAPS</literal> automatically takes the earlier value
10178 of the pair as the start. Each time period is considered to
10179 represent the half-open interval <replaceable>start</replaceable> <literal>&lt;=</literal>
10180 <replaceable>time</replaceable> <literal>&lt;</literal> <replaceable>end</replaceable>, unless
10181 <replaceable>start</replaceable> and <replaceable>end</replaceable> are equal in which case it
10182 represents that single time instant. This means for instance that two
10183 time periods with only an endpoint in common do not overlap.
10184 </para>
10185
10186 <screen>
10187 SELECT (DATE '2001-02-16', DATE '2001-12-21') OVERLAPS
10188 (DATE '2001-10-30', DATE '2002-10-30');
10189 <lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
10190 SELECT (DATE '2001-02-16', INTERVAL '100 days') OVERLAPS
10191 (DATE '2001-10-30', DATE '2002-10-30');
10192 <lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
10193 SELECT (DATE '2001-10-29', DATE '2001-10-30') OVERLAPS
10194 (DATE '2001-10-30', DATE '2001-10-31');
10195 <lineannotation>Result: </lineannotation><computeroutput>false</computeroutput>
10196 SELECT (DATE '2001-10-30', DATE '2001-10-30') OVERLAPS
10197 (DATE '2001-10-30', DATE '2001-10-31');
10198 <lineannotation>Result: </lineannotation><computeroutput>true</computeroutput>
10199 </screen>
10200
10201 <para>
10202 When adding an <type>interval</type> value to (or subtracting an
10203 <type>interval</type> value from) a <type>timestamp</type>
10204 or <type>timestamp with time zone</type> value, the months, days, and
10205 microseconds fields of the <type>interval</type> value are handled in turn.
10206 First, a nonzero months field advances or decrements the date of the
10207 timestamp by the indicated number of months, keeping the day of month the
10208 same unless it would be past the end of the new month, in which case the
10209 last day of that month is used. (For example, March 31 plus 1 month
10210 becomes April 30, but March 31 plus 2 months becomes May 31.)
10211 Then the days field advances or decrements the date of the timestamp by
10212 the indicated number of days. In both these steps the local time of day
10213 is kept the same. Finally, if there is a nonzero microseconds field, it
10214 is added or subtracted literally.
10215 When doing arithmetic on a <type>timestamp with time zone</type> value in
10216 a time zone that recognizes DST, this means that adding or subtracting
10217 (say) <literal>interval '1 day'</literal> does not necessarily have the
10218 same result as adding or subtracting <literal>interval '24
10219 hours'</literal>.
10220 For example, with the session time zone set
10221 to <literal>America/Denver</literal>:
10222 <screen>
10223 SELECT timestamp with time zone '2005-04-02 12:00:00-07' + interval '1 day';
10224 <lineannotation>Result: </lineannotation><computeroutput>2005-04-03 12:00:00-06</computeroutput>
10225 SELECT timestamp with time zone '2005-04-02 12:00:00-07' + interval '24 hours';
10226 <lineannotation>Result: </lineannotation><computeroutput>2005-04-03 13:00:00-06</computeroutput>
10227 </screen>
10228 This happens because an hour was skipped due to a change in daylight saving
10229 time at <literal>2005-04-03 02:00:00</literal> in time zone
10230 <literal>America/Denver</literal>.
10231 </para>
10232
10233 <para>
10234 Note there can be ambiguity in the <literal>months</literal> field returned by
10235 <function>age</function> because different months have different numbers of
10236 days. <productname>PostgreSQL</productname>'s approach uses the month from the
10237 earlier of the two dates when calculating partial months. For example,
10238 <literal>age('2004-06-01', '2004-04-30')</literal> uses April to yield
10239 <literal>1 mon 1 day</literal>, while using May would yield <literal>1 mon 2
10240 days</literal> because May has 31 days, while April has only 30.
10241 </para>
10242
10243 <para>
10244 Subtraction of dates and timestamps can also be complex. One conceptually
10245 simple way to perform subtraction is to convert each value to a number
10246 of seconds using <literal>EXTRACT(EPOCH FROM ...)</literal>, then subtract the
10247 results; this produces the
10248 number of <emphasis>seconds</emphasis> between the two values. This will adjust
10249 for the number of days in each month, timezone changes, and daylight
10250 saving time adjustments. Subtraction of date or timestamp
10251 values with the <quote><literal>-</literal></quote> operator
10252 returns the number of days (24-hours) and hours/minutes/seconds
10253 between the values, making the same adjustments. The <function>age</function>
10254 function returns years, months, days, and hours/minutes/seconds,
10255 performing field-by-field subtraction and then adjusting for negative
10256 field values. The following queries illustrate the differences in these
10257 approaches. The sample results were produced with <literal>timezone
10258 = 'US/Eastern'</literal>; there is a daylight saving time change between the
10259 two dates used:
10260 </para>
10261
10262 <screen>
10263 SELECT EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
10264 EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00');
10265 <lineannotation>Result: </lineannotation><computeroutput>10537200.000000</computeroutput>
10266 SELECT (EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
10267 EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00'))
10268 / 60 / 60 / 24;
10269 <lineannotation>Result: </lineannotation><computeroutput>121.9583333333333333</computeroutput>
10270 SELECT timestamptz '2013-07-01 12:00:00' - timestamptz '2013-03-01 12:00:00';
10271 <lineannotation>Result: </lineannotation><computeroutput>121 days 23:00:00</computeroutput>
10272 SELECT age(timestamptz '2013-07-01 12:00:00', timestamptz '2013-03-01 12:00:00');
10273 <lineannotation>Result: </lineannotation><computeroutput>4 mons</computeroutput>
10274 </screen>
10275
10276 <sect2 id="functions-datetime-extract">
10277 <title><function>EXTRACT</function>, <function>date_part</function></title>
10278
10279 <indexterm>
10280 <primary>date_part</primary>
10281 </indexterm>
10282 <indexterm>
10283 <primary>extract</primary>
10284 </indexterm>
10285
10286 <synopsis>
10287 EXTRACT(<replaceable>field</replaceable> FROM <replaceable>source</replaceable>)
10288 </synopsis>
10289
10290 <para>
10291 The <function>extract</function> function retrieves subfields
10292 such as year or hour from date/time values.
10293 <replaceable>source</replaceable> must be a value expression of
10294 type <type>timestamp</type>, <type>date</type>, <type>time</type>,
10295 or <type>interval</type>. (Timestamps and times can be with or
10296 without time zone.)
10297 <replaceable>field</replaceable> is an identifier or
10298 string that selects what field to extract from the source value.
10299 Not all fields are valid for every input data type; for example, fields
10300 smaller than a day cannot be extracted from a <type>date</type>, while
10301 fields of a day or more cannot be extracted from a <type>time</type>.
10302 The <function>extract</function> function returns values of type
10303 <type>numeric</type>.
10304 </para>
10305
10306 <para>
10307 The following are valid field names:
10308
10309 <!-- alphabetical -->
10310 <variablelist>
10311 <varlistentry>
10312 <term><literal>century</literal></term>
10313 <listitem>
10314 <para>
10315 The century; for <type>interval</type> values, the year field
10316 divided by 100
10317 </para>
10318
10319 <screen>
10320 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');
10321 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
10322 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
10323 <lineannotation>Result: </lineannotation><computeroutput>21</computeroutput>
10324 SELECT EXTRACT(CENTURY FROM DATE '0001-01-01 AD');
10325 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
10326 SELECT EXTRACT(CENTURY FROM DATE '0001-12-31 BC');
10327 <lineannotation>Result: </lineannotation><computeroutput>-1</computeroutput>
10328 SELECT EXTRACT(CENTURY FROM INTERVAL '2001 years');
10329 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
10330 </screen>
10331 </listitem>
10332 </varlistentry>
10333
10334 <varlistentry>
10335 <term><literal>day</literal></term>
10336 <listitem>
10337 <para>
10338 The day of the month (1&ndash;31); for <type>interval</type>
10339 values, the number of days
10340 </para>
10341
10342 <screen>
10343 SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
10344 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
10345 SELECT EXTRACT(DAY FROM INTERVAL '40 days 1 minute');
10346 <lineannotation>Result: </lineannotation><computeroutput>40</computeroutput>
10347 </screen>
10348
10349 </listitem>
10350 </varlistentry>
10351
10352 <varlistentry>
10353 <term><literal>decade</literal></term>
10354 <listitem>
10355 <para>
10356 The year field divided by 10
10357 </para>
10358
10359 <screen>
10360 SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
10361 <lineannotation>Result: </lineannotation><computeroutput>200</computeroutput>
10362 </screen>
10363 </listitem>
10364 </varlistentry>
10365
10366 <varlistentry>
10367 <term><literal>dow</literal></term>
10368 <listitem>
10369 <para>
10370 The day of the week as Sunday (<literal>0</literal>) to
10371 Saturday (<literal>6</literal>)
10372 </para>
10373
10374 <screen>
10375 SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
10376 <lineannotation>Result: </lineannotation><computeroutput>5</computeroutput>
10377 </screen>
10378 <para>
10379 Note that <function>extract</function>'s day of the week numbering
10380 differs from that of the <function>to_char(...,
10381 'D')</function> function.
10382 </para>
10383
10384 </listitem>
10385 </varlistentry>
10386
10387 <varlistentry>
10388 <term><literal>doy</literal></term>
10389 <listitem>
10390 <para>
10391 The day of the year (1&ndash;365/366)
10392 </para>
10393
10394 <screen>
10395 SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
10396 <lineannotation>Result: </lineannotation><computeroutput>47</computeroutput>
10397 </screen>
10398 </listitem>
10399 </varlistentry>
10400
10401 <varlistentry>
10402 <term><literal>epoch</literal></term>
10403 <listitem>
10404 <para>
10405 For <type>timestamp with time zone</type> values, the
10406 number of seconds since 1970-01-01 00:00:00 UTC (negative for
10407 timestamps before that);
10408 for <type>date</type> and <type>timestamp</type> values, the
10409 nominal number of seconds since 1970-01-01 00:00:00,
10410 without regard to timezone or daylight-savings rules;
10411 for <type>interval</type> values, the total number
10412 of seconds in the interval
10413 </para>
10414
10415 <screen>
10416 SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');
10417 <lineannotation>Result: </lineannotation><computeroutput>982384720.120000</computeroutput>
10418 SELECT EXTRACT(EPOCH FROM TIMESTAMP '2001-02-16 20:38:40.12');
10419 <lineannotation>Result: </lineannotation><computeroutput>982355920.120000</computeroutput>
10420 SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
10421 <lineannotation>Result: </lineannotation><computeroutput>442800.000000</computeroutput>
10422 </screen>
10423
10424 <para>
10425 You can convert an epoch value back to a <type>timestamp with time zone</type>
10426 with <function>to_timestamp</function>:
10427 </para>
10428 <screen>
10429 SELECT to_timestamp(982384720.12);
10430 <lineannotation>Result: </lineannotation><computeroutput>2001-02-17 04:38:40.12+00</computeroutput>
10431 </screen>
10432
10433 <para>
10434 Beware that applying <function>to_timestamp</function> to an epoch
10435 extracted from a <type>date</type> or <type>timestamp</type> value
10436 could produce a misleading result: the result will effectively
10437 assume that the original value had been given in UTC, which might
10438 not be the case.
10439 </para>
10440 </listitem>
10441 </varlistentry>
10442
10443 <varlistentry>
10444 <term><literal>hour</literal></term>
10445 <listitem>
10446 <para>
10447 The hour field (0&ndash;23 in timestamps, unrestricted in
10448 intervals)
10449 </para>
10450
10451 <screen>
10452 SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
10453 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
10454 </screen>
10455 </listitem>
10456 </varlistentry>
10457
10458 <varlistentry>
10459 <term><literal>isodow</literal></term>
10460 <listitem>
10461 <para>
10462 The day of the week as Monday (<literal>1</literal>) to
10463 Sunday (<literal>7</literal>)
10464 </para>
10465
10466 <screen>
10467 SELECT EXTRACT(ISODOW FROM TIMESTAMP '2001-02-18 20:38:40');
10468 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
10469 </screen>
10470 <para>
10471 This is identical to <literal>dow</literal> except for Sunday. This
10472 matches the <acronym>ISO</acronym> 8601 day of the week numbering.
10473 </para>
10474
10475 </listitem>
10476 </varlistentry>
10477
10478 <varlistentry>
10479 <term><literal>isoyear</literal></term>
10480 <listitem>
10481 <para>
10482 The <acronym>ISO</acronym> 8601 week-numbering year that the date
10483 falls in
10484 </para>
10485
10486 <screen>
10487 SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-01');
10488 <lineannotation>Result: </lineannotation><computeroutput>2005</computeroutput>
10489 SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-02');
10490 <lineannotation>Result: </lineannotation><computeroutput>2006</computeroutput>
10491 </screen>
10492
10493 <para>
10494 Each <acronym>ISO</acronym> 8601 week-numbering year begins with the
10495 Monday of the week containing the 4th of January, so in early
10496 January or late December the <acronym>ISO</acronym> year may be
10497 different from the Gregorian year. See the <literal>week</literal>
10498 field for more information.
10499 </para>
10500 </listitem>
10501 </varlistentry>
10502
10503 <varlistentry>
10504 <term><literal>julian</literal></term>
10505 <listitem>
10506 <para>
10507 The <firstterm>Julian Date</firstterm> corresponding to the
10508 date or timestamp. Timestamps
10509 that are not local midnight result in a fractional value. See
10510 <xref linkend="datetime-julian-dates"/> for more information.
10511 </para>
10512
10513 <screen>
10514 SELECT EXTRACT(JULIAN FROM DATE '2006-01-01');
10515 <lineannotation>Result: </lineannotation><computeroutput>2453737</computeroutput>
10516 SELECT EXTRACT(JULIAN FROM TIMESTAMP '2006-01-01 12:00');
10517 <lineannotation>Result: </lineannotation><computeroutput>2453737.50000000000000000000</computeroutput>
10518 </screen>
10519 </listitem>
10520 </varlistentry>
10521
10522 <varlistentry>
10523 <term><literal>microseconds</literal></term>
10524 <listitem>
10525 <para>
10526 The seconds field, including fractional parts, multiplied by 1
10527 000 000; note that this includes full seconds
10528 </para>
10529
10530 <screen>
10531 SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
10532 <lineannotation>Result: </lineannotation><computeroutput>28500000</computeroutput>
10533 </screen>
10534 </listitem>
10535 </varlistentry>
10536
10537 <varlistentry>
10538 <term><literal>millennium</literal></term>
10539 <listitem>
10540 <para>
10541 The millennium; for <type>interval</type> values, the year field
10542 divided by 1000
10543 </para>
10544
10545 <screen>
10546 SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
10547 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
10548 SELECT EXTRACT(MILLENNIUM FROM INTERVAL '2001 years');
10549 <lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
10550 </screen>
10551
10552 <para>
10553 Years in the 1900s are in the second millennium.
10554 The third millennium started January 1, 2001.
10555 </para>
10556 </listitem>
10557 </varlistentry>
10558
10559 <varlistentry>
10560 <term><literal>milliseconds</literal></term>
10561 <listitem>
10562 <para>
10563 The seconds field, including fractional parts, multiplied by
10564 1000. Note that this includes full seconds.
10565 </para>
10566
10567 <screen>
10568 SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
10569 <lineannotation>Result: </lineannotation><computeroutput>28500.000</computeroutput>
10570 </screen>
10571 </listitem>
10572 </varlistentry>
10573
10574 <varlistentry>
10575 <term><literal>minute</literal></term>
10576 <listitem>
10577 <para>
10578 The minutes field (0&ndash;59)
10579 </para>
10580
10581 <screen>
10582 SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
10583 <lineannotation>Result: </lineannotation><computeroutput>38</computeroutput>
10584 </screen>
10585 </listitem>
10586 </varlistentry>
10587
10588 <varlistentry>
10589 <term><literal>month</literal></term>
10590 <listitem>
10591 <para>
10592 The number of the month within the year (1&ndash;12);
10593 for <type>interval</type> values, the number of months modulo 12
10594 (0&ndash;11)
10595 </para>
10596
10597 <screen>
10598 SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
10599 <lineannotation>Result: </lineannotation><computeroutput>2</computeroutput>
10600 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
10601 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
10602 SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
10603 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
10604 </screen>
10605 </listitem>
10606 </varlistentry>
10607
10608 <varlistentry>
10609 <term><literal>quarter</literal></term>
10610 <listitem>
10611 <para>
10612 The quarter of the year (1&ndash;4) that the date is in;
10613 for <type>interval</type> values, the month field divided by 3
10614 plus 1
10615 </para>
10616
10617 <screen>
10618 SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
10619 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
10620 SELECT EXTRACT(QUARTER FROM INTERVAL '1 year 6 months');
10621 <lineannotation>Result: </lineannotation><computeroutput>3</computeroutput>
10622 </screen>
10623 </listitem>
10624 </varlistentry>
10625
10626 <varlistentry>
10627 <term><literal>second</literal></term>
10628 <listitem>
10629 <para>
10630 The seconds field, including any fractional seconds
10631 </para>
10632
10633 <screen>
10634 SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
10635 <lineannotation>Result: </lineannotation><computeroutput>40.000000</computeroutput>
10636 SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
10637 <lineannotation>Result: </lineannotation><computeroutput>28.500000</computeroutput>
10638 </screen>
10639 </listitem>
10640 </varlistentry>
10641 <varlistentry>
10642 <term><literal>timezone</literal></term>
10643 <listitem>
10644 <para>
10645 The time zone offset from UTC, measured in seconds. Positive values
10646 correspond to time zones east of UTC, negative values to
10647 zones west of UTC. (Technically,
10648 <productname>PostgreSQL</productname> does not use UTC because
10649 leap seconds are not handled.)
10650 </para>
10651 </listitem>
10652 </varlistentry>
10653
10654 <varlistentry>
10655 <term><literal>timezone_hour</literal></term>
10656 <listitem>
10657 <para>
10658 The hour component of the time zone offset
10659 </para>
10660 </listitem>
10661 </varlistentry>
10662
10663 <varlistentry>
10664 <term><literal>timezone_minute</literal></term>
10665 <listitem>
10666 <para>
10667 The minute component of the time zone offset
10668 </para>
10669 </listitem>
10670 </varlistentry>
10671
10672 <varlistentry>
10673 <term><literal>week</literal></term>
10674 <listitem>
10675 <para>
10676 The number of the <acronym>ISO</acronym> 8601 week-numbering week of
10677 the year. By definition, ISO weeks start on Mondays and the first
10678 week of a year contains January 4 of that year. In other words, the
10679 first Thursday of a year is in week 1 of that year.
10680 </para>
10681 <para>
10682 In the ISO week-numbering system, it is possible for early-January
10683 dates to be part of the 52nd or 53rd week of the previous year, and for
10684 late-December dates to be part of the first week of the next year.
10685 For example, <literal>2005-01-01</literal> is part of the 53rd week of year
10686 2004, and <literal>2006-01-01</literal> is part of the 52nd week of year
10687 2005, while <literal>2012-12-31</literal> is part of the first week of 2013.
10688 It's recommended to use the <literal>isoyear</literal> field together with
10689 <literal>week</literal> to get consistent results.
10690 </para>
10691
10692 <para>
10693 For <type>interval</type> values, the week field is simply the number
10694 of integral days divided by 7.
10695 </para>
10696
10697 <screen>
10698 SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
10699 <lineannotation>Result: </lineannotation><computeroutput>7</computeroutput>
10700 SELECT EXTRACT(WEEK FROM INTERVAL '13 days 24 hours');
10701 <lineannotation>Result: </lineannotation><computeroutput>1</computeroutput>
10702 </screen>
10703 </listitem>
10704 </varlistentry>
10705
10706 <varlistentry>
10707 <term><literal>year</literal></term>
10708 <listitem>
10709 <para>
10710 The year field. Keep in mind there is no <literal>0 AD</literal>, so subtracting
10711 <literal>BC</literal> years from <literal>AD</literal> years should be done with care.
10712 </para>
10713
10714 <screen>
10715 SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
10716 <lineannotation>Result: </lineannotation><computeroutput>2001</computeroutput>
10717 </screen>
10718 </listitem>
10719 </varlistentry>
10720
10721 </variablelist>
10722 </para>
10723
10724 <para>
10725 When processing an <type>interval</type> value,
10726 the <function>extract</function> function produces field values that
10727 match the interpretation used by the interval output function. This
10728 can produce surprising results if one starts with a non-normalized
10729 interval representation, for example:
10730 <screen>
10731 SELECT INTERVAL '80 minutes';
10732 <lineannotation>Result: </lineannotation><computeroutput>01:20:00</computeroutput>
10733 SELECT EXTRACT(MINUTES FROM INTERVAL '80 minutes');
10734 <lineannotation>Result: </lineannotation><computeroutput>20</computeroutput>
10735 </screen>
10736 </para>
10737
10738 <note>
10739 <para>
10740 When the input value is +/-Infinity, <function>extract</function> returns
10741 +/-Infinity for monotonically-increasing fields (<literal>epoch</literal>,
10742 <literal>julian</literal>, <literal>year</literal>, <literal>isoyear</literal>,
10743 <literal>decade</literal>, <literal>century</literal>, and <literal>millennium</literal>
10744 for <type>timestamp</type> inputs; <literal>epoch</literal>, <literal>hour</literal>,
10745 <literal>day</literal>, <literal>year</literal>, <literal>decade</literal>,
10746 <literal>century</literal>, and <literal>millennium</literal> for
10747 <type>interval</type> inputs).
10748 For other fields, NULL is returned. <productname>PostgreSQL</productname>
10749 versions before 9.6 returned zero for all cases of infinite input.
10750 </para>
10751 </note>
10752
10753 <para>
10754 The <function>extract</function> function is primarily intended
10755 for computational processing. For formatting date/time values for
10756 display, see <xref linkend="functions-formatting"/>.
10757 </para>
10758
10759 <para>
10760 The <function>date_part</function> function is modeled on the traditional
10761 <productname>Ingres</productname> equivalent to the
10762 <acronym>SQL</acronym>-standard function <function>extract</function>:
10763 <synopsis>
10764 date_part('<replaceable>field</replaceable>', <replaceable>source</replaceable>)
10765 </synopsis>
10766 Note that here the <replaceable>field</replaceable> parameter needs to
10767 be a string value, not a name. The valid field names for
10768 <function>date_part</function> are the same as for
10769 <function>extract</function>.
10770 For historical reasons, the <function>date_part</function> function
10771 returns values of type <type>double precision</type>. This can result in
10772 a loss of precision in certain uses. Using <function>extract</function>
10773 is recommended instead.
10774 </para>
10775
10776 <screen>
10777 SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
10778 <lineannotation>Result: </lineannotation><computeroutput>16</computeroutput>
10779 SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
10780 <lineannotation>Result: </lineannotation><computeroutput>4</computeroutput>
10781 </screen>
10782
10783 </sect2>
10784
10785 <sect2 id="functions-datetime-trunc">
10786 <title><function>date_trunc</function></title>
10787
10788 <indexterm>
10789 <primary>date_trunc</primary>
10790 </indexterm>
10791
10792 <para>
10793 The function <function>date_trunc</function> is conceptually
10794 similar to the <function>trunc</function> function for numbers.
10795 </para>
10796
10797 <para>
10798 <synopsis>
10799 date_trunc(<replaceable>field</replaceable>, <replaceable>source</replaceable> <optional>, <replaceable>time_zone</replaceable> </optional>)
10800 </synopsis>
10801 <replaceable>source</replaceable> is a value expression of type
10802 <type>timestamp</type>, <type>timestamp with time zone</type>,
10803 or <type>interval</type>.
10804 (Values of type <type>date</type> and
10805 <type>time</type> are cast automatically to <type>timestamp</type> or
10806 <type>interval</type>, respectively.)
10807 <replaceable>field</replaceable> selects to which precision to
10808 truncate the input value. The return value is likewise of type
10809 <type>timestamp</type>, <type>timestamp with time zone</type>,
10810 or <type>interval</type>,
10811 and it has all fields that are less significant than the
10812 selected one set to zero (or one, for day and month).
10813 </para>
10814
10815 <para>
10816 Valid values for <replaceable>field</replaceable> are:
10817 <simplelist>
10818 <member><literal>microseconds</literal></member>
10819 <member><literal>milliseconds</literal></member>
10820 <member><literal>second</literal></member>
10821 <member><literal>minute</literal></member>
10822 <member><literal>hour</literal></member>
10823 <member><literal>day</literal></member>
10824 <member><literal>week</literal></member>
10825 <member><literal>month</literal></member>
10826 <member><literal>quarter</literal></member>
10827 <member><literal>year</literal></member>
10828 <member><literal>decade</literal></member>
10829 <member><literal>century</literal></member>
10830 <member><literal>millennium</literal></member>
10831 </simplelist>
10832 </para>
10833
10834 <para>
10835 When the input value is of type <type>timestamp with time zone</type>,
10836 the truncation is performed with respect to a particular time zone;
10837 for example, truncation to <literal>day</literal> produces a value that
10838 is midnight in that zone. By default, truncation is done with respect
10839 to the current <xref linkend="guc-timezone"/> setting, but the
10840 optional <replaceable>time_zone</replaceable> argument can be provided
10841 to specify a different time zone. The time zone name can be specified
10842 in any of the ways described in <xref linkend="datatype-timezones"/>.
10843 </para>
10844
10845 <para>
10846 A time zone cannot be specified when processing <type>timestamp without
10847 time zone</type> or <type>interval</type> inputs. These are always
10848 taken at face value.
10849 </para>
10850
10851 <para>
10852 Examples (assuming the local time zone is <literal>America/New_York</literal>):
10853 <screen>
10854 SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
10855 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 20:00:00</computeroutput>
10856 SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
10857 <lineannotation>Result: </lineannotation><computeroutput>2001-01-01 00:00:00</computeroutput>
10858 SELECT date_trunc('day', TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40+00');
10859 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 00:00:00-05</computeroutput>
10860 SELECT date_trunc('day', TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40+00', 'Australia/Sydney');
10861 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 08:00:00-05</computeroutput>
10862 SELECT date_trunc('hour', INTERVAL '3 days 02:47:33');
10863 <lineannotation>Result: </lineannotation><computeroutput>3 days 02:00:00</computeroutput>
10864 </screen>
10865 </para>
10866 </sect2>
10867
10868 <sect2 id="functions-datetime-bin">
10869 <title><function>date_bin</function></title>
10870
10871 <indexterm>
10872 <primary>date_bin</primary>
10873 </indexterm>
10874
10875 <para>
10876 The function <function>date_bin</function> <quote>bins</quote> the input
10877 timestamp into the specified interval (the <firstterm>stride</firstterm>)
10878 aligned with a specified origin.
10879 </para>
10880
10881 <para>
10882 <synopsis>
10883 date_bin(<replaceable>stride</replaceable>, <replaceable>source</replaceable>, <replaceable>origin</replaceable>)
10884 </synopsis>
10885 <replaceable>source</replaceable> is a value expression of type
10886 <type>timestamp</type> or <type>timestamp with time zone</type>. (Values
10887 of type <type>date</type> are cast automatically to
10888 <type>timestamp</type>.) <replaceable>stride</replaceable> is a value
10889 expression of type <type>interval</type>. The return value is likewise
10890 of type <type>timestamp</type> or <type>timestamp with time zone</type>,
10891 and it marks the beginning of the bin into which the
10892 <replaceable>source</replaceable> is placed.
10893 </para>
10894
10895 <para>
10896 Examples:
10897 <screen>
10898 SELECT date_bin('15 minutes', TIMESTAMP '2020-02-11 15:44:17', TIMESTAMP '2001-01-01');
10899 <lineannotation>Result: </lineannotation><computeroutput>2020-02-11 15:30:00</computeroutput>
10900 SELECT date_bin('15 minutes', TIMESTAMP '2020-02-11 15:44:17', TIMESTAMP '2001-01-01 00:02:30');
10901 <lineannotation>Result: </lineannotation><computeroutput>2020-02-11 15:32:30</computeroutput>
10902 </screen>
10903 </para>
10904
10905 <para>
10906 In the case of full units (1 minute, 1 hour, etc.), it gives the same result as
10907 the analogous <function>date_trunc</function> call, but the difference is
10908 that <function>date_bin</function> can truncate to an arbitrary interval.
10909 </para>
10910
10911 <para>
10912 The <parameter>stride</parameter> interval must be greater than zero and
10913 cannot contain units of month or larger.
10914 </para>
10915 </sect2>
10916
10917 <sect2 id="functions-datetime-zoneconvert">
10918 <title><literal>AT TIME ZONE</literal> and <literal>AT LOCAL</literal></title>
10919
10920 <indexterm>
10921 <primary>time zone</primary>
10922 <secondary>conversion</secondary>
10923 </indexterm>
10924
10925 <indexterm>
10926 <primary>AT TIME ZONE</primary>
10927 </indexterm>
10928
10929 <indexterm>
10930 <primary>AT LOCAL</primary>
10931 </indexterm>
10932
10933 <para>
10934 The <literal>AT TIME ZONE</literal> operator converts time
10935 stamp <emphasis>without</emphasis> time zone to/from
10936 time stamp <emphasis>with</emphasis> time zone, and
10937 <type>time with time zone</type> values to different time
10938 zones. <xref linkend="functions-datetime-zoneconvert-table"/> shows its
10939 variants.
10940 </para>
10941
10942 <table id="functions-datetime-zoneconvert-table">
10943 <title><literal>AT TIME ZONE</literal> and <literal>AT LOCAL</literal> Variants</title>
10944 <tgroup cols="1">
10945 <thead>
10946 <row>
10947 <entry role="func_table_entry"><para role="func_signature">
10948 Operator
10949 </para>
10950 <para>
10951 Description
10952 </para>
10953 <para>
10954 Example(s)
10955 </para></entry>
10956 </row>
10957 </thead>
10958
10959 <tbody>
10960 <row>
10961 <entry role="func_table_entry"><para role="func_signature">
10962 <type>timestamp without time zone</type> <literal>AT TIME ZONE</literal> <replaceable>zone</replaceable>
10963 <returnvalue>timestamp with time zone</returnvalue>
10964 </para>
10965 <para>
10966 Converts given time stamp <emphasis>without</emphasis> time zone to
10967 time stamp <emphasis>with</emphasis> time zone, assuming the given
10968 value is in the named time zone.
10969 </para>
10970 <para>
10971 <literal>timestamp '2001-02-16 20:38:40' at time zone 'America/Denver'</literal>
10972 <returnvalue>2001-02-17 03:38:40+00</returnvalue>
10973 </para></entry>
10974 </row>
10975
10976 <row>
10977 <entry role="func_table_entry"><para role="func_signature">
10978 <type>timestamp without time zone</type> <literal>AT LOCAL</literal>
10979 <returnvalue>timestamp with time zone</returnvalue>
10980 </para>
10981 <para>
10982 Converts given time stamp <emphasis>without</emphasis> time zone to
10983 time stamp <emphasis>with</emphasis> the session's
10984 <varname>TimeZone</varname> value as time zone.
10985 </para>
10986 <para>
10987 <literal>timestamp '2001-02-16 20:38:40' at local</literal>
10988 <returnvalue>2001-02-17 03:38:40+00</returnvalue>
10989 </para></entry>
10990 </row>
10991
10992 <row>
10993 <entry role="func_table_entry"><para role="func_signature">
10994 <type>timestamp with time zone</type> <literal>AT TIME ZONE</literal> <replaceable>zone</replaceable>
10995 <returnvalue>timestamp without time zone</returnvalue>
10996 </para>
10997 <para>
10998 Converts given time stamp <emphasis>with</emphasis> time zone to
10999 time stamp <emphasis>without</emphasis> time zone, as the time would
11000 appear in that zone.
11001 </para>
11002 <para>
11003 <literal>timestamp with time zone '2001-02-16 20:38:40-05' at time zone 'America/Denver'</literal>
11004 <returnvalue>2001-02-16 18:38:40</returnvalue>
11005 </para></entry>
11006 </row>
11007
11008 <row>
11009 <entry role="func_table_entry"><para role="func_signature">
11010 <type>timestamp with time zone</type> <literal>AT LOCAL</literal>
11011 <returnvalue>timestamp without time zone</returnvalue>
11012 </para>
11013 <para>
11014 Converts given time stamp <emphasis>with</emphasis> time zone to
11015 time stamp <emphasis>without</emphasis> time zone, as the time would
11016 appear with the session's <varname>TimeZone</varname> value as time zone.
11017 </para>
11018 <para>
11019 <literal>timestamp with time zone '2001-02-16 20:38:40-05' at local</literal>
11020 <returnvalue>2001-02-16 18:38:40</returnvalue>
11021 </para></entry>
11022 </row>
11023
11024 <row>
11025 <entry role="func_table_entry"><para role="func_signature">
11026 <type>time with time zone</type> <literal>AT TIME ZONE</literal> <replaceable>zone</replaceable>
11027 <returnvalue>time with time zone</returnvalue>
11028 </para>
11029 <para>
11030 Converts given time <emphasis>with</emphasis> time zone to a new time
11031 zone. Since no date is supplied, this uses the currently active UTC
11032 offset for the named destination zone.
11033 </para>
11034 <para>
11035 <literal>time with time zone '05:34:17-05' at time zone 'UTC'</literal>
11036 <returnvalue>10:34:17+00</returnvalue>
11037 </para></entry>
11038 </row>
11039
11040 <row>
11041 <entry role="func_table_entry"><para role="func_signature">
11042 <type>time with time zone</type> <literal>AT LOCAL</literal>
11043 <returnvalue>time with time zone</returnvalue>
11044 </para>
11045 <para>
11046 Converts given time <emphasis>with</emphasis> time zone to a new time
11047 zone. Since no date is supplied, this uses the currently active UTC
11048 offset for the session's <varname>TimeZone</varname> value.
11049 </para>
11050 <para>
11051 Assuming the session's <varname>TimeZone</varname> is set to <literal>UTC</literal>:
11052 </para>
11053 <para>
11054 <literal>time with time zone '05:34:17-05' at local</literal>
11055 <returnvalue>10:34:17+00</returnvalue>
11056 </para></entry>
11057 </row>
11058 </tbody>
11059 </tgroup>
11060 </table>
11061
11062 <para>
11063 In these expressions, the desired time zone <replaceable>zone</replaceable> can be
11064 specified either as a text value (e.g., <literal>'America/Los_Angeles'</literal>)
11065 or as an interval (e.g., <literal>INTERVAL '-08:00'</literal>).
11066 In the text case, a time zone name can be specified in any of the ways
11067 described in <xref linkend="datatype-timezones"/>.
11068 The interval case is only useful for zones that have fixed offsets from
11069 UTC, so it is not very common in practice.
11070 </para>
11071
11072 <para>
11073 The syntax <literal>AT LOCAL</literal> may be used as shorthand for
11074 <literal>AT TIME ZONE <replaceable>local</replaceable></literal>, where
11075 <replaceable>local</replaceable> is the session's
11076 <varname>TimeZone</varname> value.
11077 </para>
11078
11079 <para>
11080 Examples (assuming the current <xref linkend="guc-timezone"/> setting
11081 is <literal>America/Los_Angeles</literal>):
11082 <screen>
11083 SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'America/Denver';
11084 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 19:38:40-08</computeroutput>
11085 SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'America/Denver';
11086 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 18:38:40</computeroutput>
11087 SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'Asia/Tokyo' AT TIME ZONE 'America/Chicago';
11088 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 05:38:40</computeroutput>
11089 SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT LOCAL;
11090 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 17:38:40</computeroutput>
11091 SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE '+05';
11092 <lineannotation>Result: </lineannotation><computeroutput>2001-02-16 20:38:40</computeroutput>
11093 SELECT TIME WITH TIME ZONE '20:38:40-05' AT LOCAL;
11094 <lineannotation>Result: </lineannotation><computeroutput>17:38:40</computeroutput>
11095 </screen>
11096 The first example adds a time zone to a value that lacks it, and
11097 displays the value using the current <varname>TimeZone</varname>
11098 setting. The second example shifts the time stamp with time zone value
11099 to the specified time zone, and returns the value without a time zone.
11100 This allows storage and display of values different from the current
11101 <varname>TimeZone</varname> setting. The third example converts
11102 Tokyo time to Chicago time. The fourth example shifts the time stamp
11103 with time zone value to the time zone currently specified by the
11104 <varname>TimeZone</varname> setting and returns the value without a
11105 time zone. The fifth example demonstrates that the sign in a POSIX-style
11106 time zone specification has the opposite meaning of the sign in an
11107 ISO-8601 datetime literal, as described in <xref linkend="datatype-timezones"/>
11108 and <xref linkend="datetime-appendix"/>.
11109 </para>
11110
11111 <para>
11112 The sixth example is a cautionary tale. Due to the fact that there is no
11113 date associated with the input value, the conversion is made using the
11114 current date of the session. Therefore, this static example may show a wrong
11115 result depending on the time of the year it is viewed because
11116 <literal>'America/Los_Angeles'</literal> observes Daylight Savings Time.
11117 </para>
11118
11119 <para>
11120 The function <literal><function>timezone</function>(<replaceable>zone</replaceable>,
11121 <replaceable>timestamp</replaceable>)</literal> is equivalent to the SQL-conforming construct
11122 <literal><replaceable>timestamp</replaceable> AT TIME ZONE
11123 <replaceable>zone</replaceable></literal>.
11124 </para>
11125
11126 <para>
11127 The function <literal><function>timezone</function>(<replaceable>zone</replaceable>,
11128 <replaceable>time</replaceable>)</literal> is equivalent to the SQL-conforming construct
11129 <literal><replaceable>time</replaceable> AT TIME ZONE
11130 <replaceable>zone</replaceable></literal>.
11131 </para>
11132
11133 <para>
11134 The function <literal><function>timezone</function>(<replaceable>timestamp</replaceable>)</literal>
11135 is equivalent to the SQL-conforming construct <literal><replaceable>timestamp</replaceable>
11136 AT LOCAL</literal>.
11137 </para>
11138
11139 <para>
11140 The function <literal><function>timezone</function>(<replaceable>time</replaceable>)</literal>
11141 is equivalent to the SQL-conforming construct <literal><replaceable>time</replaceable>
11142 AT LOCAL</literal>.
11143 </para>
11144 </sect2>
11145
11146 <sect2 id="functions-datetime-current">
11147 <title>Current Date/Time</title>
11148
11149 <indexterm>
11150 <primary>date</primary>
11151 <secondary>current</secondary>
11152 </indexterm>
11153
11154 <indexterm>
11155 <primary>time</primary>
11156 <secondary>current</secondary>
11157 </indexterm>
11158
11159 <para>
11160 <productname>PostgreSQL</productname> provides a number of functions
11161 that return values related to the current date and time. These
11162 SQL-standard functions all return values based on the start time of
11163 the current transaction:
11164 <synopsis>
11165 CURRENT_DATE
11166 CURRENT_TIME
11167 CURRENT_TIMESTAMP
11168 CURRENT_TIME(<replaceable>precision</replaceable>)
11169 CURRENT_TIMESTAMP(<replaceable>precision</replaceable>)
11170 LOCALTIME
11171 LOCALTIMESTAMP
11172 LOCALTIME(<replaceable>precision</replaceable>)
11173 LOCALTIMESTAMP(<replaceable>precision</replaceable>)
11174 </synopsis>
11175 </para>
11176
11177 <para>
11178 <function>CURRENT_TIME</function> and
11179 <function>CURRENT_TIMESTAMP</function> deliver values with time zone;
11180 <function>LOCALTIME</function> and
11181 <function>LOCALTIMESTAMP</function> deliver values without time zone.
11182 </para>
11183
11184 <para>
11185 <function>CURRENT_TIME</function>,
11186 <function>CURRENT_TIMESTAMP</function>,
11187 <function>LOCALTIME</function>, and
11188 <function>LOCALTIMESTAMP</function>
11189 can optionally take
11190 a precision parameter, which causes the result to be rounded
11191 to that many fractional digits in the seconds field. Without a precision parameter,
11192 the result is given to the full available precision.
11193 </para>
11194
11195 <para>
11196 Some examples:
11197 <screen>
11198 SELECT CURRENT_TIME;
11199 <lineannotation>Result: </lineannotation><computeroutput>14:39:53.662522-05</computeroutput>
11200 SELECT CURRENT_DATE;
11201 <lineannotation>Result: </lineannotation><computeroutput>2019-12-23</computeroutput>
11202 SELECT CURRENT_TIMESTAMP;
11203 <lineannotation>Result: </lineannotation><computeroutput>2019-12-23 14:39:53.662522-05</computeroutput>
11204 SELECT CURRENT_TIMESTAMP(2);
11205 <lineannotation>Result: </lineannotation><computeroutput>2019-12-23 14:39:53.66-05</computeroutput>
11206 SELECT LOCALTIMESTAMP;
11207 <lineannotation>Result: </lineannotation><computeroutput>2019-12-23 14:39:53.662522</computeroutput>
11208 </screen>
11209 </para>
11210
11211 <para>
11212 Since these functions return
11213 the start time of the current transaction, their values do not
11214 change during the transaction. This is considered a feature:
11215 the intent is to allow a single transaction to have a consistent
11216 notion of the <quote>current</quote> time, so that multiple
11217 modifications within the same transaction bear the same
11218 time stamp.
11219 </para>
11220
11221 <note>
11222 <para>
11223 Other database systems might advance these values more
11224 frequently.
11225 </para>
11226 </note>
11227
11228 <para>
11229 <productname>PostgreSQL</productname> also provides functions that
11230 return the start time of the current statement, as well as the actual
11231 current time at the instant the function is called. The complete list
11232 of non-SQL-standard time functions is:
11233 <synopsis>
11234 transaction_timestamp()
11235 statement_timestamp()
11236 clock_timestamp()
11237 timeofday()
11238 now()
11239 </synopsis>
11240 </para>
11241
11242 <para>
11243 <function>transaction_timestamp()</function> is equivalent to
11244 <function>CURRENT_TIMESTAMP</function>, but is named to clearly reflect
11245 what it returns.
11246 <function>statement_timestamp()</function> returns the start time of the current
11247 statement (more specifically, the time of receipt of the latest command
11248 message from the client).
11249 <function>statement_timestamp()</function> and <function>transaction_timestamp()</function>
11250 return the same value during the first statement of a transaction, but might
11251 differ during subsequent statements.
11252 <function>clock_timestamp()</function> returns the actual current time, and
11253 therefore its value changes even within a single SQL statement.
11254 <function>timeofday()</function> is a historical
11255 <productname>PostgreSQL</productname> function. Like
11256 <function>clock_timestamp()</function>, it returns the actual current time,
11257 but as a formatted <type>text</type> string rather than a <type>timestamp
11258 with time zone</type> value.
11259 <function>now()</function> is a traditional <productname>PostgreSQL</productname>
11260 equivalent to <function>transaction_timestamp()</function>.
11261 </para>
11262
11263 <para>
11264 All the date/time data types also accept the special literal value
11265 <literal>now</literal> to specify the current date and time (again,
11266 interpreted as the transaction start time). Thus,
11267 the following three all return the same result:
11268 <programlisting>
11269 SELECT CURRENT_TIMESTAMP;
11270 SELECT now();
11271 SELECT TIMESTAMP 'now'; -- but see tip below
11272 </programlisting>
11273 </para>
11274
11275 <tip>
11276 <para>
11277 Do not use the third form when specifying a value to be evaluated later,
11278 for example in a <literal>DEFAULT</literal> clause for a table column.
11279 The system will convert <literal>now</literal>
11280 to a <type>timestamp</type> as soon as the constant is parsed, so that when
11281 the default value is needed,
11282 the time of the table creation would be used! The first two
11283 forms will not be evaluated until the default value is used,
11284 because they are function calls. Thus they will give the desired
11285 behavior of defaulting to the time of row insertion.
11286 (See also <xref linkend="datatype-datetime-special-values"/>.)
11287 </para>
11288 </tip>
11289 </sect2>
11290
11291 <sect2 id="functions-datetime-delay">
11292 <title>Delaying Execution</title>
11293
11294 <indexterm>
11295 <primary>pg_sleep</primary>
11296 </indexterm>
11297 <indexterm>
11298 <primary>pg_sleep_for</primary>
11299 </indexterm>
11300 <indexterm>
11301 <primary>pg_sleep_until</primary>
11302 </indexterm>
11303 <indexterm>
11304 <primary>sleep</primary>
11305 </indexterm>
11306 <indexterm>
11307 <primary>delay</primary>
11308 </indexterm>
11309
11310 <para>
11311 The following functions are available to delay execution of the server
11312 process:
11313 <synopsis>
11314 pg_sleep ( <type>double precision</type> )
11315 pg_sleep_for ( <type>interval</type> )
11316 pg_sleep_until ( <type>timestamp with time zone</type> )
11317 </synopsis>
11318
11319 <function>pg_sleep</function> makes the current session's process
11320 sleep until the given number of seconds have
11321 elapsed. Fractional-second delays can be specified.
11322 <function>pg_sleep_for</function> is a convenience function to
11323 allow the sleep time to be specified as an <type>interval</type>.
11324 <function>pg_sleep_until</function> is a convenience function for when
11325 a specific wake-up time is desired.
11326 For example:
11327
11328 <programlisting>
11329 SELECT pg_sleep(1.5);
11330 SELECT pg_sleep_for('5 minutes');
11331 SELECT pg_sleep_until('tomorrow 03:00');
11332 </programlisting>
11333 </para>
11334
11335 <note>
11336 <para>
11337 The effective resolution of the sleep interval is platform-specific;
11338 0.01 seconds is a common value. The sleep delay will be at least as long
11339 as specified. It might be longer depending on factors such as server load.
11340 In particular, <function>pg_sleep_until</function> is not guaranteed to
11341 wake up exactly at the specified time, but it will not wake up any earlier.
11342 </para>
11343 </note>
11344
11345 <warning>
11346 <para>
11347 Make sure that your session does not hold more locks than necessary
11348 when calling <function>pg_sleep</function> or its variants. Otherwise
11349 other sessions might have to wait for your sleeping process, slowing down
11350 the entire system.
11351 </para>
11352 </warning>
11353 </sect2>
11354
11355 </sect1>
11356
11357
11358 <sect1 id="functions-enum">
11359 <title>Enum Support Functions</title>
11360
11361 <para>
11362 For enum types (described in <xref linkend="datatype-enum"/>),
11363 there are several functions that allow cleaner programming without
11364 hard-coding particular values of an enum type.
11365 These are listed in <xref linkend="functions-enum-table"/>. The examples
11366 assume an enum type created as:
11367
11368 <programlisting>
11369 CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'purple');
11370 </programlisting>
11371
11372 </para>
11373
11374 <table id="functions-enum-table">
11375 <title>Enum Support Functions</title>
11376 <tgroup cols="1">
11377 <thead>
11378 <row>
11379 <entry role="func_table_entry"><para role="func_signature">
11380 Function
11381 </para>
11382 <para>
11383 Description
11384 </para>
11385 <para>
11386 Example(s)
11387 </para></entry>
11388 </row>
11389 </thead>
11390
11391 <tbody>
11392 <row>
11393 <entry role="func_table_entry"><para role="func_signature">
11394 <indexterm>
11395 <primary>enum_first</primary>
11396 </indexterm>
11397 <function>enum_first</function> ( <type>anyenum</type> )
11398 <returnvalue>anyenum</returnvalue>
11399 </para>
11400 <para>
11401 Returns the first value of the input enum type.
11402 </para>
11403 <para>
11404 <literal>enum_first(null::rainbow)</literal>
11405 <returnvalue>red</returnvalue>
11406 </para></entry>
11407 </row>
11408 <row>
11409 <entry role="func_table_entry"><para role="func_signature">
11410 <indexterm>
11411 <primary>enum_last</primary>
11412 </indexterm>
11413 <function>enum_last</function> ( <type>anyenum</type> )
11414 <returnvalue>anyenum</returnvalue>
11415 </para>
11416 <para>
11417 Returns the last value of the input enum type.
11418 </para>
11419 <para>
11420 <literal>enum_last(null::rainbow)</literal>
11421 <returnvalue>purple</returnvalue>
11422 </para></entry>
11423 </row>
11424 <row>
11425 <entry role="func_table_entry"><para role="func_signature">
11426 <indexterm>
11427 <primary>enum_range</primary>
11428 </indexterm>
11429 <function>enum_range</function> ( <type>anyenum</type> )
11430 <returnvalue>anyarray</returnvalue>
11431 </para>
11432 <para>
11433 Returns all values of the input enum type in an ordered array.
11434 </para>
11435 <para>
11436 <literal>enum_range(null::rainbow)</literal>
11437 <returnvalue>{red,orange,yellow,&zwsp;green,blue,purple}</returnvalue>
11438 </para></entry>
11439 </row>
11440 <row>
11441 <entry role="func_table_entry"><para role="func_signature">
11442 <function>enum_range</function> ( <type>anyenum</type>, <type>anyenum</type> )
11443 <returnvalue>anyarray</returnvalue>
11444 </para>
11445 <para>
11446 Returns the range between the two given enum values, as an ordered
11447 array. The values must be from the same enum type. If the first
11448 parameter is null, the result will start with the first value of
11449 the enum type.
11450 If the second parameter is null, the result will end with the last
11451 value of the enum type.
11452 </para>
11453 <para>
11454 <literal>enum_range('orange'::rainbow, 'green'::rainbow)</literal>
11455 <returnvalue>{orange,yellow,green}</returnvalue>
11456 </para>
11457 <para>
11458 <literal>enum_range(NULL, 'green'::rainbow)</literal>
11459 <returnvalue>{red,orange,&zwsp;yellow,green}</returnvalue>
11460 </para>
11461 <para>
11462 <literal>enum_range('orange'::rainbow, NULL)</literal>
11463 <returnvalue>{orange,yellow,green,&zwsp;blue,purple}</returnvalue>
11464 </para></entry>
11465 </row>
11466 </tbody>
11467 </tgroup>
11468 </table>
11469
11470 <para>
11471 Notice that except for the two-argument form of <function>enum_range</function>,
11472 these functions disregard the specific value passed to them; they care
11473 only about its declared data type. Either null or a specific value of
11474 the type can be passed, with the same result. It is more common to
11475 apply these functions to a table column or function argument than to
11476 a hardwired type name as used in the examples.
11477 </para>
11478 </sect1>
11479
11480 <sect1 id="functions-geometry">
11481 <title>Geometric Functions and Operators</title>
11482
11483 <para>
11484 The geometric types <type>point</type>, <type>box</type>,
11485 <type>lseg</type>, <type>line</type>, <type>path</type>,
11486 <type>polygon</type>, and <type>circle</type> have a large set of
11487 native support functions and operators, shown in <xref
11488 linkend="functions-geometry-op-table"/>, <xref
11489 linkend="functions-geometry-func-table"/>, and <xref
11490 linkend="functions-geometry-conv-table"/>.
11491 </para>
11492
11493 <table id="functions-geometry-op-table">
11494 <title>Geometric Operators</title>
11495 <tgroup cols="1">
11496 <thead>
11497 <row>
11498 <entry role="func_table_entry"><para role="func_signature">
11499 Operator
11500 </para>
11501 <para>
11502 Description
11503 </para>
11504 <para>
11505 Example(s)
11506 </para></entry>
11507 </row>
11508 </thead>
11509
11510 <tbody>
11511 <row>
11512 <entry role="func_table_entry"><para role="func_signature">
11513 <replaceable>geometric_type</replaceable> <literal>+</literal> <type>point</type>
11514 <returnvalue><replaceable>geometric_type</replaceable></returnvalue>
11515 </para>
11516 <para>
11517 Adds the coordinates of the second <type>point</type> to those of each
11518 point of the first argument, thus performing translation.
11519 Available for <type>point</type>, <type>box</type>, <type>path</type>,
11520 <type>circle</type>.
11521 </para>
11522 <para>
11523 <literal>box '(1,1),(0,0)' + point '(2,0)'</literal>
11524 <returnvalue>(3,1),(2,0)</returnvalue>
11525 </para></entry>
11526 </row>
11527
11528 <row>
11529 <entry role="func_table_entry"><para role="func_signature">
11530 <type>path</type> <literal>+</literal> <type>path</type>
11531 <returnvalue>path</returnvalue>
11532 </para>
11533 <para>
11534 Concatenates two open paths (returns NULL if either path is closed).
11535 </para>
11536 <para>
11537 <literal>path '[(0,0),(1,1)]' + path '[(2,2),(3,3),(4,4)]'</literal>
11538 <returnvalue>[(0,0),(1,1),(2,2),(3,3),(4,4)]</returnvalue>
11539 </para></entry>
11540 </row>
11541
11542 <row>
11543 <entry role="func_table_entry"><para role="func_signature">
11544 <replaceable>geometric_type</replaceable> <literal>-</literal> <type>point</type>
11545 <returnvalue><replaceable>geometric_type</replaceable></returnvalue>
11546 </para>
11547 <para>
11548 Subtracts the coordinates of the second <type>point</type> from those
11549 of each point of the first argument, thus performing translation.
11550 Available for <type>point</type>, <type>box</type>, <type>path</type>,
11551 <type>circle</type>.
11552 </para>
11553 <para>
11554 <literal>box '(1,1),(0,0)' - point '(2,0)'</literal>
11555 <returnvalue>(-1,1),(-2,0)</returnvalue>
11556 </para></entry>
11557 </row>
11558
11559 <row>
11560 <entry role="func_table_entry"><para role="func_signature">
11561 <replaceable>geometric_type</replaceable> <literal>*</literal> <type>point</type>
11562 <returnvalue><replaceable>geometric_type</replaceable></returnvalue>
11563 </para>
11564 <para>
11565 Multiplies each point of the first argument by the second
11566 <type>point</type> (treating a point as being a complex number
11567 represented by real and imaginary parts, and performing standard
11568 complex multiplication). If one interprets
11569 the second <type>point</type> as a vector, this is equivalent to
11570 scaling the object's size and distance from the origin by the length
11571 of the vector, and rotating it counterclockwise around the origin by
11572 the vector's angle from the <replaceable>x</replaceable> axis.
11573 Available for <type>point</type>, <type>box</type>,<footnote
11574 id="functions-geometry-rotation-fn"><para><quote>Rotating</quote> a
11575 box with these operators only moves its corner points: the box is
11576 still considered to have sides parallel to the axes. Hence the box's
11577 size is not preserved, as a true rotation would do.</para></footnote>
11578 <type>path</type>, <type>circle</type>.
11579 </para>
11580 <para>
11581 <literal>path '((0,0),(1,0),(1,1))' * point '(3.0,0)'</literal>
11582 <returnvalue>((0,0),(3,0),(3,3))</returnvalue>
11583 </para>
11584 <para>
11585 <literal>path '((0,0),(1,0),(1,1))' * point(cosd(45), sind(45))</literal>
11586 <returnvalue>((0,0),&zwsp;(0.7071067811865475,0.7071067811865475),&zwsp;(0,1.414213562373095))</returnvalue>
11587 </para></entry>
11588 </row>
11589
11590 <row>
11591 <entry role="func_table_entry"><para role="func_signature">
11592 <replaceable>geometric_type</replaceable> <literal>/</literal> <type>point</type>
11593 <returnvalue><replaceable>geometric_type</replaceable></returnvalue>
11594 </para>
11595 <para>
11596 Divides each point of the first argument by the second
11597 <type>point</type> (treating a point as being a complex number
11598 represented by real and imaginary parts, and performing standard
11599 complex division). If one interprets
11600 the second <type>point</type> as a vector, this is equivalent to
11601 scaling the object's size and distance from the origin down by the
11602 length of the vector, and rotating it clockwise around the origin by
11603 the vector's angle from the <replaceable>x</replaceable> axis.
11604 Available for <type>point</type>, <type>box</type>,<footnoteref
11605 linkend="functions-geometry-rotation-fn"/> <type>path</type>,
11606 <type>circle</type>.
11607 </para>
11608 <para>
11609 <literal>path '((0,0),(1,0),(1,1))' / point '(2.0,0)'</literal>
11610 <returnvalue>((0,0),(0.5,0),(0.5,0.5))</returnvalue>
11611 </para>
11612 <para>
11613 <literal>path '((0,0),(1,0),(1,1))' / point(cosd(45), sind(45))</literal>
11614 <returnvalue>((0,0),&zwsp;(0.7071067811865476,-0.7071067811865476),&zwsp;(1.4142135623730951,0))</returnvalue>
11615 </para></entry>
11616 </row>
11617
11618 <row>
11619 <entry role="func_table_entry"><para role="func_signature">
11620 <literal>@-@</literal> <replaceable>geometric_type</replaceable>
11621 <returnvalue>double precision</returnvalue>
11622 </para>
11623 <para>
11624 Computes the total length.
11625 Available for <type>lseg</type>, <type>path</type>.
11626 </para>
11627 <para>
11628 <literal>@-@ path '[(0,0),(1,0),(1,1)]'</literal>
11629 <returnvalue>2</returnvalue>
11630 </para></entry>
11631 </row>
11632
11633 <row>
11634 <entry role="func_table_entry"><para role="func_signature">
11635 <literal>@@</literal> <replaceable>geometric_type</replaceable>
11636 <returnvalue>point</returnvalue>
11637 </para>
11638 <para>
11639 Computes the center point.
11640 Available for <type>box</type>, <type>lseg</type>,
11641 <type>polygon</type>, <type>circle</type>.
11642 </para>
11643 <para>
11644 <literal>@@ box '(2,2),(0,0)'</literal>
11645 <returnvalue>(1,1)</returnvalue>
11646 </para></entry>
11647 </row>
11648
11649 <row>
11650 <entry role="func_table_entry"><para role="func_signature">
11651 <literal>#</literal> <replaceable>geometric_type</replaceable>
11652 <returnvalue>integer</returnvalue>
11653 </para>
11654 <para>
11655 Returns the number of points.
11656 Available for <type>path</type>, <type>polygon</type>.
11657 </para>
11658 <para>
11659 <literal># path '((1,0),(0,1),(-1,0))'</literal>
11660 <returnvalue>3</returnvalue>
11661 </para></entry>
11662 </row>
11663
11664 <row>
11665 <entry role="func_table_entry"><para role="func_signature">
11666 <replaceable>geometric_type</replaceable> <literal>#</literal> <replaceable>geometric_type</replaceable>
11667 <returnvalue>point</returnvalue>
11668 </para>
11669 <para>
11670 Computes the point of intersection, or NULL if there is none.
11671 Available for <type>lseg</type>, <type>line</type>.
11672 </para>
11673 <para>
11674 <literal>lseg '[(0,0),(1,1)]' # lseg '[(1,0),(0,1)]'</literal>
11675 <returnvalue>(0.5,0.5)</returnvalue>
11676 </para></entry>
11677 </row>
11678
11679 <row>
11680 <entry role="func_table_entry"><para role="func_signature">
11681 <type>box</type> <literal>#</literal> <type>box</type>
11682 <returnvalue>box</returnvalue>
11683 </para>
11684 <para>
11685 Computes the intersection of two boxes, or NULL if there is none.
11686 </para>
11687 <para>
11688 <literal>box '(2,2),(-1,-1)' # box '(1,1),(-2,-2)'</literal>
11689 <returnvalue>(1,1),(-1,-1)</returnvalue>
11690 </para></entry>
11691 </row>
11692
11693 <row>
11694 <entry role="func_table_entry"><para role="func_signature">
11695 <replaceable>geometric_type</replaceable> <literal>##</literal> <replaceable>geometric_type</replaceable>
11696 <returnvalue>point</returnvalue>
11697 </para>
11698 <para>
11699 Computes the closest point to the first object on the second object.
11700 Available for these pairs of types:
11701 (<type>point</type>, <type>box</type>),
11702 (<type>point</type>, <type>lseg</type>),
11703 (<type>point</type>, <type>line</type>),
11704 (<type>lseg</type>, <type>box</type>),
11705 (<type>lseg</type>, <type>lseg</type>),
11706 (<type>line</type>, <type>lseg</type>).
11707 </para>
11708 <para>
11709 <literal>point '(0,0)' ## lseg '[(2,0),(0,2)]'</literal>
11710 <returnvalue>(1,1)</returnvalue>
11711 </para></entry>
11712 </row>
11713
11714 <row>
11715 <entry role="func_table_entry"><para role="func_signature">
11716 <replaceable>geometric_type</replaceable> <literal>&lt;-&gt;</literal> <replaceable>geometric_type</replaceable>
11717 <returnvalue>double precision</returnvalue>
11718 </para>
11719 <para>
11720 Computes the distance between the objects.
11721 Available for all seven geometric types, for all combinations
11722 of <type>point</type> with another geometric type, and for
11723 these additional pairs of types:
11724 (<type>box</type>, <type>lseg</type>),
11725 (<type>lseg</type>, <type>line</type>),
11726 (<type>polygon</type>, <type>circle</type>)
11727 (and the commutator cases).
11728 </para>
11729 <para>
11730 <literal>circle '&lt;(0,0),1&gt;' &lt;-&gt; circle '&lt;(5,0),1&gt;'</literal>
11731 <returnvalue>3</returnvalue>
11732 </para></entry>
11733 </row>
11734
11735 <row>
11736 <entry role="func_table_entry"><para role="func_signature">
11737 <replaceable>geometric_type</replaceable> <literal>@&gt;</literal> <replaceable>geometric_type</replaceable>
11738 <returnvalue>boolean</returnvalue>
11739 </para>
11740 <para>
11741 Does first object contain second?
11742 Available for these pairs of types:
11743 (<literal>box</literal>, <literal>point</literal>),
11744 (<literal>box</literal>, <literal>box</literal>),
11745 (<literal>path</literal>, <literal>point</literal>),
11746 (<literal>polygon</literal>, <literal>point</literal>),
11747 (<literal>polygon</literal>, <literal>polygon</literal>),
11748 (<literal>circle</literal>, <literal>point</literal>),
11749 (<literal>circle</literal>, <literal>circle</literal>).
11750 </para>
11751 <para>
11752 <literal>circle '&lt;(0,0),2&gt;' @&gt; point '(1,1)'</literal>
11753 <returnvalue>t</returnvalue>
11754 </para></entry>
11755 </row>
11756
11757 <row>
11758 <entry role="func_table_entry"><para role="func_signature">
11759 <replaceable>geometric_type</replaceable> <literal>&lt;@</literal> <replaceable>geometric_type</replaceable>
11760 <returnvalue>boolean</returnvalue>
11761 </para>
11762 <para>
11763 Is first object contained in or on second?
11764 Available for these pairs of types:
11765 (<literal>point</literal>, <literal>box</literal>),
11766 (<literal>point</literal>, <literal>lseg</literal>),
11767 (<literal>point</literal>, <literal>line</literal>),
11768 (<literal>point</literal>, <literal>path</literal>),
11769 (<literal>point</literal>, <literal>polygon</literal>),
11770 (<literal>point</literal>, <literal>circle</literal>),
11771 (<literal>box</literal>, <literal>box</literal>),
11772 (<literal>lseg</literal>, <literal>box</literal>),
11773 (<literal>lseg</literal>, <literal>line</literal>),
11774 (<literal>polygon</literal>, <literal>polygon</literal>),
11775 (<literal>circle</literal>, <literal>circle</literal>).
11776 </para>
11777 <para>
11778 <literal>point '(1,1)' &lt;@ circle '&lt;(0,0),2&gt;'</literal>
11779 <returnvalue>t</returnvalue>
11780 </para></entry>
11781 </row>
11782
11783 <row>
11784 <entry role="func_table_entry"><para role="func_signature">
11785 <replaceable>geometric_type</replaceable> <literal>&amp;&amp;</literal> <replaceable>geometric_type</replaceable>
11786 <returnvalue>boolean</returnvalue>
11787 </para>
11788 <para>
11789 Do these objects overlap? (One point in common makes this true.)
11790 Available for <type>box</type>, <type>polygon</type>,
11791 <type>circle</type>.
11792 </para>
11793 <para>
11794 <literal>box '(1,1),(0,0)' &amp;&amp; box '(2,2),(0,0)'</literal>
11795 <returnvalue>t</returnvalue>
11796 </para></entry>
11797 </row>
11798
11799 <row>
11800 <entry role="func_table_entry"><para role="func_signature">
11801 <replaceable>geometric_type</replaceable> <literal>&lt;&lt;</literal> <replaceable>geometric_type</replaceable>
11802 <returnvalue>boolean</returnvalue>
11803 </para>
11804 <para>
11805 Is first object strictly left of second?
11806 Available for <type>point</type>, <type>box</type>,
11807 <type>polygon</type>, <type>circle</type>.
11808 </para>
11809 <para>
11810 <literal>circle '&lt;(0,0),1&gt;' &lt;&lt; circle '&lt;(5,0),1&gt;'</literal>
11811 <returnvalue>t</returnvalue>
11812 </para></entry>
11813 </row>
11814
11815 <row>
11816 <entry role="func_table_entry"><para role="func_signature">
11817 <replaceable>geometric_type</replaceable> <literal>&gt;&gt;</literal> <replaceable>geometric_type</replaceable>
11818 <returnvalue>boolean</returnvalue>
11819 </para>
11820 <para>
11821 Is first object strictly right of second?
11822 Available for <type>point</type>, <type>box</type>,
11823 <type>polygon</type>, <type>circle</type>.
11824 </para>
11825 <para>
11826 <literal>circle '&lt;(5,0),1&gt;' &gt;&gt; circle '&lt;(0,0),1&gt;'</literal>
11827 <returnvalue>t</returnvalue>
11828 </para></entry>
11829 </row>
11830
11831 <row>
11832 <entry role="func_table_entry"><para role="func_signature">
11833 <replaceable>geometric_type</replaceable> <literal>&amp;&lt;</literal> <replaceable>geometric_type</replaceable>
11834 <returnvalue>boolean</returnvalue>
11835 </para>
11836 <para>
11837 Does first object not extend to the right of second?
11838 Available for <type>box</type>, <type>polygon</type>,
11839 <type>circle</type>.
11840 </para>
11841 <para>
11842 <literal>box '(1,1),(0,0)' &amp;&lt; box '(2,2),(0,0)'</literal>
11843 <returnvalue>t</returnvalue>
11844 </para></entry>
11845 </row>
11846
11847 <row>
11848 <entry role="func_table_entry"><para role="func_signature">
11849 <replaceable>geometric_type</replaceable> <literal>&amp;&gt;</literal> <replaceable>geometric_type</replaceable>
11850 <returnvalue>boolean</returnvalue>
11851 </para>
11852 <para>
11853 Does first object not extend to the left of second?
11854 Available for <type>box</type>, <type>polygon</type>,
11855 <type>circle</type>.
11856 </para>
11857 <para>
11858 <literal>box '(3,3),(0,0)' &amp;&gt; box '(2,2),(0,0)'</literal>
11859 <returnvalue>t</returnvalue>
11860 </para></entry>
11861 </row>
11862
11863 <row>
11864 <entry role="func_table_entry"><para role="func_signature">
11865 <replaceable>geometric_type</replaceable> <literal>&lt;&lt;|</literal> <replaceable>geometric_type</replaceable>
11866 <returnvalue>boolean</returnvalue>
11867 </para>
11868 <para>
11869 Is first object strictly below second?
11870 Available for <type>point</type>, <type>box</type>, <type>polygon</type>,
11871 <type>circle</type>.
11872 </para>
11873 <para>
11874 <literal>box '(3,3),(0,0)' &lt;&lt;| box '(5,5),(3,4)'</literal>
11875 <returnvalue>t</returnvalue>
11876 </para></entry>
11877 </row>
11878
11879 <row>
11880 <entry role="func_table_entry"><para role="func_signature">
11881 <replaceable>geometric_type</replaceable> <literal>|&gt;&gt;</literal> <replaceable>geometric_type</replaceable>
11882 <returnvalue>boolean</returnvalue>
11883 </para>
11884 <para>
11885 Is first object strictly above second?
11886 Available for <type>point</type>, <type>box</type>, <type>polygon</type>,
11887 <type>circle</type>.
11888 </para>
11889 <para>
11890 <literal>box '(5,5),(3,4)' |&gt;&gt; box '(3,3),(0,0)'</literal>
11891 <returnvalue>t</returnvalue>
11892 </para></entry>
11893 </row>
11894
11895 <row>
11896 <entry role="func_table_entry"><para role="func_signature">
11897 <replaceable>geometric_type</replaceable> <literal>&amp;&lt;|</literal> <replaceable>geometric_type</replaceable>
11898 <returnvalue>boolean</returnvalue>
11899 </para>
11900 <para>
11901 Does first object not extend above second?
11902 Available for <type>box</type>, <type>polygon</type>,
11903 <type>circle</type>.
11904 </para>
11905 <para>
11906 <literal>box '(1,1),(0,0)' &amp;&lt;| box '(2,2),(0,0)'</literal>
11907 <returnvalue>t</returnvalue>
11908 </para></entry>
11909 </row>
11910
11911 <row>
11912 <entry role="func_table_entry"><para role="func_signature">
11913 <replaceable>geometric_type</replaceable> <literal>|&amp;&gt;</literal> <replaceable>geometric_type</replaceable>
11914 <returnvalue>boolean</returnvalue>
11915 </para>
11916 <para>
11917 Does first object not extend below second?
11918 Available for <type>box</type>, <type>polygon</type>,
11919 <type>circle</type>.
11920 </para>
11921 <para>
11922 <literal>box '(3,3),(0,0)' |&amp;&gt; box '(2,2),(0,0)'</literal>
11923 <returnvalue>t</returnvalue>
11924 </para></entry>
11925 </row>
11926
11927 <row>
11928 <entry role="func_table_entry"><para role="func_signature">
11929 <type>box</type> <literal>&lt;^</literal> <type>box</type>
11930 <returnvalue>boolean</returnvalue>
11931 </para>
11932 <para>
11933 Is first object below second (allows edges to touch)?
11934 </para>
11935 <para>
11936 <literal>box '((1,1),(0,0))' &lt;^ box '((2,2),(1,1))'</literal>
11937 <returnvalue>t</returnvalue>
11938 </para></entry>
11939 </row>
11940
11941 <row>
11942 <entry role="func_table_entry"><para role="func_signature">
11943 <type>box</type> <literal>&gt;^</literal> <type>box</type>
11944 <returnvalue>boolean</returnvalue>
11945 </para>
11946 <para>
11947 Is first object above second (allows edges to touch)?
11948 </para>
11949 <para>
11950 <literal>box '((2,2),(1,1))' &gt;^ box '((1,1),(0,0))'</literal>
11951 <returnvalue>t</returnvalue>
11952 </para></entry>
11953 </row>
11954
11955 <row>
11956 <entry role="func_table_entry"><para role="func_signature">
11957 <replaceable>geometric_type</replaceable> <literal>?#</literal> <replaceable>geometric_type</replaceable>
11958 <returnvalue>boolean</returnvalue>
11959 </para>
11960 <para>
11961 Do these objects intersect?
11962 Available for these pairs of types:
11963 (<type>box</type>, <type>box</type>),
11964 (<type>lseg</type>, <type>box</type>),
11965 (<type>lseg</type>, <type>lseg</type>),
11966 (<type>lseg</type>, <type>line</type>),
11967 (<type>line</type>, <type>box</type>),
11968 (<type>line</type>, <type>line</type>),
11969 (<type>path</type>, <type>path</type>).
11970 </para>
11971 <para>
11972 <literal>lseg '[(-1,0),(1,0)]' ?# box '(2,2),(-2,-2)'</literal>
11973 <returnvalue>t</returnvalue>
11974 </para></entry>
11975 </row>
11976
11977 <row>
11978 <entry role="func_table_entry"><para role="func_signature">
11979 <literal>?-</literal> <type>line</type>
11980 <returnvalue>boolean</returnvalue>
11981 </para>
11982 <para role="func_signature">
11983 <literal>?-</literal> <type>lseg</type>
11984 <returnvalue>boolean</returnvalue>
11985 </para>
11986 <para>
11987 Is line horizontal?
11988 </para>
11989 <para>
11990 <literal>?- lseg '[(-1,0),(1,0)]'</literal>
11991 <returnvalue>t</returnvalue>
11992 </para></entry>
11993 </row>
11994
11995 <row>
11996 <entry role="func_table_entry"><para role="func_signature">
11997 <type>point</type> <literal>?-</literal> <type>point</type>
11998 <returnvalue>boolean</returnvalue>
11999 </para>
12000 <para>
12001 Are points horizontally aligned (that is, have same y coordinate)?
12002 </para>
12003 <para>
12004 <literal>point '(1,0)' ?- point '(0,0)'</literal>
12005 <returnvalue>t</returnvalue>
12006 </para></entry>
12007 </row>
12008
12009 <row>
12010 <entry role="func_table_entry"><para role="func_signature">
12011 <literal>?|</literal> <type>line</type>
12012 <returnvalue>boolean</returnvalue>
12013 </para>
12014 <para role="func_signature">
12015 <literal>?|</literal> <type>lseg</type>
12016 <returnvalue>boolean</returnvalue>
12017 </para>
12018 <para>
12019 Is line vertical?
12020 </para>
12021 <para>
12022 <literal>?| lseg '[(-1,0),(1,0)]'</literal>
12023 <returnvalue>f</returnvalue>
12024 </para></entry>
12025 </row>
12026
12027 <row>
12028 <entry role="func_table_entry"><para role="func_signature">
12029 <type>point</type> <literal>?|</literal> <type>point</type>
12030 <returnvalue>boolean</returnvalue>
12031 </para>
12032 <para>
12033 Are points vertically aligned (that is, have same x coordinate)?
12034 </para>
12035 <para>
12036 <literal>point '(0,1)' ?| point '(0,0)'</literal>
12037 <returnvalue>t</returnvalue>
12038 </para></entry>
12039 </row>
12040
12041 <row>
12042 <entry role="func_table_entry"><para role="func_signature">
12043 <type>line</type> <literal>?-|</literal> <type>line</type>
12044 <returnvalue>boolean</returnvalue>
12045 </para>
12046 <para role="func_signature">
12047 <type>lseg</type> <literal>?-|</literal> <type>lseg</type>
12048 <returnvalue>boolean</returnvalue>
12049 </para>
12050 <para>
12051 Are lines perpendicular?
12052 </para>
12053 <para>
12054 <literal>lseg '[(0,0),(0,1)]' ?-| lseg '[(0,0),(1,0)]'</literal>
12055 <returnvalue>t</returnvalue>
12056 </para></entry>
12057 </row>
12058
12059 <row>
12060 <entry role="func_table_entry"><para role="func_signature">
12061 <type>line</type> <literal>?||</literal> <type>line</type>
12062 <returnvalue>boolean</returnvalue>
12063 </para>
12064 <para role="func_signature">
12065 <type>lseg</type> <literal>?||</literal> <type>lseg</type>
12066 <returnvalue>boolean</returnvalue>
12067 </para>
12068 <para>
12069 Are lines parallel?
12070 </para>
12071 <para>
12072 <literal>lseg '[(-1,0),(1,0)]' ?|| lseg '[(-1,2),(1,2)]'</literal>
12073 <returnvalue>t</returnvalue>
12074 </para></entry>
12075 </row>
12076
12077 <row>
12078 <entry role="func_table_entry"><para role="func_signature">
12079 <replaceable>geometric_type</replaceable> <literal>~=</literal> <replaceable>geometric_type</replaceable>
12080 <returnvalue>boolean</returnvalue>
12081 </para>
12082 <para>
12083 Are these objects the same?
12084 Available for <type>point</type>, <type>box</type>,
12085 <type>polygon</type>, <type>circle</type>.
12086 </para>
12087 <para>
12088 <literal>polygon '((0,0),(1,1))' ~= polygon '((1,1),(0,0))'</literal>
12089 <returnvalue>t</returnvalue>
12090 </para></entry>
12091 </row>
12092 </tbody>
12093 </tgroup>
12094 </table>
12095
12096 <caution>
12097 <para>
12098 Note that the <quote>same as</quote> operator, <literal>~=</literal>,
12099 represents the usual notion of equality for the <type>point</type>,
12100 <type>box</type>, <type>polygon</type>, and <type>circle</type> types.
12101 Some of the geometric types also have an <literal>=</literal> operator, but
12102 <literal>=</literal> compares for equal <emphasis>areas</emphasis> only.
12103 The other scalar comparison operators (<literal>&lt;=</literal> and so
12104 on), where available for these types, likewise compare areas.
12105 </para>
12106 </caution>
12107
12108 <note>
12109 <para>
12110 Before <productname>PostgreSQL</productname> 14, the point
12111 is strictly below/above comparison operators <type>point</type>
12112 <literal>&lt;&lt;|</literal> <type>point</type> and <type>point</type>
12113 <literal>|&gt;&gt;</literal> <type>point</type> were respectively
12114 called <literal>&lt;^</literal> and <literal>&gt;^</literal>. These
12115 names are still available, but are deprecated and will eventually be
12116 removed.
12117 </para>
12118 </note>
12119
12120 <table id="functions-geometry-func-table">
12121 <title>Geometric Functions</title>
12122 <tgroup cols="1">
12123 <thead>
12124 <row>
12125 <entry role="func_table_entry"><para role="func_signature">
12126 Function
12127 </para>
12128 <para>
12129 Description
12130 </para>
12131 <para>
12132 Example(s)
12133 </para></entry>
12134 </row>
12135 </thead>
12136
12137 <tbody>
12138 <row>
12139 <entry role="func_table_entry"><para role="func_signature">
12140 <indexterm>
12141 <primary>area</primary>
12142 </indexterm>
12143 <function>area</function> ( <replaceable>geometric_type</replaceable> )
12144 <returnvalue>double precision</returnvalue>
12145 </para>
12146 <para>
12147 Computes area.
12148 Available for <type>box</type>, <type>path</type>, <type>circle</type>.
12149 A <type>path</type> input must be closed, else NULL is returned.
12150 Also, if the <type>path</type> is self-intersecting, the result may be
12151 meaningless.
12152 </para>
12153 <para>
12154 <literal>area(box '(2,2),(0,0)')</literal>
12155 <returnvalue>4</returnvalue>
12156 </para></entry>
12157 </row>
12158
12159 <row>
12160 <entry role="func_table_entry"><para role="func_signature">
12161 <indexterm>
12162 <primary>center</primary>
12163 </indexterm>
12164 <function>center</function> ( <replaceable>geometric_type</replaceable> )
12165 <returnvalue>point</returnvalue>
12166 </para>
12167 <para>
12168 Computes center point.
12169 Available for <type>box</type>, <type>circle</type>.
12170 </para>
12171 <para>
12172 <literal>center(box '(1,2),(0,0)')</literal>
12173 <returnvalue>(0.5,1)</returnvalue>
12174 </para></entry>
12175 </row>
12176
12177 <row>
12178 <entry role="func_table_entry"><para role="func_signature">
12179 <indexterm>
12180 <primary>diagonal</primary>
12181 </indexterm>
12182 <function>diagonal</function> ( <type>box</type> )
12183 <returnvalue>lseg</returnvalue>
12184 </para>
12185 <para>
12186 Extracts box's diagonal as a line segment
12187 (same as <function>lseg(box)</function>).
12188 </para>
12189 <para>
12190 <literal>diagonal(box '(1,2),(0,0)')</literal>
12191 <returnvalue>[(1,2),(0,0)]</returnvalue>
12192 </para></entry>
12193 </row>
12194
12195 <row>
12196 <entry role="func_table_entry"><para role="func_signature">
12197 <indexterm>
12198 <primary>diameter</primary>
12199 </indexterm>
12200 <function>diameter</function> ( <type>circle</type> )
12201 <returnvalue>double precision</returnvalue>
12202 </para>
12203 <para>
12204 Computes diameter of circle.
12205 </para>
12206 <para>
12207 <literal>diameter(circle '&lt;(0,0),2&gt;')</literal>
12208 <returnvalue>4</returnvalue>
12209 </para></entry>
12210 </row>
12211
12212 <row>
12213 <entry role="func_table_entry"><para role="func_signature">
12214 <indexterm>
12215 <primary>height</primary>
12216 </indexterm>
12217 <function>height</function> ( <type>box</type> )
12218 <returnvalue>double precision</returnvalue>
12219 </para>
12220 <para>
12221 Computes vertical size of box.
12222 </para>
12223 <para>
12224 <literal>height(box '(1,2),(0,0)')</literal>
12225 <returnvalue>2</returnvalue>
12226 </para></entry>
12227 </row>
12228
12229 <row>
12230 <entry role="func_table_entry"><para role="func_signature">
12231 <indexterm>
12232 <primary>isclosed</primary>
12233 </indexterm>
12234 <function>isclosed</function> ( <type>path</type> )
12235 <returnvalue>boolean</returnvalue>
12236 </para>
12237 <para>
12238 Is path closed?
12239 </para>
12240 <para>
12241 <literal>isclosed(path '((0,0),(1,1),(2,0))')</literal>
12242 <returnvalue>t</returnvalue>
12243 </para></entry>
12244 </row>
12245
12246 <row>
12247 <entry role="func_table_entry"><para role="func_signature">
12248 <indexterm>
12249 <primary>isopen</primary>
12250 </indexterm>
12251 <function>isopen</function> ( <type>path</type> )
12252 <returnvalue>boolean</returnvalue>
12253 </para>
12254 <para>
12255 Is path open?
12256 </para>
12257 <para>
12258 <literal>isopen(path '[(0,0),(1,1),(2,0)]')</literal>
12259 <returnvalue>t</returnvalue>
12260 </para></entry>
12261 </row>
12262
12263 <row>
12264 <entry role="func_table_entry"><para role="func_signature">
12265 <indexterm>
12266 <primary>length</primary>
12267 </indexterm>
12268 <function>length</function> ( <replaceable>geometric_type</replaceable> )
12269 <returnvalue>double precision</returnvalue>
12270 </para>
12271 <para>
12272 Computes the total length.
12273 Available for <type>lseg</type>, <type>path</type>.
12274 </para>
12275 <para>
12276 <literal>length(path '((-1,0),(1,0))')</literal>
12277 <returnvalue>4</returnvalue>
12278 </para></entry>
12279 </row>
12280
12281 <row>
12282 <entry role="func_table_entry"><para role="func_signature">
12283 <indexterm>
12284 <primary>npoints</primary>
12285 </indexterm>
12286 <function>npoints</function> ( <replaceable>geometric_type</replaceable> )
12287 <returnvalue>integer</returnvalue>
12288 </para>
12289 <para>
12290 Returns the number of points.
12291 Available for <type>path</type>, <type>polygon</type>.
12292 </para>
12293 <para>
12294 <literal>npoints(path '[(0,0),(1,1),(2,0)]')</literal>
12295 <returnvalue>3</returnvalue>
12296 </para></entry>
12297 </row>
12298
12299 <row>
12300 <entry role="func_table_entry"><para role="func_signature">
12301 <indexterm>
12302 <primary>pclose</primary>
12303 </indexterm>
12304 <function>pclose</function> ( <type>path</type> )
12305 <returnvalue>path</returnvalue>
12306 </para>
12307 <para>
12308 Converts path to closed form.
12309 </para>
12310 <para>
12311 <literal>pclose(path '[(0,0),(1,1),(2,0)]')</literal>
12312 <returnvalue>((0,0),(1,1),(2,0))</returnvalue>
12313 </para></entry>
12314 </row>
12315
12316 <row>
12317 <entry role="func_table_entry"><para role="func_signature">
12318 <indexterm>
12319 <primary>popen</primary>
12320 </indexterm>
12321 <function>popen</function> ( <type>path</type> )
12322 <returnvalue>path</returnvalue>
12323 </para>
12324 <para>
12325 Converts path to open form.
12326 </para>
12327 <para>
12328 <literal>popen(path '((0,0),(1,1),(2,0))')</literal>
12329 <returnvalue>[(0,0),(1,1),(2,0)]</returnvalue>
12330 </para></entry>
12331 </row>
12332
12333 <row>
12334 <entry role="func_table_entry"><para role="func_signature">
12335 <indexterm>
12336 <primary>radius</primary>
12337 </indexterm>
12338 <function>radius</function> ( <type>circle</type> )
12339 <returnvalue>double precision</returnvalue>
12340 </para>
12341 <para>
12342 Computes radius of circle.
12343 </para>
12344 <para>
12345 <literal>radius(circle '&lt;(0,0),2&gt;')</literal>
12346 <returnvalue>2</returnvalue>
12347 </para></entry>
12348 </row>
12349
12350 <row>
12351 <entry role="func_table_entry"><para role="func_signature">
12352 <indexterm>
12353 <primary>slope</primary>
12354 </indexterm>
12355 <function>slope</function> ( <type>point</type>, <type>point</type> )
12356 <returnvalue>double precision</returnvalue>
12357 </para>
12358 <para>
12359 Computes slope of a line drawn through the two points.
12360 </para>
12361 <para>
12362 <literal>slope(point '(0,0)', point '(2,1)')</literal>
12363 <returnvalue>0.5</returnvalue>
12364 </para></entry>
12365 </row>
12366
12367 <row>
12368 <entry role="func_table_entry"><para role="func_signature">
12369 <indexterm>
12370 <primary>width</primary>
12371 </indexterm>
12372 <function>width</function> ( <type>box</type> )
12373 <returnvalue>double precision</returnvalue>
12374 </para>
12375 <para>
12376 Computes horizontal size of box.
12377 </para>
12378 <para>
12379 <literal>width(box '(1,2),(0,0)')</literal>
12380 <returnvalue>1</returnvalue>
12381 </para></entry>
12382 </row>
12383 </tbody>
12384 </tgroup>
12385 </table>
12386
12387 <table id="functions-geometry-conv-table">
12388 <title>Geometric Type Conversion Functions</title>
12389 <tgroup cols="1">
12390 <thead>
12391 <row>
12392 <entry role="func_table_entry"><para role="func_signature">
12393 Function
12394 </para>
12395 <para>
12396 Description
12397 </para>
12398 <para>
12399 Example(s)
12400 </para></entry>
12401 </row>
12402 </thead>
12403 <tbody>
12404
12405 <row>
12406 <entry role="func_table_entry"><para role="func_signature">
12407 <indexterm>
12408 <primary>box</primary>
12409 </indexterm>
12410 <function>box</function> ( <type>circle</type> )
12411 <returnvalue>box</returnvalue>
12412 </para>
12413 <para>
12414 Computes box inscribed within the circle.
12415 </para>
12416 <para>
12417 <literal>box(circle '&lt;(0,0),2&gt;')</literal>
12418 <returnvalue>(1.414213562373095,1.414213562373095),&zwsp;(-1.414213562373095,-1.414213562373095)</returnvalue>
12419 </para></entry>
12420 </row>
12421
12422 <row>
12423 <entry role="func_table_entry"><para role="func_signature">
12424 <function>box</function> ( <type>point</type> )
12425 <returnvalue>box</returnvalue>
12426 </para>
12427 <para>
12428 Converts point to empty box.
12429 </para>
12430 <para>
12431 <literal>box(point '(1,0)')</literal>
12432 <returnvalue>(1,0),(1,0)</returnvalue>
12433 </para></entry>
12434 </row>
12435
12436 <row>
12437 <entry role="func_table_entry"><para role="func_signature">
12438 <function>box</function> ( <type>point</type>, <type>point</type> )
12439 <returnvalue>box</returnvalue>
12440 </para>
12441 <para>
12442 Converts any two corner points to box.
12443 </para>
12444 <para>
12445 <literal>box(point '(0,1)', point '(1,0)')</literal>
12446 <returnvalue>(1,1),(0,0)</returnvalue>
12447 </para></entry>
12448 </row>
12449
12450 <row>
12451 <entry role="func_table_entry"><para role="func_signature">
12452 <function>box</function> ( <type>polygon</type> )
12453 <returnvalue>box</returnvalue>
12454 </para>
12455 <para>
12456 Computes bounding box of polygon.
12457 </para>
12458 <para>
12459 <literal>box(polygon '((0,0),(1,1),(2,0))')</literal>
12460 <returnvalue>(2,1),(0,0)</returnvalue>
12461 </para></entry>
12462 </row>
12463
12464 <row>
12465 <entry role="func_table_entry"><para role="func_signature">
12466 <indexterm>
12467 <primary>bound_box</primary>
12468 </indexterm>
12469 <function>bound_box</function> ( <type>box</type>, <type>box</type> )
12470 <returnvalue>box</returnvalue>
12471 </para>
12472 <para>
12473 Computes bounding box of two boxes.
12474 </para>
12475 <para>
12476 <literal>bound_box(box '(1,1),(0,0)', box '(4,4),(3,3)')</literal>
12477 <returnvalue>(4,4),(0,0)</returnvalue>
12478 </para></entry>
12479 </row>
12480
12481 <row>
12482 <entry role="func_table_entry"><para role="func_signature">
12483 <indexterm>
12484 <primary>circle</primary>
12485 </indexterm>
12486 <function>circle</function> ( <type>box</type> )
12487 <returnvalue>circle</returnvalue>
12488 </para>
12489 <para>
12490 Computes smallest circle enclosing box.
12491 </para>
12492 <para>
12493 <literal>circle(box '(1,1),(0,0)')</literal>
12494 <returnvalue>&lt;(0.5,0.5),0.7071067811865476&gt;</returnvalue>
12495 </para></entry>
12496 </row>
12497
12498 <row>
12499 <entry role="func_table_entry"><para role="func_signature">
12500 <function>circle</function> ( <type>point</type>, <type>double precision</type> )
12501 <returnvalue>circle</returnvalue>
12502 </para>
12503 <para>
12504 Constructs circle from center and radius.
12505 </para>
12506 <para>
12507 <literal>circle(point '(0,0)', 2.0)</literal>
12508 <returnvalue>&lt;(0,0),2&gt;</returnvalue>
12509 </para></entry>
12510 </row>
12511
12512 <row>
12513 <entry role="func_table_entry"><para role="func_signature">
12514 <function>circle</function> ( <type>polygon</type> )
12515 <returnvalue>circle</returnvalue>
12516 </para>
12517 <para>
12518 Converts polygon to circle. The circle's center is the mean of the
12519 positions of the polygon's points, and the radius is the average
12520 distance of the polygon's points from that center.
12521 </para>
12522 <para>
12523 <literal>circle(polygon '((0,0),(1,3),(2,0))')</literal>
12524 <returnvalue>&lt;(1,1),1.6094757082487299&gt;</returnvalue>
12525 </para></entry>
12526 </row>
12527
12528 <row>
12529 <entry role="func_table_entry"><para role="func_signature">
12530 <indexterm>
12531 <primary>line</primary>
12532 </indexterm>
12533 <function>line</function> ( <type>point</type>, <type>point</type> )
12534 <returnvalue>line</returnvalue>
12535 </para>
12536 <para>
12537 Converts two points to the line through them.
12538 </para>
12539 <para>
12540 <literal>line(point '(-1,0)', point '(1,0)')</literal>
12541 <returnvalue>{0,-1,0}</returnvalue>
12542 </para></entry>
12543 </row>
12544
12545 <row>
12546 <entry role="func_table_entry"><para role="func_signature">
12547 <indexterm>
12548 <primary>lseg</primary>
12549 </indexterm>
12550 <function>lseg</function> ( <type>box</type> )
12551 <returnvalue>lseg</returnvalue>
12552 </para>
12553 <para>
12554 Extracts box's diagonal as a line segment.
12555 </para>
12556 <para>
12557 <literal>lseg(box '(1,0),(-1,0)')</literal>
12558 <returnvalue>[(1,0),(-1,0)]</returnvalue>
12559 </para></entry>
12560 </row>
12561
12562 <row>
12563 <entry role="func_table_entry"><para role="func_signature">
12564 <function>lseg</function> ( <type>point</type>, <type>point</type> )
12565 <returnvalue>lseg</returnvalue>
12566 </para>
12567 <para>
12568 Constructs line segment from two endpoints.
12569 </para>
12570 <para>
12571 <literal>lseg(point '(-1,0)', point '(1,0)')</literal>
12572 <returnvalue>[(-1,0),(1,0)]</returnvalue>
12573 </para></entry>
12574 </row>
12575
12576 <row>
12577 <entry role="func_table_entry"><para role="func_signature">
12578 <indexterm>
12579 <primary>path</primary>
12580 </indexterm>
12581 <function>path</function> ( <type>polygon</type> )
12582 <returnvalue>path</returnvalue>
12583 </para>
12584 <para>
12585 Converts polygon to a closed path with the same list of points.
12586 </para>
12587 <para>
12588 <literal>path(polygon '((0,0),(1,1),(2,0))')</literal>
12589 <returnvalue>((0,0),(1,1),(2,0))</returnvalue>
12590 </para></entry>
12591 </row>
12592
12593 <row>
12594 <entry role="func_table_entry"><para role="func_signature">
12595 <indexterm>
12596 <primary>point</primary>
12597 </indexterm>
12598 <function>point</function> ( <type>double precision</type>, <type>double precision</type> )
12599 <returnvalue>point</returnvalue>
12600 </para>
12601 <para>
12602 Constructs point from its coordinates.
12603 </para>
12604 <para>
12605 <literal>point(23.4, -44.5)</literal>
12606 <returnvalue>(23.4,-44.5)</returnvalue>
12607 </para></entry>
12608 </row>
12609
12610 <row>
12611 <entry role="func_table_entry"><para role="func_signature">
12612 <function>point</function> ( <type>box</type> )
12613 <returnvalue>point</returnvalue>
12614 </para>
12615 <para>
12616 Computes center of box.
12617 </para>
12618 <para>
12619 <literal>point(box '(1,0),(-1,0)')</literal>
12620 <returnvalue>(0,0)</returnvalue>
12621 </para></entry>
12622 </row>
12623
12624 <row>
12625 <entry role="func_table_entry"><para role="func_signature">
12626 <function>point</function> ( <type>circle</type> )
12627 <returnvalue>point</returnvalue>
12628 </para>
12629 <para>
12630 Computes center of circle.
12631 </para>
12632 <para>
12633 <literal>point(circle '&lt;(0,0),2&gt;')</literal>
12634 <returnvalue>(0,0)</returnvalue>
12635 </para></entry>
12636 </row>
12637
12638 <row>
12639 <entry role="func_table_entry"><para role="func_signature">
12640 <function>point</function> ( <type>lseg</type> )
12641 <returnvalue>point</returnvalue>
12642 </para>
12643 <para>
12644 Computes center of line segment.
12645 </para>
12646 <para>
12647 <literal>point(lseg '[(-1,0),(1,0)]')</literal>
12648 <returnvalue>(0,0)</returnvalue>
12649 </para></entry>
12650 </row>
12651
12652 <row>
12653 <entry role="func_table_entry"><para role="func_signature">
12654 <function>point</function> ( <type>polygon</type> )
12655 <returnvalue>point</returnvalue>
12656 </para>
12657 <para>
12658 Computes center of polygon (the mean of the
12659 positions of the polygon's points).
12660 </para>
12661 <para>
12662 <literal>point(polygon '((0,0),(1,1),(2,0))')</literal>
12663 <returnvalue>(1,0.3333333333333333)</returnvalue>
12664 </para></entry>
12665 </row>
12666
12667 <row>
12668 <entry role="func_table_entry"><para role="func_signature">
12669 <indexterm>
12670 <primary>polygon</primary>
12671 </indexterm>
12672 <function>polygon</function> ( <type>box</type> )
12673 <returnvalue>polygon</returnvalue>
12674 </para>
12675 <para>
12676 Converts box to a 4-point polygon.
12677 </para>
12678 <para>
12679 <literal>polygon(box '(1,1),(0,0)')</literal>
12680 <returnvalue>((0,0),(0,1),(1,1),(1,0))</returnvalue>
12681 </para></entry>
12682 </row>
12683
12684 <row>
12685 <entry role="func_table_entry"><para role="func_signature">
12686 <function>polygon</function> ( <type>circle</type> )
12687 <returnvalue>polygon</returnvalue>
12688 </para>
12689 <para>
12690 Converts circle to a 12-point polygon.
12691 </para>
12692 <para>
12693 <literal>polygon(circle '&lt;(0,0),2&gt;')</literal>
12694 <returnvalue>((-2,0),&zwsp;(-1.7320508075688774,0.9999999999999999),&zwsp;(-1.0000000000000002,1.7320508075688772),&zwsp;(-1.2246063538223773e-16,2),&zwsp;(0.9999999999999996,1.7320508075688774),&zwsp;(1.732050807568877,1.0000000000000007),&zwsp;(2,2.4492127076447545e-16),&zwsp;(1.7320508075688776,-0.9999999999999994),&zwsp;(1.0000000000000009,-1.7320508075688767),&zwsp;(3.673819061467132e-16,-2),&zwsp;(-0.9999999999999987,-1.732050807568878),&zwsp;(-1.7320508075688767,-1.0000000000000009))</returnvalue>
12695 </para></entry>
12696 </row>
12697
12698 <row>
12699 <entry role="func_table_entry"><para role="func_signature">
12700 <function>polygon</function> ( <type>integer</type>, <type>circle</type> )
12701 <returnvalue>polygon</returnvalue>
12702 </para>
12703 <para>
12704 Converts circle to an <replaceable>n</replaceable>-point polygon.
12705 </para>
12706 <para>
12707 <literal>polygon(4, circle '&lt;(3,0),1&gt;')</literal>
12708 <returnvalue>((2,0),&zwsp;(3,1),&zwsp;(4,1.2246063538223773e-16),&zwsp;(3,-1))</returnvalue>
12709 </para></entry>
12710 </row>
12711
12712 <row>
12713 <entry role="func_table_entry"><para role="func_signature">
12714 <function>polygon</function> ( <type>path</type> )
12715 <returnvalue>polygon</returnvalue>
12716 </para>
12717 <para>
12718 Converts closed path to a polygon with the same list of points.
12719 </para>
12720 <para>
12721 <literal>polygon(path '((0,0),(1,1),(2,0))')</literal>
12722 <returnvalue>((0,0),(1,1),(2,0))</returnvalue>
12723 </para></entry>
12724 </row>
12725
12726 </tbody>
12727 </tgroup>
12728 </table>
12729
12730 <para>
12731 It is possible to access the two component numbers of a <type>point</type>
12732 as though the point were an array with indexes 0 and 1. For example, if
12733 <literal>t.p</literal> is a <type>point</type> column then
12734 <literal>SELECT p[0] FROM t</literal> retrieves the X coordinate and
12735 <literal>UPDATE t SET p[1] = ...</literal> changes the Y coordinate.
12736 In the same way, a value of type <type>box</type> or <type>lseg</type> can be treated
12737 as an array of two <type>point</type> values.
12738 </para>
12739
12740 </sect1>
12741
12742
12743 <sect1 id="functions-net">
12744 <title>Network Address Functions and Operators</title>
12745
12746 <para>
12747 The IP network address types, <type>cidr</type> and <type>inet</type>,
12748 support the usual comparison operators shown in
12749 <xref linkend="functions-comparison-op-table"/>
12750 as well as the specialized operators and functions shown in
12751 <xref linkend="cidr-inet-operators-table"/> and
12752 <xref linkend="cidr-inet-functions-table"/>.
12753 </para>
12754
12755 <para>
12756 Any <type>cidr</type> value can be cast to <type>inet</type> implicitly;
12757 therefore, the operators and functions shown below as operating on
12758 <type>inet</type> also work on <type>cidr</type> values. (Where there are
12759 separate functions for <type>inet</type> and <type>cidr</type>, it is
12760 because the behavior should be different for the two cases.)
12761 Also, it is permitted to cast an <type>inet</type> value
12762 to <type>cidr</type>. When this is done, any bits to the right of the
12763 netmask are silently zeroed to create a valid <type>cidr</type> value.
12764 </para>
12765
12766 <table id="cidr-inet-operators-table">
12767 <title>IP Address Operators</title>
12768 <tgroup cols="1">
12769 <thead>
12770 <row>
12771 <entry role="func_table_entry"><para role="func_signature">
12772 Operator
12773 </para>
12774 <para>
12775 Description
12776 </para>
12777 <para>
12778 Example(s)
12779 </para></entry>
12780 </row>
12781 </thead>
12782
12783 <tbody>
12784 <row>
12785 <entry role="func_table_entry"><para role="func_signature">
12786 <type>inet</type> <literal>&lt;&lt;</literal> <type>inet</type>
12787 <returnvalue>boolean</returnvalue>
12788 </para>
12789 <para>
12790 Is subnet strictly contained by subnet?
12791 This operator, and the next four, test for subnet inclusion. They
12792 consider only the network parts of the two addresses (ignoring any
12793 bits to the right of the netmasks) and determine whether one network
12794 is identical to or a subnet of the other.
12795 </para>
12796 <para>
12797 <literal>inet '192.168.1.5' &lt;&lt; inet '192.168.1/24'</literal>
12798 <returnvalue>t</returnvalue>
12799 </para>
12800 <para>
12801 <literal>inet '192.168.0.5' &lt;&lt; inet '192.168.1/24'</literal>
12802 <returnvalue>f</returnvalue>
12803 </para>
12804 <para>
12805 <literal>inet '192.168.1/24' &lt;&lt; inet '192.168.1/24'</literal>
12806 <returnvalue>f</returnvalue>
12807 </para></entry>
12808 </row>
12809
12810 <row>
12811 <entry role="func_table_entry"><para role="func_signature">
12812 <type>inet</type> <literal>&lt;&lt;=</literal> <type>inet</type>
12813 <returnvalue>boolean</returnvalue>
12814 </para>
12815 <para>
12816 Is subnet contained by or equal to subnet?
12817 </para>
12818 <para>
12819 <literal>inet '192.168.1/24' &lt;&lt;= inet '192.168.1/24'</literal>
12820 <returnvalue>t</returnvalue>
12821 </para></entry>
12822 </row>
12823
12824 <row>
12825 <entry role="func_table_entry"><para role="func_signature">
12826 <type>inet</type> <literal>&gt;&gt;</literal> <type>inet</type>
12827 <returnvalue>boolean</returnvalue>
12828 </para>
12829 <para>
12830 Does subnet strictly contain subnet?
12831 </para>
12832 <para>
12833 <literal>inet '192.168.1/24' &gt;&gt; inet '192.168.1.5'</literal>
12834 <returnvalue>t</returnvalue>
12835 </para></entry>
12836 </row>
12837
12838 <row>
12839 <entry role="func_table_entry"><para role="func_signature">
12840 <type>inet</type> <literal>&gt;&gt;=</literal> <type>inet</type>
12841 <returnvalue>boolean</returnvalue>
12842 </para>
12843 <para>
12844 Does subnet contain or equal subnet?
12845 </para>
12846 <para>
12847 <literal>inet '192.168.1/24' &gt;&gt;= inet '192.168.1/24'</literal>
12848 <returnvalue>t</returnvalue>
12849 </para></entry>
12850 </row>
12851
12852 <row>
12853 <entry role="func_table_entry"><para role="func_signature">
12854 <type>inet</type> <literal>&amp;&amp;</literal> <type>inet</type>
12855 <returnvalue>boolean</returnvalue>
12856 </para>
12857 <para>
12858 Does either subnet contain or equal the other?
12859 </para>
12860 <para>
12861 <literal>inet '192.168.1/24' &amp;&amp; inet '192.168.1.80/28'</literal>
12862 <returnvalue>t</returnvalue>
12863 </para>
12864 <para>
12865 <literal>inet '192.168.1/24' &amp;&amp; inet '192.168.2.0/28'</literal>
12866 <returnvalue>f</returnvalue>
12867 </para></entry>
12868 </row>
12869
12870 <row>
12871 <entry role="func_table_entry"><para role="func_signature">
12872 <literal>~</literal> <type>inet</type>
12873 <returnvalue>inet</returnvalue>
12874 </para>
12875 <para>
12876 Computes bitwise NOT.
12877 </para>
12878 <para>
12879 <literal>~ inet '192.168.1.6'</literal>
12880 <returnvalue>63.87.254.249</returnvalue>
12881 </para></entry>
12882 </row>
12883
12884 <row>
12885 <entry role="func_table_entry"><para role="func_signature">
12886 <type>inet</type> <literal>&amp;</literal> <type>inet</type>
12887 <returnvalue>inet</returnvalue>
12888 </para>
12889 <para>
12890 Computes bitwise AND.
12891 </para>
12892 <para>
12893 <literal>inet '192.168.1.6' &amp; inet '0.0.0.255'</literal>
12894 <returnvalue>0.0.0.6</returnvalue>
12895 </para></entry>
12896 </row>
12897
12898 <row>
12899 <entry role="func_table_entry"><para role="func_signature">
12900 <type>inet</type> <literal>|</literal> <type>inet</type>
12901 <returnvalue>inet</returnvalue>
12902 </para>
12903 <para>
12904 Computes bitwise OR.
12905 </para>
12906 <para>
12907 <literal>inet '192.168.1.6' | inet '0.0.0.255'</literal>
12908 <returnvalue>192.168.1.255</returnvalue>
12909 </para></entry>
12910 </row>
12911
12912 <row>
12913 <entry role="func_table_entry"><para role="func_signature">
12914 <type>inet</type> <literal>+</literal> <type>bigint</type>
12915 <returnvalue>inet</returnvalue>
12916 </para>
12917 <para>
12918 Adds an offset to an address.
12919 </para>
12920 <para>
12921 <literal>inet '192.168.1.6' + 25</literal>
12922 <returnvalue>192.168.1.31</returnvalue>
12923 </para></entry>
12924 </row>
12925
12926 <row>
12927 <entry role="func_table_entry"><para role="func_signature">
12928 <type>bigint</type> <literal>+</literal> <type>inet</type>
12929 <returnvalue>inet</returnvalue>
12930 </para>
12931 <para>
12932 Adds an offset to an address.
12933 </para>
12934 <para>
12935 <literal>200 + inet '::ffff:fff0:1'</literal>
12936 <returnvalue>::ffff:255.240.0.201</returnvalue>
12937 </para></entry>
12938 </row>
12939
12940 <row>
12941 <entry role="func_table_entry"><para role="func_signature">
12942 <type>inet</type> <literal>-</literal> <type>bigint</type>
12943 <returnvalue>inet</returnvalue>
12944 </para>
12945 <para>
12946 Subtracts an offset from an address.
12947 </para>
12948 <para>
12949 <literal>inet '192.168.1.43' - 36</literal>
12950 <returnvalue>192.168.1.7</returnvalue>
12951 </para></entry>
12952 </row>
12953
12954 <row>
12955 <entry role="func_table_entry"><para role="func_signature">
12956 <type>inet</type> <literal>-</literal> <type>inet</type>
12957 <returnvalue>bigint</returnvalue>
12958 </para>
12959 <para>
12960 Computes the difference of two addresses.
12961 </para>
12962 <para>
12963 <literal>inet '192.168.1.43' - inet '192.168.1.19'</literal>
12964 <returnvalue>24</returnvalue>
12965 </para>
12966 <para>
12967 <literal>inet '::1' - inet '::ffff:1'</literal>
12968 <returnvalue>-4294901760</returnvalue>
12969 </para></entry>
12970 </row>
12971 </tbody>
12972 </tgroup>
12973 </table>
12974
12975 <table id="cidr-inet-functions-table">
12976 <title>IP Address Functions</title>
12977 <tgroup cols="1">
12978 <thead>
12979 <row>
12980 <entry role="func_table_entry"><para role="func_signature">
12981 Function
12982 </para>
12983 <para>
12984 Description
12985 </para>
12986 <para>
12987 Example(s)
12988 </para></entry>
12989 </row>
12990 </thead>
12991
12992 <tbody>
12993 <row>
12994 <entry role="func_table_entry"><para role="func_signature">
12995 <indexterm>
12996 <primary>abbrev</primary>
12997 </indexterm>
12998 <function>abbrev</function> ( <type>inet</type> )
12999 <returnvalue>text</returnvalue>
13000 </para>
13001 <para>
13002 Creates an abbreviated display format as text.
13003 (The result is the same as the <type>inet</type> output function
13004 produces; it is <quote>abbreviated</quote> only in comparison to the
13005 result of an explicit cast to <type>text</type>, which for historical
13006 reasons will never suppress the netmask part.)
13007 </para>
13008 <para>
13009 <literal>abbrev(inet '10.1.0.0/32')</literal>
13010 <returnvalue>10.1.0.0</returnvalue>
13011 </para></entry>
13012 </row>
13013
13014 <row>
13015 <entry role="func_table_entry"><para role="func_signature">
13016 <function>abbrev</function> ( <type>cidr</type> )
13017 <returnvalue>text</returnvalue>
13018 </para>
13019 <para>
13020 Creates an abbreviated display format as text.
13021 (The abbreviation consists of dropping all-zero octets to the right
13022 of the netmask; more examples are in
13023 <xref linkend="datatype-net-cidr-table"/>.)
13024 </para>
13025 <para>
13026 <literal>abbrev(cidr '10.1.0.0/16')</literal>
13027 <returnvalue>10.1/16</returnvalue>
13028 </para></entry>
13029 </row>
13030
13031 <row>
13032 <entry role="func_table_entry"><para role="func_signature">
13033 <indexterm>
13034 <primary>broadcast</primary>
13035 </indexterm>
13036 <function>broadcast</function> ( <type>inet</type> )
13037 <returnvalue>inet</returnvalue>
13038 </para>
13039 <para>
13040 Computes the broadcast address for the address's network.
13041 </para>
13042 <para>
13043 <literal>broadcast(inet '192.168.1.5/24')</literal>
13044 <returnvalue>192.168.1.255/24</returnvalue>
13045 </para></entry>
13046 </row>
13047
13048 <row>
13049 <entry role="func_table_entry"><para role="func_signature">
13050 <indexterm>
13051 <primary>family</primary>
13052 </indexterm>
13053 <function>family</function> ( <type>inet</type> )
13054 <returnvalue>integer</returnvalue>
13055 </para>
13056 <para>
13057 Returns the address's family: <literal>4</literal> for IPv4,
13058 <literal>6</literal> for IPv6.
13059 </para>
13060 <para>
13061 <literal>family(inet '::1')</literal>
13062 <returnvalue>6</returnvalue>
13063 </para></entry>
13064 </row>
13065
13066 <row>
13067 <entry role="func_table_entry"><para role="func_signature">
13068 <indexterm>
13069 <primary>host</primary>
13070 </indexterm>
13071 <function>host</function> ( <type>inet</type> )
13072 <returnvalue>text</returnvalue>
13073 </para>
13074 <para>
13075 Returns the IP address as text, ignoring the netmask.
13076 </para>
13077 <para>
13078 <literal>host(inet '192.168.1.0/24')</literal>
13079 <returnvalue>192.168.1.0</returnvalue>
13080 </para></entry>
13081 </row>
13082
13083 <row>
13084 <entry role="func_table_entry"><para role="func_signature">
13085 <indexterm>
13086 <primary>hostmask</primary>
13087 </indexterm>
13088 <function>hostmask</function> ( <type>inet</type> )
13089 <returnvalue>inet</returnvalue>
13090 </para>
13091 <para>
13092 Computes the host mask for the address's network.
13093 </para>
13094 <para>
13095 <literal>hostmask(inet '192.168.23.20/30')</literal>
13096 <returnvalue>0.0.0.3</returnvalue>
13097 </para></entry>
13098 </row>
13099
13100 <row>
13101 <entry role="func_table_entry"><para role="func_signature">
13102 <indexterm>
13103 <primary>inet_merge</primary>
13104 </indexterm>
13105 <function>inet_merge</function> ( <type>inet</type>, <type>inet</type> )
13106 <returnvalue>cidr</returnvalue>
13107 </para>
13108 <para>
13109 Computes the smallest network that includes both of the given networks.
13110 </para>
13111 <para>
13112 <literal>inet_merge(inet '192.168.1.5/24', inet '192.168.2.5/24')</literal>
13113 <returnvalue>192.168.0.0/22</returnvalue>
13114 </para></entry>
13115 </row>
13116
13117 <row>
13118 <entry role="func_table_entry"><para role="func_signature">
13119 <indexterm>
13120 <primary>inet_same_family</primary>
13121 </indexterm>
13122 <function>inet_same_family</function> ( <type>inet</type>, <type>inet</type> )
13123 <returnvalue>boolean</returnvalue>
13124 </para>
13125 <para>
13126 Tests whether the addresses belong to the same IP family.
13127 </para>
13128 <para>
13129 <literal>inet_same_family(inet '192.168.1.5/24', inet '::1')</literal>
13130 <returnvalue>f</returnvalue>
13131 </para></entry>
13132 </row>
13133
13134 <row>
13135 <entry role="func_table_entry"><para role="func_signature">
13136 <indexterm>
13137 <primary>masklen</primary>
13138 </indexterm>
13139 <function>masklen</function> ( <type>inet</type> )
13140 <returnvalue>integer</returnvalue>
13141 </para>
13142 <para>
13143 Returns the netmask length in bits.
13144 </para>
13145 <para>
13146 <literal>masklen(inet '192.168.1.5/24')</literal>
13147 <returnvalue>24</returnvalue>
13148 </para></entry>
13149 </row>
13150
13151 <row>
13152 <entry role="func_table_entry"><para role="func_signature">
13153 <indexterm>
13154 <primary>netmask</primary>
13155 </indexterm>
13156 <function>netmask</function> ( <type>inet</type> )
13157 <returnvalue>inet</returnvalue>
13158 </para>
13159 <para>
13160 Computes the network mask for the address's network.
13161 </para>
13162 <para>
13163 <literal>netmask(inet '192.168.1.5/24')</literal>
13164 <returnvalue>255.255.255.0</returnvalue>
13165 </para></entry>
13166 </row>
13167
13168 <row>
13169 <entry role="func_table_entry"><para role="func_signature">
13170 <indexterm>
13171 <primary>network</primary>
13172 </indexterm>
13173 <function>network</function> ( <type>inet</type> )
13174 <returnvalue>cidr</returnvalue>
13175 </para>
13176 <para>
13177 Returns the network part of the address, zeroing out
13178 whatever is to the right of the netmask.
13179 (This is equivalent to casting the value to <type>cidr</type>.)
13180 </para>
13181 <para>
13182 <literal>network(inet '192.168.1.5/24')</literal>
13183 <returnvalue>192.168.1.0/24</returnvalue>
13184 </para></entry>
13185 </row>
13186
13187 <row>
13188 <entry role="func_table_entry"><para role="func_signature">
13189 <indexterm>
13190 <primary>set_masklen</primary>
13191 </indexterm>
13192 <function>set_masklen</function> ( <type>inet</type>, <type>integer</type> )
13193 <returnvalue>inet</returnvalue>
13194 </para>
13195 <para>
13196 Sets the netmask length for an <type>inet</type> value.
13197 The address part does not change.
13198 </para>
13199 <para>
13200 <literal>set_masklen(inet '192.168.1.5/24', 16)</literal>
13201 <returnvalue>192.168.1.5/16</returnvalue>
13202 </para></entry>
13203 </row>
13204
13205 <row>
13206 <entry role="func_table_entry"><para role="func_signature">
13207 <function>set_masklen</function> ( <type>cidr</type>, <type>integer</type> )
13208 <returnvalue>cidr</returnvalue>
13209 </para>
13210 <para>
13211 Sets the netmask length for a <type>cidr</type> value.
13212 Address bits to the right of the new netmask are set to zero.
13213 </para>
13214 <para>
13215 <literal>set_masklen(cidr '192.168.1.0/24', 16)</literal>
13216 <returnvalue>192.168.0.0/16</returnvalue>
13217 </para></entry>
13218 </row>
13219
13220 <row>
13221 <entry role="func_table_entry"><para role="func_signature">
13222 <indexterm>
13223 <primary>text</primary>
13224 </indexterm>
13225 <function>text</function> ( <type>inet</type> )
13226 <returnvalue>text</returnvalue>
13227 </para>
13228 <para>
13229 Returns the unabbreviated IP address and netmask length as text.
13230 (This has the same result as an explicit cast to <type>text</type>.)
13231 </para>
13232 <para>
13233 <literal>text(inet '192.168.1.5')</literal>
13234 <returnvalue>192.168.1.5/32</returnvalue>
13235 </para></entry>
13236 </row>
13237 </tbody>
13238 </tgroup>
13239 </table>
13240
13241 <tip>
13242 <para>
13243 The <function>abbrev</function>, <function>host</function>,
13244 and <function>text</function> functions are primarily intended to offer
13245 alternative display formats for IP addresses.
13246 </para>
13247 </tip>
13248
13249 <para>
13250 The MAC address types, <type>macaddr</type> and <type>macaddr8</type>,
13251 support the usual comparison operators shown in
13252 <xref linkend="functions-comparison-op-table"/>
13253 as well as the specialized functions shown in
13254 <xref linkend="macaddr-functions-table"/>.
13255 In addition, they support the bitwise logical operators
13256 <literal>~</literal>, <literal>&amp;</literal> and <literal>|</literal>
13257 (NOT, AND and OR), just as shown above for IP addresses.
13258 </para>
13259
13260 <table id="macaddr-functions-table">
13261 <title>MAC Address Functions</title>
13262 <tgroup cols="1">
13263 <thead>
13264 <row>
13265 <entry role="func_table_entry"><para role="func_signature">
13266 Function
13267 </para>
13268 <para>
13269 Description
13270 </para>
13271 <para>
13272 Example(s)
13273 </para></entry>
13274 </row>
13275 </thead>
13276
13277 <tbody>
13278 <row>
13279 <entry role="func_table_entry"><para role="func_signature">
13280 <indexterm>
13281 <primary>trunc</primary>
13282 </indexterm>
13283 <function>trunc</function> ( <type>macaddr</type> )
13284 <returnvalue>macaddr</returnvalue>
13285 </para>
13286 <para>
13287 Sets the last 3 bytes of the address to zero. The remaining prefix
13288 can be associated with a particular manufacturer (using data not
13289 included in <productname>PostgreSQL</productname>).
13290 </para>
13291 <para>
13292 <literal>trunc(macaddr '12:34:56:78:90:ab')</literal>
13293 <returnvalue>12:34:56:00:00:00</returnvalue>
13294 </para></entry>
13295 </row>
13296
13297 <row>
13298 <entry role="func_table_entry"><para role="func_signature">
13299 <function>trunc</function> ( <type>macaddr8</type> )
13300 <returnvalue>macaddr8</returnvalue>
13301 </para>
13302 <para>
13303 Sets the last 5 bytes of the address to zero. The remaining prefix
13304 can be associated with a particular manufacturer (using data not
13305 included in <productname>PostgreSQL</productname>).
13306 </para>
13307 <para>
13308 <literal>trunc(macaddr8 '12:34:56:78:90:ab:cd:ef')</literal>
13309 <returnvalue>12:34:56:00:00:00:00:00</returnvalue>
13310 </para></entry>
13311 </row>
13312
13313 <row>
13314 <entry role="func_table_entry"><para role="func_signature">
13315 <indexterm>
13316 <primary>macaddr8_set7bit</primary>
13317 </indexterm>
13318 <function>macaddr8_set7bit</function> ( <type>macaddr8</type> )
13319 <returnvalue>macaddr8</returnvalue>
13320 </para>
13321 <para>
13322 Sets the 7th bit of the address to one, creating what is known as
13323 modified EUI-64, for inclusion in an IPv6 address.
13324 </para>
13325 <para>
13326 <literal>macaddr8_set7bit(macaddr8 '00:34:56:ab:cd:ef')</literal>
13327 <returnvalue>02:34:56:ff:fe:ab:cd:ef</returnvalue>
13328 </para></entry>
13329 </row>
13330 </tbody>
13331 </tgroup>
13332 </table>
13333
13334 </sect1>
13335
13336
13337 <sect1 id="functions-textsearch">
13338 <title>Text Search Functions and Operators</title>
13339
13340 <indexterm zone="datatype-textsearch">
13341 <primary>full text search</primary>
13342 <secondary>functions and operators</secondary>
13343 </indexterm>
13344
13345 <indexterm zone="datatype-textsearch">
13346 <primary>text search</primary>
13347 <secondary>functions and operators</secondary>
13348 </indexterm>
13349
13350 <para>
13351 <xref linkend="textsearch-operators-table"/>,
13352 <xref linkend="textsearch-functions-table"/> and
13353 <xref linkend="textsearch-functions-debug-table"/>
13354 summarize the functions and operators that are provided
13355 for full text searching. See <xref linkend="textsearch"/> for a detailed
13356 explanation of <productname>PostgreSQL</productname>'s text search
13357 facility.
13358 </para>
13359
13360 <table id="textsearch-operators-table">
13361 <title>Text Search Operators</title>
13362 <tgroup cols="1">
13363 <thead>
13364 <row>
13365 <entry role="func_table_entry"><para role="func_signature">
13366 Operator
13367 </para>
13368 <para>
13369 Description
13370 </para>
13371 <para>
13372 Example(s)
13373 </para></entry>
13374 </row>
13375 </thead>
13376
13377 <tbody>
13378 <row>
13379 <entry role="func_table_entry"><para role="func_signature">
13380 <type>tsvector</type> <literal>@@</literal> <type>tsquery</type>
13381 <returnvalue>boolean</returnvalue>
13382 </para>
13383 <para role="func_signature">
13384 <type>tsquery</type> <literal>@@</literal> <type>tsvector</type>
13385 <returnvalue>boolean</returnvalue>
13386 </para>
13387 <para>
13388 Does <type>tsvector</type> match <type>tsquery</type>?
13389 (The arguments can be given in either order.)
13390 </para>
13391 <para>
13392 <literal>to_tsvector('fat cats ate rats') @@ to_tsquery('cat &amp; rat')</literal>
13393 <returnvalue>t</returnvalue>
13394 </para></entry>
13395 </row>
13396
13397 <row>
13398 <entry role="func_table_entry"><para role="func_signature">
13399 <type>text</type> <literal>@@</literal> <type>tsquery</type>
13400 <returnvalue>boolean</returnvalue>
13401 </para>
13402 <para>
13403 Does text string, after implicit invocation
13404 of <function>to_tsvector()</function>, match <type>tsquery</type>?
13405 </para>
13406 <para>
13407 <literal>'fat cats ate rats' @@ to_tsquery('cat &amp; rat')</literal>
13408 <returnvalue>t</returnvalue>
13409 </para></entry>
13410 </row>
13411
13412 <row>
13413 <entry role="func_table_entry"><para role="func_signature">
13414 <type>tsvector</type> <literal>||</literal> <type>tsvector</type>
13415 <returnvalue>tsvector</returnvalue>
13416 </para>
13417 <para>
13418 Concatenates two <type>tsvector</type>s. If both inputs contain
13419 lexeme positions, the second input's positions are adjusted
13420 accordingly.
13421 </para>
13422 <para>
13423 <literal>'a:1 b:2'::tsvector || 'c:1 d:2 b:3'::tsvector</literal>
13424 <returnvalue>'a':1 'b':2,5 'c':3 'd':4</returnvalue>
13425 </para></entry>
13426 </row>
13427
13428 <row>
13429 <entry role="func_table_entry"><para role="func_signature">
13430 <type>tsquery</type> <literal>&amp;&amp;</literal> <type>tsquery</type>
13431 <returnvalue>tsquery</returnvalue>
13432 </para>
13433 <para>
13434 ANDs two <type>tsquery</type>s together, producing a query that
13435 matches documents that match both input queries.
13436 </para>
13437 <para>
13438 <literal>'fat | rat'::tsquery &amp;&amp; 'cat'::tsquery</literal>
13439 <returnvalue>( 'fat' | 'rat' ) &amp; 'cat'</returnvalue>
13440 </para></entry>
13441 </row>
13442
13443 <row>
13444 <entry role="func_table_entry"><para role="func_signature">
13445 <type>tsquery</type> <literal>||</literal> <type>tsquery</type>
13446 <returnvalue>tsquery</returnvalue>
13447 </para>
13448 <para>
13449 ORs two <type>tsquery</type>s together, producing a query that
13450 matches documents that match either input query.
13451 </para>
13452 <para>
13453 <literal>'fat | rat'::tsquery || 'cat'::tsquery</literal>
13454 <returnvalue>'fat' | 'rat' | 'cat'</returnvalue>
13455 </para></entry>
13456 </row>
13457
13458 <row>
13459 <entry role="func_table_entry"><para role="func_signature">
13460 <literal>!!</literal> <type>tsquery</type>
13461 <returnvalue>tsquery</returnvalue>
13462 </para>
13463 <para>
13464 Negates a <type>tsquery</type>, producing a query that matches
13465 documents that do not match the input query.
13466 </para>
13467 <para>
13468 <literal>!! 'cat'::tsquery</literal>
13469 <returnvalue>!'cat'</returnvalue>
13470 </para></entry>
13471 </row>
13472
13473 <row>
13474 <entry role="func_table_entry"><para role="func_signature">
13475 <type>tsquery</type> <literal>&lt;-&gt;</literal> <type>tsquery</type>
13476 <returnvalue>tsquery</returnvalue>
13477 </para>
13478 <para>
13479 Constructs a phrase query, which matches if the two input queries
13480 match at successive lexemes.
13481 </para>
13482 <para>
13483 <literal>to_tsquery('fat') &lt;-&gt; to_tsquery('rat')</literal>
13484 <returnvalue>'fat' &lt;-&gt; 'rat'</returnvalue>
13485 </para></entry>
13486 </row>
13487
13488 <row>
13489 <entry role="func_table_entry"><para role="func_signature">
13490 <type>tsquery</type> <literal>@&gt;</literal> <type>tsquery</type>
13491 <returnvalue>boolean</returnvalue>
13492 </para>
13493 <para>
13494 Does first <type>tsquery</type> contain the second? (This considers
13495 only whether all the lexemes appearing in one query appear in the
13496 other, ignoring the combining operators.)
13497 </para>
13498 <para>
13499 <literal>'cat'::tsquery @&gt; 'cat &amp; rat'::tsquery</literal>
13500 <returnvalue>f</returnvalue>
13501 </para></entry>
13502 </row>
13503
13504 <row>
13505 <entry role="func_table_entry"><para role="func_signature">
13506 <type>tsquery</type> <literal>&lt;@</literal> <type>tsquery</type>
13507 <returnvalue>boolean</returnvalue>
13508 </para>
13509 <para>
13510 Is first <type>tsquery</type> contained in the second? (This
13511 considers only whether all the lexemes appearing in one query appear
13512 in the other, ignoring the combining operators.)
13513 </para>
13514 <para>
13515 <literal>'cat'::tsquery &lt;@ 'cat &amp; rat'::tsquery</literal>
13516 <returnvalue>t</returnvalue>
13517 </para>
13518 <para>
13519 <literal>'cat'::tsquery &lt;@ '!cat &amp; rat'::tsquery</literal>
13520 <returnvalue>t</returnvalue>
13521 </para></entry>
13522 </row>
13523 </tbody>
13524 </tgroup>
13525 </table>
13526
13527 <para>
13528 In addition to these specialized operators, the usual comparison
13529 operators shown in <xref linkend="functions-comparison-op-table"/> are
13530 available for types <type>tsvector</type> and <type>tsquery</type>.
13531 These are not very
13532 useful for text searching but allow, for example, unique indexes to be
13533 built on columns of these types.
13534 </para>
13535
13536 <table id="textsearch-functions-table">
13537 <title>Text Search Functions</title>
13538 <tgroup cols="1">
13539 <thead>
13540 <row>
13541 <entry role="func_table_entry"><para role="func_signature">
13542 Function
13543 </para>
13544 <para>
13545 Description
13546 </para>
13547 <para>
13548 Example(s)
13549 </para></entry>
13550 </row>
13551 </thead>
13552
13553 <tbody>
13554 <row>
13555 <entry role="func_table_entry"><para role="func_signature">
13556 <indexterm>
13557 <primary>array_to_tsvector</primary>
13558 </indexterm>
13559 <function>array_to_tsvector</function> ( <type>text[]</type> )
13560 <returnvalue>tsvector</returnvalue>
13561 </para>
13562 <para>
13563 Converts an array of text strings to a <type>tsvector</type>.
13564 The given strings are used as lexemes as-is, without further
13565 processing. Array elements must not be empty strings
13566 or <literal>NULL</literal>.
13567 </para>
13568 <para>
13569 <literal>array_to_tsvector('{fat,cat,rat}'::text[])</literal>
13570 <returnvalue>'cat' 'fat' 'rat'</returnvalue>
13571 </para></entry>
13572 </row>
13573
13574 <row>
13575 <entry role="func_table_entry"><para role="func_signature">
13576 <indexterm>
13577 <primary>get_current_ts_config</primary>
13578 </indexterm>
13579 <function>get_current_ts_config</function> ( )
13580 <returnvalue>regconfig</returnvalue>
13581 </para>
13582 <para>
13583 Returns the OID of the current default text search configuration
13584 (as set by <xref linkend="guc-default-text-search-config"/>).
13585 </para>
13586 <para>
13587 <literal>get_current_ts_config()</literal>
13588 <returnvalue>english</returnvalue>
13589 </para></entry>
13590 </row>
13591
13592 <row>
13593 <entry role="func_table_entry"><para role="func_signature">
13594 <indexterm>
13595 <primary>length</primary>
13596 </indexterm>
13597 <function>length</function> ( <type>tsvector</type> )
13598 <returnvalue>integer</returnvalue>
13599 </para>
13600 <para>
13601 Returns the number of lexemes in the <type>tsvector</type>.
13602 </para>
13603 <para>
13604 <literal>length('fat:2,4 cat:3 rat:5A'::tsvector)</literal>
13605 <returnvalue>3</returnvalue>
13606 </para></entry>
13607 </row>
13608
13609 <row>
13610 <entry role="func_table_entry"><para role="func_signature">
13611 <indexterm>
13612 <primary>numnode</primary>
13613 </indexterm>
13614 <function>numnode</function> ( <type>tsquery</type> )
13615 <returnvalue>integer</returnvalue>
13616 </para>
13617 <para>
13618 Returns the number of lexemes plus operators in
13619 the <type>tsquery</type>.
13620 </para>
13621 <para>
13622 <literal>numnode('(fat &amp; rat) | cat'::tsquery)</literal>
13623 <returnvalue>5</returnvalue>
13624 </para></entry>
13625 </row>
13626
13627 <row>
13628 <entry role="func_table_entry"><para role="func_signature">
13629 <indexterm>
13630 <primary>plainto_tsquery</primary>
13631 </indexterm>
13632 <function>plainto_tsquery</function> (
13633 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13634 <parameter>query</parameter> <type>text</type> )
13635 <returnvalue>tsquery</returnvalue>
13636 </para>
13637 <para>
13638 Converts text to a <type>tsquery</type>, normalizing words according to
13639 the specified or default configuration. Any punctuation in the string
13640 is ignored (it does not determine query operators). The resulting
13641 query matches documents containing all non-stopwords in the text.
13642 </para>
13643 <para>
13644 <literal>plainto_tsquery('english', 'The Fat Rats')</literal>
13645 <returnvalue>'fat' &amp; 'rat'</returnvalue>
13646 </para></entry>
13647 </row>
13648
13649 <row>
13650 <entry role="func_table_entry"><para role="func_signature">
13651 <indexterm>
13652 <primary>phraseto_tsquery</primary>
13653 </indexterm>
13654 <function>phraseto_tsquery</function> (
13655 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13656 <parameter>query</parameter> <type>text</type> )
13657 <returnvalue>tsquery</returnvalue>
13658 </para>
13659 <para>
13660 Converts text to a <type>tsquery</type>, normalizing words according to
13661 the specified or default configuration. Any punctuation in the string
13662 is ignored (it does not determine query operators). The resulting
13663 query matches phrases containing all non-stopwords in the text.
13664 </para>
13665 <para>
13666 <literal>phraseto_tsquery('english', 'The Fat Rats')</literal>
13667 <returnvalue>'fat' &lt;-&gt; 'rat'</returnvalue>
13668 </para>
13669 <para>
13670 <literal>phraseto_tsquery('english', 'The Cat and Rats')</literal>
13671 <returnvalue>'cat' &lt;2&gt; 'rat'</returnvalue>
13672 </para></entry>
13673 </row>
13674
13675 <row>
13676 <entry role="func_table_entry"><para role="func_signature">
13677 <indexterm>
13678 <primary>websearch_to_tsquery</primary>
13679 </indexterm>
13680 <function>websearch_to_tsquery</function> (
13681 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13682 <parameter>query</parameter> <type>text</type> )
13683 <returnvalue>tsquery</returnvalue>
13684 </para>
13685 <para>
13686 Converts text to a <type>tsquery</type>, normalizing words according
13687 to the specified or default configuration. Quoted word sequences are
13688 converted to phrase tests. The word <quote>or</quote> is understood
13689 as producing an OR operator, and a dash produces a NOT operator;
13690 other punctuation is ignored.
13691 This approximates the behavior of some common web search tools.
13692 </para>
13693 <para>
13694 <literal>websearch_to_tsquery('english', '"fat rat" or cat dog')</literal>
13695 <returnvalue>'fat' &lt;-&gt; 'rat' | 'cat' &amp; 'dog'</returnvalue>
13696 </para></entry>
13697 </row>
13698
13699 <row>
13700 <entry role="func_table_entry"><para role="func_signature">
13701 <indexterm>
13702 <primary>querytree</primary>
13703 </indexterm>
13704 <function>querytree</function> ( <type>tsquery</type> )
13705 <returnvalue>text</returnvalue>
13706 </para>
13707 <para>
13708 Produces a representation of the indexable portion of
13709 a <type>tsquery</type>. A result that is empty or
13710 just <literal>T</literal> indicates a non-indexable query.
13711 </para>
13712 <para>
13713 <literal>querytree('foo &amp; ! bar'::tsquery)</literal>
13714 <returnvalue>'foo'</returnvalue>
13715 </para></entry>
13716 </row>
13717
13718 <row>
13719 <entry role="func_table_entry"><para role="func_signature">
13720 <indexterm>
13721 <primary>setweight</primary>
13722 </indexterm>
13723 <function>setweight</function> ( <parameter>vector</parameter> <type>tsvector</type>, <parameter>weight</parameter> <type>"char"</type> )
13724 <returnvalue>tsvector</returnvalue>
13725 </para>
13726 <para>
13727 Assigns the specified <parameter>weight</parameter> to each element
13728 of the <parameter>vector</parameter>.
13729 </para>
13730 <para>
13731 <literal>setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A')</literal>
13732 <returnvalue>'cat':3A 'fat':2A,4A 'rat':5A</returnvalue>
13733 </para></entry>
13734 </row>
13735
13736 <row>
13737 <entry role="func_table_entry"><para role="func_signature">
13738 <indexterm>
13739 <primary>setweight</primary>
13740 <secondary>setweight for specific lexeme(s)</secondary>
13741 </indexterm>
13742 <function>setweight</function> ( <parameter>vector</parameter> <type>tsvector</type>, <parameter>weight</parameter> <type>"char"</type>, <parameter>lexemes</parameter> <type>text[]</type> )
13743 <returnvalue>tsvector</returnvalue>
13744 </para>
13745 <para>
13746 Assigns the specified <parameter>weight</parameter> to elements
13747 of the <parameter>vector</parameter> that are listed
13748 in <parameter>lexemes</parameter>.
13749 The strings in <parameter>lexemes</parameter> are taken as lexemes
13750 as-is, without further processing. Strings that do not match any
13751 lexeme in <parameter>vector</parameter> are ignored.
13752 </para>
13753 <para>
13754 <literal>setweight('fat:2,4 cat:3 rat:5,6B'::tsvector, 'A', '{cat,rat}')</literal>
13755 <returnvalue>'cat':3A 'fat':2,4 'rat':5A,6A</returnvalue>
13756 </para></entry>
13757 </row>
13758
13759 <row>
13760 <entry role="func_table_entry"><para role="func_signature">
13761 <indexterm>
13762 <primary>strip</primary>
13763 </indexterm>
13764 <function>strip</function> ( <type>tsvector</type> )
13765 <returnvalue>tsvector</returnvalue>
13766 </para>
13767 <para>
13768 Removes positions and weights from the <type>tsvector</type>.
13769 </para>
13770 <para>
13771 <literal>strip('fat:2,4 cat:3 rat:5A'::tsvector)</literal>
13772 <returnvalue>'cat' 'fat' 'rat'</returnvalue>
13773 </para></entry>
13774 </row>
13775
13776 <row>
13777 <entry role="func_table_entry"><para role="func_signature">
13778 <indexterm>
13779 <primary>to_tsquery</primary>
13780 </indexterm>
13781 <function>to_tsquery</function> (
13782 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13783 <parameter>query</parameter> <type>text</type> )
13784 <returnvalue>tsquery</returnvalue>
13785 </para>
13786 <para>
13787 Converts text to a <type>tsquery</type>, normalizing words according to
13788 the specified or default configuration. The words must be combined
13789 by valid <type>tsquery</type> operators.
13790 </para>
13791 <para>
13792 <literal>to_tsquery('english', 'The &amp; Fat &amp; Rats')</literal>
13793 <returnvalue>'fat' &amp; 'rat'</returnvalue>
13794 </para></entry>
13795 </row>
13796
13797 <row>
13798 <entry role="func_table_entry"><para role="func_signature">
13799 <indexterm>
13800 <primary>to_tsvector</primary>
13801 </indexterm>
13802 <function>to_tsvector</function> (
13803 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13804 <parameter>document</parameter> <type>text</type> )
13805 <returnvalue>tsvector</returnvalue>
13806 </para>
13807 <para>
13808 Converts text to a <type>tsvector</type>, normalizing words according
13809 to the specified or default configuration. Position information is
13810 included in the result.
13811 </para>
13812 <para>
13813 <literal>to_tsvector('english', 'The Fat Rats')</literal>
13814 <returnvalue>'fat':2 'rat':3</returnvalue>
13815 </para></entry>
13816 </row>
13817
13818 <row>
13819 <entry role="func_table_entry"><para role="func_signature">
13820 <function>to_tsvector</function> (
13821 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13822 <parameter>document</parameter> <type>json</type> )
13823 <returnvalue>tsvector</returnvalue>
13824 </para>
13825 <para role="func_signature">
13826 <function>to_tsvector</function> (
13827 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13828 <parameter>document</parameter> <type>jsonb</type> )
13829 <returnvalue>tsvector</returnvalue>
13830 </para>
13831 <para>
13832 Converts each string value in the JSON document to
13833 a <type>tsvector</type>, normalizing words according to the specified
13834 or default configuration. The results are then concatenated in
13835 document order to produce the output. Position information is
13836 generated as though one stopword exists between each pair of string
13837 values. (Beware that <quote>document order</quote> of the fields of a
13838 JSON object is implementation-dependent when the input
13839 is <type>jsonb</type>; observe the difference in the examples.)
13840 </para>
13841 <para>
13842 <literal>to_tsvector('english', '{"aa": "The Fat Rats", "b": "dog"}'::json)</literal>
13843 <returnvalue>'dog':5 'fat':2 'rat':3</returnvalue>
13844 </para>
13845 <para>
13846 <literal>to_tsvector('english', '{"aa": "The Fat Rats", "b": "dog"}'::jsonb)</literal>
13847 <returnvalue>'dog':1 'fat':4 'rat':5</returnvalue>
13848 </para></entry>
13849 </row>
13850
13851 <row>
13852 <entry role="func_table_entry"><para role="func_signature">
13853 <indexterm>
13854 <primary>json_to_tsvector</primary>
13855 </indexterm>
13856 <function>json_to_tsvector</function> (
13857 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13858 <parameter>document</parameter> <type>json</type>,
13859 <parameter>filter</parameter> <type>jsonb</type> )
13860 <returnvalue>tsvector</returnvalue>
13861 </para>
13862 <para role="func_signature">
13863 <indexterm>
13864 <primary>jsonb_to_tsvector</primary>
13865 </indexterm>
13866 <function>jsonb_to_tsvector</function> (
13867 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13868 <parameter>document</parameter> <type>jsonb</type>,
13869 <parameter>filter</parameter> <type>jsonb</type> )
13870 <returnvalue>tsvector</returnvalue>
13871 </para>
13872 <para>
13873 Selects each item in the JSON document that is requested by
13874 the <parameter>filter</parameter> and converts each one to
13875 a <type>tsvector</type>, normalizing words according to the specified
13876 or default configuration. The results are then concatenated in
13877 document order to produce the output. Position information is
13878 generated as though one stopword exists between each pair of selected
13879 items. (Beware that <quote>document order</quote> of the fields of a
13880 JSON object is implementation-dependent when the input
13881 is <type>jsonb</type>.)
13882 The <parameter>filter</parameter> must be a <type>jsonb</type>
13883 array containing zero or more of these keywords:
13884 <literal>"string"</literal> (to include all string values),
13885 <literal>"numeric"</literal> (to include all numeric values),
13886 <literal>"boolean"</literal> (to include all boolean values),
13887 <literal>"key"</literal> (to include all keys), or
13888 <literal>"all"</literal> (to include all the above).
13889 As a special case, the <parameter>filter</parameter> can also be a
13890 simple JSON value that is one of these keywords.
13891 </para>
13892 <para>
13893 <literal>json_to_tsvector('english', '{"a": "The Fat Rats", "b": 123}'::json, '["string", "numeric"]')</literal>
13894 <returnvalue>'123':5 'fat':2 'rat':3</returnvalue>
13895 </para>
13896 <para>
13897 <literal>json_to_tsvector('english', '{"cat": "The Fat Rats", "dog": 123}'::json, '"all"')</literal>
13898 <returnvalue>'123':9 'cat':1 'dog':7 'fat':4 'rat':5</returnvalue>
13899 </para></entry>
13900 </row>
13901
13902 <row>
13903 <entry role="func_table_entry"><para role="func_signature">
13904 <indexterm>
13905 <primary>ts_delete</primary>
13906 </indexterm>
13907 <function>ts_delete</function> ( <parameter>vector</parameter> <type>tsvector</type>, <parameter>lexeme</parameter> <type>text</type> )
13908 <returnvalue>tsvector</returnvalue>
13909 </para>
13910 <para>
13911 Removes any occurrence of the given <parameter>lexeme</parameter>
13912 from the <parameter>vector</parameter>.
13913 The <parameter>lexeme</parameter> string is treated as a lexeme as-is,
13914 without further processing.
13915 </para>
13916 <para>
13917 <literal>ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, 'fat')</literal>
13918 <returnvalue>'cat':3 'rat':5A</returnvalue>
13919 </para></entry>
13920 </row>
13921
13922 <row>
13923 <entry role="func_table_entry"><para role="func_signature">
13924 <function>ts_delete</function> ( <parameter>vector</parameter> <type>tsvector</type>, <parameter>lexemes</parameter> <type>text[]</type> )
13925 <returnvalue>tsvector</returnvalue>
13926 </para>
13927 <para>
13928 Removes any occurrences of the lexemes
13929 in <parameter>lexemes</parameter>
13930 from the <parameter>vector</parameter>.
13931 The strings in <parameter>lexemes</parameter> are taken as lexemes
13932 as-is, without further processing. Strings that do not match any
13933 lexeme in <parameter>vector</parameter> are ignored.
13934 </para>
13935 <para>
13936 <literal>ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, ARRAY['fat','rat'])</literal>
13937 <returnvalue>'cat':3</returnvalue>
13938 </para></entry>
13939 </row>
13940
13941 <row>
13942 <entry role="func_table_entry"><para role="func_signature">
13943 <indexterm>
13944 <primary>ts_filter</primary>
13945 </indexterm>
13946 <function>ts_filter</function> ( <parameter>vector</parameter> <type>tsvector</type>, <parameter>weights</parameter> <type>"char"[]</type> )
13947 <returnvalue>tsvector</returnvalue>
13948 </para>
13949 <para>
13950 Selects only elements with the given <parameter>weights</parameter>
13951 from the <parameter>vector</parameter>.
13952 </para>
13953 <para>
13954 <literal>ts_filter('fat:2,4 cat:3b,7c rat:5A'::tsvector, '{a,b}')</literal>
13955 <returnvalue>'cat':3B 'rat':5A</returnvalue>
13956 </para></entry>
13957 </row>
13958
13959 <row>
13960 <entry role="func_table_entry"><para role="func_signature">
13961 <indexterm>
13962 <primary>ts_headline</primary>
13963 </indexterm>
13964 <function>ts_headline</function> (
13965 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13966 <parameter>document</parameter> <type>text</type>,
13967 <parameter>query</parameter> <type>tsquery</type>
13968 <optional>, <parameter>options</parameter> <type>text</type> </optional> )
13969 <returnvalue>text</returnvalue>
13970 </para>
13971 <para>
13972 Displays, in an abbreviated form, the match(es) for
13973 the <parameter>query</parameter> in
13974 the <parameter>document</parameter>, which must be raw text not
13975 a <type>tsvector</type>. Words in the document are normalized
13976 according to the specified or default configuration before matching to
13977 the query. Use of this function is discussed in
13978 <xref linkend="textsearch-headline"/>, which also describes the
13979 available <parameter>options</parameter>.
13980 </para>
13981 <para>
13982 <literal>ts_headline('The fat cat ate the rat.', 'cat')</literal>
13983 <returnvalue>The fat &lt;b&gt;cat&lt;/b&gt; ate the rat.</returnvalue>
13984 </para></entry>
13985 </row>
13986
13987 <row>
13988 <entry role="func_table_entry"><para role="func_signature">
13989 <function>ts_headline</function> (
13990 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13991 <parameter>document</parameter> <type>json</type>,
13992 <parameter>query</parameter> <type>tsquery</type>
13993 <optional>, <parameter>options</parameter> <type>text</type> </optional> )
13994 <returnvalue>text</returnvalue>
13995 </para>
13996 <para role="func_signature">
13997 <function>ts_headline</function> (
13998 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
13999 <parameter>document</parameter> <type>jsonb</type>,
14000 <parameter>query</parameter> <type>tsquery</type>
14001 <optional>, <parameter>options</parameter> <type>text</type> </optional> )
14002 <returnvalue>text</returnvalue>
14003 </para>
14004 <para>
14005 Displays, in an abbreviated form, match(es) for
14006 the <parameter>query</parameter> that occur in string values
14007 within the JSON <parameter>document</parameter>.
14008 See <xref linkend="textsearch-headline"/> for more details.
14009 </para>
14010 <para>
14011 <literal>ts_headline('{"cat":"raining cats and dogs"}'::jsonb, 'cat')</literal>
14012 <returnvalue>{"cat": "raining &lt;b&gt;cats&lt;/b&gt; and dogs"}</returnvalue>
14013 </para></entry>
14014 </row>
14015
14016 <row>
14017 <entry role="func_table_entry"><para role="func_signature">
14018 <indexterm>
14019 <primary>ts_rank</primary>
14020 </indexterm>
14021 <function>ts_rank</function> (
14022 <optional> <parameter>weights</parameter> <type>real[]</type>, </optional>
14023 <parameter>vector</parameter> <type>tsvector</type>,
14024 <parameter>query</parameter> <type>tsquery</type>
14025 <optional>, <parameter>normalization</parameter> <type>integer</type> </optional> )
14026 <returnvalue>real</returnvalue>
14027 </para>
14028 <para>
14029 Computes a score showing how well
14030 the <parameter>vector</parameter> matches
14031 the <parameter>query</parameter>. See
14032 <xref linkend="textsearch-ranking"/> for details.
14033 </para>
14034 <para>
14035 <literal>ts_rank(to_tsvector('raining cats and dogs'), 'cat')</literal>
14036 <returnvalue>0.06079271</returnvalue>
14037 </para></entry>
14038 </row>
14039
14040 <row>
14041 <entry role="func_table_entry"><para role="func_signature">
14042 <indexterm>
14043 <primary>ts_rank_cd</primary>
14044 </indexterm>
14045 <function>ts_rank_cd</function> (
14046 <optional> <parameter>weights</parameter> <type>real[]</type>, </optional>
14047 <parameter>vector</parameter> <type>tsvector</type>,
14048 <parameter>query</parameter> <type>tsquery</type>
14049 <optional>, <parameter>normalization</parameter> <type>integer</type> </optional> )
14050 <returnvalue>real</returnvalue>
14051 </para>
14052 <para>
14053 Computes a score showing how well
14054 the <parameter>vector</parameter> matches
14055 the <parameter>query</parameter>, using a cover density
14056 algorithm. See <xref linkend="textsearch-ranking"/> for details.
14057 </para>
14058 <para>
14059 <literal>ts_rank_cd(to_tsvector('raining cats and dogs'), 'cat')</literal>
14060 <returnvalue>0.1</returnvalue>
14061 </para></entry>
14062 </row>
14063
14064 <row>
14065 <entry role="func_table_entry"><para role="func_signature">
14066 <indexterm>
14067 <primary>ts_rewrite</primary>
14068 </indexterm>
14069 <function>ts_rewrite</function> ( <parameter>query</parameter> <type>tsquery</type>,
14070 <parameter>target</parameter> <type>tsquery</type>,
14071 <parameter>substitute</parameter> <type>tsquery</type> )
14072 <returnvalue>tsquery</returnvalue>
14073 </para>
14074 <para>
14075 Replaces occurrences of <parameter>target</parameter>
14076 with <parameter>substitute</parameter>
14077 within the <parameter>query</parameter>.
14078 See <xref linkend="textsearch-query-rewriting"/> for details.
14079 </para>
14080 <para>
14081 <literal>ts_rewrite('a &amp; b'::tsquery, 'a'::tsquery, 'foo|bar'::tsquery)</literal>
14082 <returnvalue>'b' &amp; ( 'foo' | 'bar' )</returnvalue>
14083 </para></entry>
14084 </row>
14085
14086 <row>
14087 <entry role="func_table_entry"><para role="func_signature">
14088 <function>ts_rewrite</function> ( <parameter>query</parameter> <type>tsquery</type>,
14089 <parameter>select</parameter> <type>text</type> )
14090 <returnvalue>tsquery</returnvalue>
14091 </para>
14092 <para>
14093 Replaces portions of the <parameter>query</parameter> according to
14094 target(s) and substitute(s) obtained by executing
14095 a <command>SELECT</command> command.
14096 See <xref linkend="textsearch-query-rewriting"/> for details.
14097 </para>
14098 <para>
14099 <literal>SELECT ts_rewrite('a &amp; b'::tsquery, 'SELECT t,s FROM aliases')</literal>
14100 <returnvalue>'b' &amp; ( 'foo' | 'bar' )</returnvalue>
14101 </para></entry>
14102 </row>
14103
14104 <row>
14105 <entry role="func_table_entry"><para role="func_signature">
14106 <indexterm>
14107 <primary>tsquery_phrase</primary>
14108 </indexterm>
14109 <function>tsquery_phrase</function> ( <parameter>query1</parameter> <type>tsquery</type>, <parameter>query2</parameter> <type>tsquery</type> )
14110 <returnvalue>tsquery</returnvalue>
14111 </para>
14112 <para>
14113 Constructs a phrase query that searches
14114 for matches of <parameter>query1</parameter>
14115 and <parameter>query2</parameter> at successive lexemes (same
14116 as <literal>&lt;-&gt;</literal> operator).
14117 </para>
14118 <para>
14119 <literal>tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'))</literal>
14120 <returnvalue>'fat' &lt;-&gt; 'cat'</returnvalue>
14121 </para></entry>
14122 </row>
14123
14124 <row>
14125 <entry role="func_table_entry"><para role="func_signature">
14126 <function>tsquery_phrase</function> ( <parameter>query1</parameter> <type>tsquery</type>, <parameter>query2</parameter> <type>tsquery</type>, <parameter>distance</parameter> <type>integer</type> )
14127 <returnvalue>tsquery</returnvalue>
14128 </para>
14129 <para>
14130 Constructs a phrase query that searches
14131 for matches of <parameter>query1</parameter> and
14132 <parameter>query2</parameter> that occur exactly
14133 <parameter>distance</parameter> lexemes apart.
14134 </para>
14135 <para>
14136 <literal>tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'), 10)</literal>
14137 <returnvalue>'fat' &lt;10&gt; 'cat'</returnvalue>
14138 </para></entry>
14139 </row>
14140
14141 <row>
14142 <entry role="func_table_entry"><para role="func_signature">
14143 <indexterm>
14144 <primary>tsvector_to_array</primary>
14145 </indexterm>
14146 <function>tsvector_to_array</function> ( <type>tsvector</type> )
14147 <returnvalue>text[]</returnvalue>
14148 </para>
14149 <para>
14150 Converts a <type>tsvector</type> to an array of lexemes.
14151 </para>
14152 <para>
14153 <literal>tsvector_to_array('fat:2,4 cat:3 rat:5A'::tsvector)</literal>
14154 <returnvalue>{cat,fat,rat}</returnvalue>
14155 </para></entry>
14156 </row>
14157
14158 <row>
14159 <entry role="func_table_entry"><para role="func_signature">
14160 <indexterm>
14161 <primary>unnest</primary>
14162 <secondary>for tsvector</secondary>
14163 </indexterm>
14164 <function>unnest</function> ( <type>tsvector</type> )
14165 <returnvalue>setof record</returnvalue>
14166 ( <parameter>lexeme</parameter> <type>text</type>,
14167 <parameter>positions</parameter> <type>smallint[]</type>,
14168 <parameter>weights</parameter> <type>text</type> )
14169 </para>
14170 <para>
14171 Expands a <type>tsvector</type> into a set of rows, one per lexeme.
14172 </para>
14173 <para>
14174 <literal>select * from unnest('cat:3 fat:2,4 rat:5A'::tsvector)</literal>
14175 <returnvalue></returnvalue>
14176 <programlisting>
14177 lexeme | positions | weights
14178 --------+-----------+---------
14179 cat | {3} | {D}
14180 fat | {2,4} | {D,D}
14181 rat | {5} | {A}
14182 </programlisting>
14183 </para></entry>
14184 </row>
14185 </tbody>
14186 </tgroup>
14187 </table>
14188
14189 <note>
14190 <para>
14191 All the text search functions that accept an optional <type>regconfig</type>
14192 argument will use the configuration specified by
14193 <xref linkend="guc-default-text-search-config"/>
14194 when that argument is omitted.
14195 </para>
14196 </note>
14197
14198 <para>
14199 The functions in
14200 <xref linkend="textsearch-functions-debug-table"/>
14201 are listed separately because they are not usually used in everyday text
14202 searching operations. They are primarily helpful for development and
14203 debugging of new text search configurations.
14204 </para>
14205
14206 <table id="textsearch-functions-debug-table">
14207 <title>Text Search Debugging Functions</title>
14208 <tgroup cols="1">
14209 <thead>
14210 <row>
14211 <entry role="func_table_entry"><para role="func_signature">
14212 Function
14213 </para>
14214 <para>
14215 Description
14216 </para>
14217 <para>
14218 Example(s)
14219 </para></entry>
14220 </row>
14221 </thead>
14222
14223 <tbody>
14224 <row>
14225 <entry role="func_table_entry"><para role="func_signature">
14226 <indexterm>
14227 <primary>ts_debug</primary>
14228 </indexterm>
14229 <function>ts_debug</function> (
14230 <optional> <parameter>config</parameter> <type>regconfig</type>, </optional>
14231 <parameter>document</parameter> <type>text</type> )
14232 <returnvalue>setof record</returnvalue>
14233 ( <parameter>alias</parameter> <type>text</type>,
14234 <parameter>description</parameter> <type>text</type>,
14235 <parameter>token</parameter> <type>text</type>,
14236 <parameter>dictionaries</parameter> <type>regdictionary[]</type>,
14237 <parameter>dictionary</parameter> <type>regdictionary</type>,
14238 <parameter>lexemes</parameter> <type>text[]</type> )
14239 </para>
14240 <para>
14241 Extracts and normalizes tokens from
14242 the <parameter>document</parameter> according to the specified or
14243 default text search configuration, and returns information about how
14244 each token was processed.
14245 See <xref linkend="textsearch-configuration-testing"/> for details.
14246 </para>
14247 <para>
14248 <literal>ts_debug('english', 'The Brightest supernovaes')</literal>
14249 <returnvalue>(asciiword,"Word, all ASCII",The,{english_stem},english_stem,{}) ...</returnvalue>
14250 </para></entry>
14251 </row>
14252
14253 <row>
14254 <entry role="func_table_entry"><para role="func_signature">
14255 <indexterm>
14256 <primary>ts_lexize</primary>
14257 </indexterm>
14258 <function>ts_lexize</function> ( <parameter>dict</parameter> <type>regdictionary</type>, <parameter>token</parameter> <type>text</type> )
14259 <returnvalue>text[]</returnvalue>
14260 </para>
14261 <para>
14262 Returns an array of replacement lexemes if the input token is known to
14263 the dictionary, or an empty array if the token is known to the
14264 dictionary but it is a stop word, or NULL if it is not a known word.
14265 See <xref linkend="textsearch-dictionary-testing"/> for details.
14266 </para>
14267 <para>
14268 <literal>ts_lexize('english_stem', 'stars')</literal>
14269 <returnvalue>{star}</returnvalue>
14270 </para></entry>
14271 </row>
14272
14273 <row>
14274 <entry role="func_table_entry"><para role="func_signature">
14275 <indexterm>
14276 <primary>ts_parse</primary>
14277 </indexterm>
14278 <function>ts_parse</function> ( <parameter>parser_name</parameter> <type>text</type>,
14279 <parameter>document</parameter> <type>text</type> )
14280 <returnvalue>setof record</returnvalue>
14281 ( <parameter>tokid</parameter> <type>integer</type>,
14282 <parameter>token</parameter> <type>text</type> )
14283 </para>
14284 <para>
14285 Extracts tokens from the <parameter>document</parameter> using the
14286 named parser.
14287 See <xref linkend="textsearch-parser-testing"/> for details.
14288 </para>
14289 <para>
14290 <literal>ts_parse('default', 'foo - bar')</literal>
14291 <returnvalue>(1,foo) ...</returnvalue>
14292 </para></entry>
14293 </row>
14294
14295 <row>
14296 <entry role="func_table_entry"><para role="func_signature">
14297 <function>ts_parse</function> ( <parameter>parser_oid</parameter> <type>oid</type>,
14298 <parameter>document</parameter> <type>text</type> )
14299 <returnvalue>setof record</returnvalue>
14300 ( <parameter>tokid</parameter> <type>integer</type>,
14301 <parameter>token</parameter> <type>text</type> )
14302 </para>
14303 <para>
14304 Extracts tokens from the <parameter>document</parameter> using a
14305 parser specified by OID.
14306 See <xref linkend="textsearch-parser-testing"/> for details.
14307 </para>
14308 <para>
14309 <literal>ts_parse(3722, 'foo - bar')</literal>
14310 <returnvalue>(1,foo) ...</returnvalue>
14311 </para></entry>
14312 </row>
14313
14314 <row>
14315 <entry role="func_table_entry"><para role="func_signature">
14316 <indexterm>
14317 <primary>ts_token_type</primary>
14318 </indexterm>
14319 <function>ts_token_type</function> ( <parameter>parser_name</parameter> <type>text</type> )
14320 <returnvalue>setof record</returnvalue>
14321 ( <parameter>tokid</parameter> <type>integer</type>,
14322 <parameter>alias</parameter> <type>text</type>,
14323 <parameter>description</parameter> <type>text</type> )
14324 </para>
14325 <para>
14326 Returns a table that describes each type of token the named parser can
14327 recognize.
14328 See <xref linkend="textsearch-parser-testing"/> for details.
14329 </para>
14330 <para>
14331 <literal>ts_token_type('default')</literal>
14332 <returnvalue>(1,asciiword,"Word, all ASCII") ...</returnvalue>
14333 </para></entry>
14334 </row>
14335
14336 <row>
14337 <entry role="func_table_entry"><para role="func_signature">
14338 <function>ts_token_type</function> ( <parameter>parser_oid</parameter> <type>oid</type> )
14339 <returnvalue>setof record</returnvalue>
14340 ( <parameter>tokid</parameter> <type>integer</type>,
14341 <parameter>alias</parameter> <type>text</type>,
14342 <parameter>description</parameter> <type>text</type> )
14343 </para>
14344 <para>
14345 Returns a table that describes each type of token a parser specified
14346 by OID can recognize.
14347 See <xref linkend="textsearch-parser-testing"/> for details.
14348 </para>
14349 <para>
14350 <literal>ts_token_type(3722)</literal>
14351 <returnvalue>(1,asciiword,"Word, all ASCII") ...</returnvalue>
14352 </para></entry>
14353 </row>
14354
14355 <row>
14356 <entry role="func_table_entry"><para role="func_signature">
14357 <indexterm>
14358 <primary>ts_stat</primary>
14359 </indexterm>
14360 <function>ts_stat</function> ( <parameter>sqlquery</parameter> <type>text</type>
14361 <optional>, <parameter>weights</parameter> <type>text</type> </optional> )
14362 <returnvalue>setof record</returnvalue>
14363 ( <parameter>word</parameter> <type>text</type>,
14364 <parameter>ndoc</parameter> <type>integer</type>,
14365 <parameter>nentry</parameter> <type>integer</type> )
14366 </para>
14367 <para>
14368 Executes the <parameter>sqlquery</parameter>, which must return a
14369 single <type>tsvector</type> column, and returns statistics about each
14370 distinct lexeme contained in the data.
14371 See <xref linkend="textsearch-statistics"/> for details.
14372 </para>
14373 <para>
14374 <literal>ts_stat('SELECT vector FROM apod')</literal>
14375 <returnvalue>(foo,10,15) ...</returnvalue>
14376 </para></entry>
14377 </row>
14378 </tbody>
14379 </tgroup>
14380 </table>
14381
14382 </sect1>
14383
14384 <sect1 id="functions-uuid">
14385 <title>UUID Functions</title>
14386
14387 <indexterm zone="functions-uuid">
14388 <primary>UUID</primary>
14389 <secondary>generating</secondary>
14390 </indexterm>
14391
14392 <indexterm>
14393 <primary>gen_random_uuid</primary>
14394 </indexterm>
14395
14396 <indexterm>
14397 <primary>uuidv4</primary>
14398 </indexterm>
14399
14400 <indexterm>
14401 <primary>uuidv7</primary>
14402 </indexterm>
14403
14404 <indexterm>
14405 <primary>uuid_extract_timestamp</primary>
14406 </indexterm>
14407
14408 <indexterm>
14409 <primary>uuid_extract_version</primary>
14410 </indexterm>
14411
14412 <para>
14413 <xref linkend="func_uuid_gen_table"/> shows the <productname>PostgreSQL</productname>
14414 functions that can be used to generate UUIDs.
14415 </para>
14416
14417 <table id="func_uuid_gen_table">
14418 <title><acronym>UUID</acronym> Generation Functions</title>
14419 <tgroup cols="1">
14420 <thead>
14421 <row>
14422 <entry role="func_table_entry"><para role="func_signature">
14423 Function
14424 </para>
14425 <para>
14426 Description
14427 </para>
14428 <para>
14429 Example(s)
14430 </para></entry>
14431 </row>
14432 </thead>
14433
14434 <tbody>
14435 <row>
14436 <entry role="func_table_entry"><para role="func_signature">
14437 <function>gen_random_uuid</function> ( )
14438 <returnvalue>uuid</returnvalue>
14439 </para>
14440 <para role="func_signature">
14441 <function>uuidv4</function> ( )
14442 <returnvalue>uuid</returnvalue>
14443 </para>
14444 <para>
14445 Generates a version 4 (random) UUID
14446 </para>
14447 <para>
14448 <literal>gen_random_uuid()</literal>
14449 <returnvalue>5b30857f-0bfa-48b5-ac0b-5c64e28078d1</returnvalue>
14450 </para>
14451 <para>
14452 <literal>uuidv4()</literal>
14453 <returnvalue>b42410ee-132f-42ee-9e4f-09a6485c95b8</returnvalue>
14454 </para></entry>
14455 </row>
14456 <row>
14457 <entry role="func_table_entry"><para role="func_signature">
14458 <function>uuidv7</function>
14459 ( <optional> <parameter>shift</parameter> <type>interval</type> </optional> )
14460 <returnvalue>uuid</returnvalue>
14461 </para>
14462 <para>
14463 Generates a version 7 (time-ordered) UUID. The timestamp is
14464 computed using UNIX timestamp with millisecond precision +
14465 sub-millisecond timestamp + random. The optional
14466 parameter <parameter>shift</parameter> will shift the computed
14467 timestamp by the given <type>interval</type>.
14468 Infinite interval values are not accepted.
14469 The shifted timestamp must fall within the range supported by
14470 UUID version 7's 48-bit millisecond timestamp field: from
14471 1970-01-01 00:00:00 UTC to approximately year 10889.
14472 An error is raised if the resulting timestamp is outside this
14473 range.
14474 </para>
14475 <para>
14476 <literal>uuidv7()</literal>
14477 <returnvalue>019535d9-3df7-79fb-b466-fa907fa17f9e</returnvalue>
14478 </para></entry>
14479 </row>
14480 </tbody>
14481 </tgroup>
14482 </table>
14483
14484 <note>
14485 <para>
14486 The <xref linkend="uuid-ossp"/> module provides additional functions that
14487 implement other standard algorithms for generating UUIDs.
14488 </para>
14489 </note>
14490
14491 <para>
14492 <xref linkend="func_uuid_extract_table"/> shows the <productname>PostgreSQL</productname>
14493 functions that can be used to extract information from UUIDs.
14494 </para>
14495
14496 <table id="func_uuid_extract_table">
14497 <title><acronym>UUID</acronym> Extraction Functions</title>
14498 <tgroup cols="1">
14499 <thead>
14500 <row>
14501 <entry role="func_table_entry"><para role="func_signature">
14502 Function
14503 </para>
14504 <para>
14505 Description
14506 </para>
14507 <para>
14508 Example(s)
14509 </para></entry>
14510 </row>
14511 </thead>
14512
14513 <tbody>
14514 <row>
14515 <entry role="func_table_entry"><para role="func_signature">
14516 <function>uuid_extract_timestamp</function>
14517 ( <type>uuid</type> )
14518 <returnvalue>timestamp with time zone</returnvalue>
14519 </para>
14520 <para>
14521 Extracts a <type>timestamp with time zone</type> from a UUID of
14522 version 1 or 7. For other versions, this function returns null.
14523 Note that the extracted timestamp is not necessarily exactly equal
14524 to the time the UUID was generated; this depends on the
14525 implementation that generated the UUID.
14526 </para>
14527 <para>
14528 <literal>uuid_extract_timestamp('019535d9-3df7-79fb-b466-&zwsp;fa907fa17f9e'::uuid)</literal>
14529 <returnvalue>2025-02-23 21:46:24.503-05</returnvalue>
14530 </para></entry>
14531 </row>
14532 <row>
14533 <entry role="func_table_entry"><para role="func_signature">
14534 <function>uuid_extract_version</function>
14535 ( <type>uuid</type> )
14536 <returnvalue>smallint</returnvalue>
14537 </para>
14538 <para>
14539 Extracts the version from a UUID of one of the variants described by
14540 <ulink url="https://datatracker.ietf.org/doc/html/rfc9562">RFC
14541 9562</ulink>. For other variants, this function returns null.
14542 For example, for a UUID generated
14543 by <function>gen_random_uuid()</function>, this function will
14544 return 4.
14545 </para>
14546 <para>
14547 <literal>uuid_extract_version('41db1265-8bc1-4ab3-992f-&zwsp;885799a4af1d'::uuid)</literal>
14548 <returnvalue>4</returnvalue>
14549 </para>
14550 <para>
14551 <literal>uuid_extract_version('019535d9-3df7-79fb-b466-&zwsp;fa907fa17f9e'::uuid)</literal>
14552 <returnvalue>7</returnvalue>
14553 </para></entry>
14554 </row>
14555 </tbody>
14556 </tgroup>
14557 </table>
14558
14559 <para>
14560 <productname>PostgreSQL</productname> also provides the usual comparison
14561 operators shown in <xref linkend="functions-comparison-op-table"/> for
14562 UUIDs.
14563 </para>
14564 <para>
14565 See <xref linkend="datatype-uuid"/> for details on the data type
14566 <type>uuid</type> in <productname>PostgreSQL</productname>.
14567 </para>
14568 </sect1>
14569
14570 <sect1 id="functions-xml">
14571
14572 <title>XML Functions</title>
14573
14574 <indexterm>
14575 <primary>XML Functions</primary>
14576 </indexterm>
14577
14578 <para>
14579 The functions and function-like expressions described in this
14580 section operate on values of type <type>xml</type>. See <xref
14581 linkend="datatype-xml"/> for information about the <type>xml</type>
14582 type. The function-like expressions <function>xmlparse</function>
14583 and <function>xmlserialize</function> for converting to and from
14584 type <type>xml</type> are documented there, not in this section.
14585 </para>
14586
14587 <para>
14588 Use of most of these functions
14589 requires <productname>PostgreSQL</productname> to have been built
14590 with <command>configure --with-libxml</command>.
14591 </para>
14592
14593 <sect2 id="functions-producing-xml">
14594 <title>Producing XML Content</title>
14595
14596 <para>
14597 A set of functions and function-like expressions is available for
14598 producing XML content from SQL data. As such, they are
14599 particularly suitable for formatting query results into XML
14600 documents for processing in client applications.
14601 </para>
14602
14603 <sect3 id="functions-producing-xml-xmltext">
14604 <title><literal>xmltext</literal></title>
14605
14606 <indexterm>
14607 <primary>xmltext</primary>
14608 </indexterm>
14609
14610 <synopsis>
14611 <function>xmltext</function> ( <type>text</type> ) <returnvalue>xml</returnvalue>
14612 </synopsis>
14613
14614 <para>
14615 The function <function>xmltext</function> returns an XML value with a single
14616 text node containing the input argument as its content. Predefined entities
14617 like ampersand (<literal><![CDATA[&]]></literal>), left and right angle brackets
14618 (<literal><![CDATA[< >]]></literal>), and quotation marks (<literal><![CDATA[""]]></literal>)
14619 are escaped.
14620 </para>
14621
14622 <para>
14623 Example:
14624 <screen><![CDATA[
14625 SELECT xmltext('< foo & bar >');
14626 xmltext
14627 -------------------------
14628 &lt; foo &amp; bar &gt;
14629 ]]></screen>
14630 </para>
14631 </sect3>
14632
14633 <sect3 id="functions-producing-xml-xmlcomment">
14634 <title><literal>xmlcomment</literal></title>
14635
14636 <indexterm>
14637 <primary>xmlcomment</primary>
14638 </indexterm>
14639
14640 <synopsis>
14641 <function>xmlcomment</function> ( <type>text</type> ) <returnvalue>xml</returnvalue>
14642 </synopsis>
14643
14644 <para>
14645 The function <function>xmlcomment</function> creates an XML value
14646 containing an XML comment with the specified text as content.
14647 The text cannot contain <quote><literal>--</literal></quote> or end with a
14648 <quote><literal>-</literal></quote>, otherwise the resulting construct
14649 would not be a valid XML comment.
14650 If the argument is null, the result is null.
14651 </para>
14652
14653 <para>
14654 Example:
14655 <screen><![CDATA[
14656 SELECT xmlcomment('hello');
14657
14658 xmlcomment
14659 --------------
14660 <!--hello-->
14661 ]]></screen>
14662 </para>
14663 </sect3>
14664
14665 <sect3 id="functions-producing-xml-xmlconcat">
14666 <title><literal>xmlconcat</literal></title>
14667
14668 <indexterm>
14669 <primary>xmlconcat</primary>
14670 </indexterm>
14671
14672 <synopsis>
14673 <function>xmlconcat</function> ( <type>xml</type> <optional>, ...</optional> ) <returnvalue>xml</returnvalue>
14674 </synopsis>
14675
14676 <para>
14677 The function <function>xmlconcat</function> concatenates a list
14678 of individual XML values to create a single value containing an
14679 XML content fragment. Null values are omitted; the result is
14680 only null if there are no nonnull arguments.
14681 </para>
14682
14683 <para>
14684 Example:
14685 <screen><![CDATA[
14686 SELECT xmlconcat('<abc/>', '<bar>foo</bar>');
14687
14688 xmlconcat
14689 ----------------------
14690 <abc/><bar>foo</bar>
14691 ]]></screen>
14692 </para>
14693
14694 <para>
14695 XML declarations, if present, are combined as follows. If all
14696 argument values have the same XML version declaration, that
14697 version is used in the result, else no version is used. If all
14698 argument values have the standalone declaration value
14699 <quote>yes</quote>, then that value is used in the result. If
14700 all argument values have a standalone declaration value and at
14701 least one is <quote>no</quote>, then that is used in the result.
14702 Else the result will have no standalone declaration. If the
14703 result is determined to require a standalone declaration but no
14704 version declaration, a version declaration with version 1.0 will
14705 be used because XML requires an XML declaration to contain a
14706 version declaration. Encoding declarations are ignored and
14707 removed in all cases.
14708 </para>
14709
14710 <para>
14711 Example:
14712 <screen><![CDATA[
14713 SELECT xmlconcat('<?xml version="1.1"?><foo/>', '<?xml version="1.1" standalone="no"?><bar/>');
14714
14715 xmlconcat
14716 -----------------------------------
14717 <?xml version="1.1"?><foo/><bar/>
14718 ]]></screen>
14719 </para>
14720 </sect3>
14721
14722 <sect3 id="functions-producing-xml-xmlelement">
14723 <title><literal>xmlelement</literal></title>
14724
14725 <indexterm>
14726 <primary>xmlelement</primary>
14727 </indexterm>
14728
14729 <synopsis>
14730 <function>xmlelement</function> ( <literal>NAME</literal> <replaceable>name</replaceable> <optional>, <literal>XMLATTRIBUTES</literal> ( <replaceable>attvalue</replaceable> <optional> <literal>AS</literal> <replaceable>attname</replaceable> </optional> <optional>, ...</optional> ) </optional> <optional>, <replaceable>content</replaceable> <optional>, ...</optional></optional> ) <returnvalue>xml</returnvalue>
14731 </synopsis>
14732
14733 <para>
14734 The <function>xmlelement</function> expression produces an XML
14735 element with the given name, attributes, and content.
14736 The <replaceable>name</replaceable>
14737 and <replaceable>attname</replaceable> items shown in the syntax are
14738 simple identifiers, not values. The <replaceable>attvalue</replaceable>
14739 and <replaceable>content</replaceable> items are expressions, which can
14740 yield any <productname>PostgreSQL</productname> data type. The
14741 argument(s) within <literal>XMLATTRIBUTES</literal> generate attributes
14742 of the XML element; the <replaceable>content</replaceable> value(s) are
14743 concatenated to form its content.
14744 </para>
14745
14746 <para>
14747 Examples:
14748 <screen><![CDATA[
14749 SELECT xmlelement(name foo);
14750
14751 xmlelement
14752 ------------
14753 <foo/>
14754
14755 SELECT xmlelement(name foo, xmlattributes('xyz' as bar));
14756
14757 xmlelement
14758 ------------------
14759 <foo bar="xyz"/>
14760
14761 SELECT xmlelement(name foo, xmlattributes(current_date as bar), 'cont', 'ent');
14762
14763 xmlelement
14764 -------------------------------------
14765 <foo bar="2007-01-26">content</foo>
14766 ]]></screen>
14767 </para>
14768
14769 <para>
14770 Element and attribute names that are not valid XML names are
14771 escaped by replacing the offending characters by the sequence
14772 <literal>_x<replaceable>HHHH</replaceable>_</literal>, where
14773 <replaceable>HHHH</replaceable> is the character's Unicode
14774 codepoint in hexadecimal notation. For example:
14775 <screen><![CDATA[
14776 SELECT xmlelement(name "foo$bar", xmlattributes('xyz' as "a&b"));
14777
14778 xmlelement
14779 ----------------------------------
14780 <foo_x0024_bar a_x0026_b="xyz"/>
14781 ]]></screen>
14782 </para>
14783
14784 <para>
14785 An explicit attribute name need not be specified if the attribute
14786 value is a column reference, in which case the column's name will
14787 be used as the attribute name by default. In other cases, the
14788 attribute must be given an explicit name. So this example is
14789 valid:
14790 <screen>
14791 CREATE TABLE test (a xml, b xml);
14792 SELECT xmlelement(name test, xmlattributes(a, b)) FROM test;
14793 </screen>
14794 But these are not:
14795 <screen>
14796 SELECT xmlelement(name test, xmlattributes('constant'), a, b) FROM test;
14797 SELECT xmlelement(name test, xmlattributes(func(a, b))) FROM test;
14798 </screen>
14799 </para>
14800
14801 <para>
14802 Element content, if specified, will be formatted according to
14803 its data type. If the content is itself of type <type>xml</type>,
14804 complex XML documents can be constructed. For example:
14805 <screen><![CDATA[
14806 SELECT xmlelement(name foo, xmlattributes('xyz' as bar),
14807 xmlelement(name abc),
14808 xmlcomment('test'),
14809 xmlelement(name xyz));
14810
14811 xmlelement
14812 ----------------------------------------------
14813 <foo bar="xyz"><abc/><!--test--><xyz/></foo>
14814 ]]></screen>
14815
14816 Content of other types will be formatted into valid XML character
14817 data. This means in particular that the characters &lt;, &gt;,
14818 and &amp; will be converted to entities. Binary data (data type
14819 <type>bytea</type>) will be represented in base64 or hex
14820 encoding, depending on the setting of the configuration parameter
14821 <xref linkend="guc-xmlbinary"/>. The particular behavior for
14822 individual data types is expected to evolve in order to align the
14823 PostgreSQL mappings with those specified in SQL:2006 and later,
14824 as discussed in <xref linkend="functions-xml-limits-casts"/>.
14825 </para>
14826 </sect3>
14827
14828 <sect3 id="functions-producing-xml-xmlforest">
14829 <title><literal>xmlforest</literal></title>
14830
14831 <indexterm>
14832 <primary>xmlforest</primary>
14833 </indexterm>
14834
14835 <synopsis>
14836 <function>xmlforest</function> ( <replaceable>content</replaceable> <optional> <literal>AS</literal> <replaceable>name</replaceable> </optional> <optional>, ...</optional> ) <returnvalue>xml</returnvalue>
14837 </synopsis>
14838
14839 <para>
14840 The <function>xmlforest</function> expression produces an XML
14841 forest (sequence) of elements using the given names and content.
14842 As for <function>xmlelement</function>,
14843 each <replaceable>name</replaceable> must be a simple identifier, while
14844 the <replaceable>content</replaceable> expressions can have any data
14845 type.
14846 </para>
14847
14848 <para>
14849 Examples:
14850 <screen>
14851 SELECT xmlforest('abc' AS foo, 123 AS bar);
14852
14853 xmlforest
14854 ------------------------------
14855 &lt;foo&gt;abc&lt;/foo&gt;&lt;bar&gt;123&lt;/bar&gt;
14856
14857
14858 SELECT xmlforest(table_name, column_name)
14859 FROM information_schema.columns
14860 WHERE table_schema = 'pg_catalog';
14861
14862 xmlforest
14863 ------------------------------------&zwsp;-----------------------------------
14864 &lt;table_name&gt;pg_authid&lt;/table_name&gt;&zwsp;&lt;column_name&gt;rolname&lt;/column_name&gt;
14865 &lt;table_name&gt;pg_authid&lt;/table_name&gt;&zwsp;&lt;column_name&gt;rolsuper&lt;/column_name&gt;
14866 ...
14867 </screen>
14868
14869 As seen in the second example, the element name can be omitted if
14870 the content value is a column reference, in which case the column
14871 name is used by default. Otherwise, a name must be specified.
14872 </para>
14873
14874 <para>
14875 Element names that are not valid XML names are escaped as shown
14876 for <function>xmlelement</function> above. Similarly, content
14877 data is escaped to make valid XML content, unless it is already
14878 of type <type>xml</type>.
14879 </para>
14880
14881 <para>
14882 Note that XML forests are not valid XML documents if they consist
14883 of more than one element, so it might be useful to wrap
14884 <function>xmlforest</function> expressions in
14885 <function>xmlelement</function>.
14886 </para>
14887 </sect3>
14888
14889 <sect3 id="functions-producing-xml-xmlpi">
14890 <title><literal>xmlpi</literal></title>
14891
14892 <indexterm>
14893 <primary>xmlpi</primary>
14894 </indexterm>
14895
14896 <synopsis>
14897 <function>xmlpi</function> ( <literal>NAME</literal> <replaceable>name</replaceable> <optional>, <replaceable>content</replaceable> </optional> ) <returnvalue>xml</returnvalue>
14898 </synopsis>
14899
14900 <para>
14901 The <function>xmlpi</function> expression creates an XML
14902 processing instruction.
14903 As for <function>xmlelement</function>,
14904 the <replaceable>name</replaceable> must be a simple identifier, while
14905 the <replaceable>content</replaceable> expression can have any data type.
14906 The <replaceable>content</replaceable>, if present, must not contain the
14907 character sequence <literal>?&gt;</literal>.
14908 </para>
14909
14910 <para>
14911 Example:
14912 <screen><![CDATA[
14913 SELECT xmlpi(name php, 'echo "hello world";');
14914
14915 xmlpi
14916 -----------------------------
14917 <?php echo "hello world";?>
14918 ]]></screen>
14919 </para>
14920 </sect3>
14921
14922 <sect3 id="functions-producing-xml-xmlroot">
14923 <title><literal>xmlroot</literal></title>
14924
14925 <indexterm>
14926 <primary>xmlroot</primary>
14927 </indexterm>
14928
14929 <synopsis>
14930 <function>xmlroot</function> ( <type>xml</type>, <literal>VERSION</literal> {<type>text</type>|<literal>NO VALUE</literal>} <optional>, <literal>STANDALONE</literal> {<literal>YES</literal>|<literal>NO</literal>|<literal>NO VALUE</literal>} </optional> ) <returnvalue>xml</returnvalue>
14931 </synopsis>
14932
14933 <para>
14934 The <function>xmlroot</function> expression alters the properties
14935 of the root node of an XML value. If a version is specified,
14936 it replaces the value in the root node's version declaration; if a
14937 standalone setting is specified, it replaces the value in the
14938 root node's standalone declaration.
14939 </para>
14940
14941 <para>
14942 <screen><![CDATA[
14943 SELECT xmlroot(xmlparse(document '<?xml version="1.1"?><content>abc</content>'),
14944 version '1.0', standalone yes);
14945
14946 xmlroot
14947 ----------------------------------------
14948 <?xml version="1.0" standalone="yes"?>
14949 <content>abc</content>
14950 ]]></screen>
14951 </para>
14952 </sect3>
14953
14954 <sect3 id="functions-xml-xmlagg">
14955 <title><literal>xmlagg</literal></title>
14956
14957 <indexterm>
14958 <primary>xmlagg</primary>
14959 </indexterm>
14960
14961 <synopsis>
14962 <function>xmlagg</function> ( <type>xml</type> ) <returnvalue>xml</returnvalue>
14963 </synopsis>
14964
14965 <para>
14966 The function <function>xmlagg</function> is, unlike the other
14967 functions described here, an aggregate function. It concatenates the
14968 input values to the aggregate function call,
14969 much like <function>xmlconcat</function> does, except that concatenation
14970 occurs across rows rather than across expressions in a single row.
14971 See <xref linkend="functions-aggregate"/> for additional information
14972 about aggregate functions.
14973 </para>
14974
14975 <para>
14976 Example:
14977 <screen><![CDATA[
14978 CREATE TABLE test (y int, x xml);
14979 INSERT INTO test VALUES (1, '<foo>abc</foo>');
14980 INSERT INTO test VALUES (2, '<bar/>');
14981 SELECT xmlagg(x) FROM test;
14982 xmlagg
14983 ----------------------
14984 <foo>abc</foo><bar/>
14985 ]]></screen>
14986 </para>
14987
14988 <para>
14989 To determine the order of the concatenation, an <literal>ORDER BY</literal>
14990 clause may be added to the aggregate call as described in
14991 <xref linkend="syntax-aggregates"/>. For example:
14992
14993 <screen><![CDATA[
14994 SELECT xmlagg(x ORDER BY y DESC) FROM test;
14995 xmlagg
14996 ----------------------
14997 <bar/><foo>abc</foo>
14998 ]]></screen>
14999 </para>
15000
15001 <para>
15002 The following non-standard approach used to be recommended
15003 in previous versions, and may still be useful in specific
15004 cases:
15005
15006 <screen><![CDATA[
15007 SELECT xmlagg(x) FROM (SELECT * FROM test ORDER BY y DESC) AS tab;
15008 xmlagg
15009 ----------------------
15010 <bar/><foo>abc</foo>
15011 ]]></screen>
15012 </para>
15013 </sect3>
15014 </sect2>
15015
15016 <sect2 id="functions-xml-predicates">
15017 <title>XML Predicates</title>
15018
15019 <para>
15020 The expressions described in this section check properties
15021 of <type>xml</type> values.
15022 </para>
15023
15024 <sect3 id="functions-producing-xml-is-document">
15025 <title><literal>IS DOCUMENT</literal></title>
15026
15027 <indexterm>
15028 <primary>IS DOCUMENT</primary>
15029 </indexterm>
15030
15031 <synopsis>
15032 <type>xml</type> <literal>IS DOCUMENT</literal> <returnvalue>boolean</returnvalue>
15033 </synopsis>
15034
15035 <para>
15036 The expression <literal>IS DOCUMENT</literal> returns true if the
15037 argument XML value is a proper XML document, false if it is not
15038 (that is, it is a content fragment), or null if the argument is
15039 null. See <xref linkend="datatype-xml"/> about the difference
15040 between documents and content fragments.
15041 </para>
15042 </sect3>
15043
15044 <sect3 id="functions-producing-xml-is-not-document">
15045 <title><literal>IS NOT DOCUMENT</literal></title>
15046
15047 <indexterm>
15048 <primary>IS NOT DOCUMENT</primary>
15049 </indexterm>
15050
15051 <synopsis>
15052 <type>xml</type> <literal>IS NOT DOCUMENT</literal> <returnvalue>boolean</returnvalue>
15053 </synopsis>
15054
15055 <para>
15056 The expression <literal>IS NOT DOCUMENT</literal> returns false if the
15057 argument XML value is a proper XML document, true if it is not (that is,
15058 it is a content fragment), or null if the argument is null.
15059 </para>
15060 </sect3>
15061
15062 <sect3 id="xml-exists">
15063 <title><literal>XMLEXISTS</literal></title>
15064
15065 <indexterm>
15066 <primary>XMLEXISTS</primary>
15067 </indexterm>
15068
15069 <synopsis>
15070 <function>XMLEXISTS</function> ( <type>text</type> <literal>PASSING</literal> <optional><literal>BY</literal> {<literal>REF</literal>|<literal>VALUE</literal>}</optional> <type>xml</type> <optional><literal>BY</literal> {<literal>REF</literal>|<literal>VALUE</literal>}</optional> ) <returnvalue>boolean</returnvalue>
15071 </synopsis>
15072
15073 <para>
15074 The function <function>xmlexists</function> evaluates an XPath 1.0
15075 expression (the first argument), with the passed XML value as its context
15076 item. The function returns false if the result of that evaluation
15077 yields an empty node-set, true if it yields any other value. The
15078 function returns null if any argument is null. A nonnull value
15079 passed as the context item must be an XML document, not a content
15080 fragment or any non-XML value.
15081 </para>
15082
15083 <para>
15084 Example:
15085 <screen><![CDATA[
15086 SELECT xmlexists('//town[text() = ''Toronto'']' PASSING BY VALUE '<towns><town>Toronto</town><town>Ottawa</town></towns>');
15087
15088 xmlexists
15089 ------------
15090 t
15091 (1 row)
15092 ]]></screen>
15093 </para>
15094
15095 <para>
15096 The <literal>BY REF</literal> and <literal>BY VALUE</literal> clauses
15097 are accepted in <productname>PostgreSQL</productname>, but are ignored,
15098 as discussed in <xref linkend="functions-xml-limits-postgresql"/>.
15099 </para>
15100
15101 <para>
15102 In the SQL standard, the <function>xmlexists</function> function
15103 evaluates an expression in the XML Query language,
15104 but <productname>PostgreSQL</productname> allows only an XPath 1.0
15105 expression, as discussed in
15106 <xref linkend="functions-xml-limits-xpath1"/>.
15107 </para>
15108 </sect3>
15109
15110 <sect3 id="xml-is-well-formed">
15111 <title><literal>xml_is_well_formed</literal></title>
15112
15113 <indexterm>
15114 <primary>xml_is_well_formed</primary>
15115 </indexterm>
15116
15117 <indexterm>
15118 <primary>xml_is_well_formed_document</primary>
15119 </indexterm>
15120
15121 <indexterm>
15122 <primary>xml_is_well_formed_content</primary>
15123 </indexterm>
15124
15125 <synopsis>
15126 <function>xml_is_well_formed</function> ( <type>text</type> ) <returnvalue>boolean</returnvalue>
15127 <function>xml_is_well_formed_document</function> ( <type>text</type> ) <returnvalue>boolean</returnvalue>
15128 <function>xml_is_well_formed_content</function> ( <type>text</type> ) <returnvalue>boolean</returnvalue>
15129 </synopsis>
15130
15131 <para>
15132 These functions check whether a <type>text</type> string represents
15133 well-formed XML, returning a Boolean result.
15134 <function>xml_is_well_formed_document</function> checks for a well-formed
15135 document, while <function>xml_is_well_formed_content</function> checks
15136 for well-formed content. <function>xml_is_well_formed</function> does
15137 the former if the <xref linkend="guc-xmloption"/> configuration
15138 parameter is set to <literal>DOCUMENT</literal>, or the latter if it is set to
15139 <literal>CONTENT</literal>. This means that
15140 <function>xml_is_well_formed</function> is useful for seeing whether
15141 a simple cast to type <type>xml</type> will succeed, whereas the other two
15142 functions are useful for seeing whether the corresponding variants of
15143 <function>XMLPARSE</function> will succeed.
15144 </para>
15145
15146 <para>
15147 Examples:
15148
15149 <screen><![CDATA[
15150 SET xmloption TO DOCUMENT;
15151 SELECT xml_is_well_formed('<>');
15152 xml_is_well_formed
15153 --------------------
15154 f
15155 (1 row)
15156
15157 SELECT xml_is_well_formed('<abc/>');
15158 xml_is_well_formed
15159 --------------------
15160 t
15161 (1 row)
15162
15163 SET xmloption TO CONTENT;
15164 SELECT xml_is_well_formed('abc');
15165 xml_is_well_formed
15166 --------------------
15167 t
15168 (1 row)
15169
15170 SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</pg:foo>');
15171 xml_is_well_formed_document
15172 -----------------------------
15173 t
15174 (1 row)
15175
15176 SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</my:foo>');
15177 xml_is_well_formed_document
15178 -----------------------------
15179 f
15180 (1 row)
15181 ]]></screen>
15182
15183 The last example shows that the checks include whether
15184 namespaces are correctly matched.
15185 </para>
15186 </sect3>
15187 </sect2>
15188
15189 <sect2 id="functions-xml-processing">
15190 <title>Processing XML</title>
15191
15192 <para>
15193 To process values of data type <type>xml</type>, PostgreSQL offers
15194 the functions <function>xpath</function> and
15195 <function>xpath_exists</function>, which evaluate XPath 1.0
15196 expressions, and the <function>XMLTABLE</function>
15197 table function.
15198 </para>
15199
15200 <sect3 id="functions-xml-processing-xpath">
15201 <title><literal>xpath</literal></title>
15202
15203 <indexterm>
15204 <primary>XPath</primary>
15205 </indexterm>
15206
15207 <synopsis>
15208 <function>xpath</function> ( <parameter>xpath</parameter> <type>text</type>, <parameter>xml</parameter> <type>xml</type> <optional>, <parameter>nsarray</parameter> <type>text[]</type> </optional> ) <returnvalue>xml[]</returnvalue>
15209 </synopsis>
15210
15211 <para>
15212 The function <function>xpath</function> evaluates the XPath 1.0
15213 expression <parameter>xpath</parameter> (given as text)
15214 against the XML value
15215 <parameter>xml</parameter>. It returns an array of XML values
15216 corresponding to the node-set produced by the XPath expression.
15217 If the XPath expression returns a scalar value rather than a node-set,
15218 a single-element array is returned.
15219 </para>
15220
15221 <para>
15222 The second argument must be a well formed XML document. In particular,
15223 it must have a single root node element.
15224 </para>
15225
15226 <para>
15227 The optional third argument of the function is an array of namespace
15228 mappings. This array should be a two-dimensional <type>text</type> array with
15229 the length of the second axis being equal to 2 (i.e., it should be an
15230 array of arrays, each of which consists of exactly 2 elements).
15231 The first element of each array entry is the namespace name (alias), the
15232 second the namespace URI. It is not required that aliases provided in
15233 this array be the same as those being used in the XML document itself (in
15234 other words, both in the XML document and in the <function>xpath</function>
15235 function context, aliases are <emphasis>local</emphasis>).
15236 </para>
15237
15238 <para>
15239 Example:
15240 <screen><![CDATA[
15241 SELECT xpath('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
15242 ARRAY[ARRAY['my', 'http://example.com']]);
15243
15244 xpath
15245 --------
15246 {test}
15247 (1 row)
15248 ]]></screen>
15249 </para>
15250
15251 <para>
15252 To deal with default (anonymous) namespaces, do something like this:
15253 <screen><![CDATA[
15254 SELECT xpath('//mydefns:b/text()', '<a xmlns="http://example.com"><b>test</b></a>',
15255 ARRAY[ARRAY['mydefns', 'http://example.com']]);
15256
15257 xpath
15258 --------
15259 {test}
15260 (1 row)
15261 ]]></screen>
15262 </para>
15263 </sect3>
15264
15265 <sect3 id="functions-xml-processing-xpath-exists">
15266 <title><literal>xpath_exists</literal></title>
15267
15268 <indexterm>
15269 <primary>xpath_exists</primary>
15270 </indexterm>
15271
15272 <synopsis>
15273 <function>xpath_exists</function> ( <parameter>xpath</parameter> <type>text</type>, <parameter>xml</parameter> <type>xml</type> <optional>, <parameter>nsarray</parameter> <type>text[]</type> </optional> ) <returnvalue>boolean</returnvalue>
15274 </synopsis>
15275
15276 <para>
15277 The function <function>xpath_exists</function> is a specialized form
15278 of the <function>xpath</function> function. Instead of returning the
15279 individual XML values that satisfy the XPath 1.0 expression, this function
15280 returns a Boolean indicating whether the query was satisfied or not
15281 (specifically, whether it produced any value other than an empty node-set).
15282 This function is equivalent to the <literal>XMLEXISTS</literal> predicate,
15283 except that it also offers support for a namespace mapping argument.
15284 </para>
15285
15286 <para>
15287 Example:
15288 <screen><![CDATA[
15289 SELECT xpath_exists('/my:a/text()', '<my:a xmlns:my="http://example.com">test</my:a>',
15290 ARRAY[ARRAY['my', 'http://example.com']]);
15291
15292 xpath_exists
15293 --------------
15294 t
15295 (1 row)
15296 ]]></screen>
15297 </para>
15298 </sect3>
15299
15300 <sect3 id="functions-xml-processing-xmltable">
15301 <title><literal>xmltable</literal></title>
15302
15303 <indexterm>
15304 <primary>xmltable</primary>
15305 </indexterm>
15306
15307 <indexterm zone="functions-xml-processing-xmltable">
15308 <primary>table function</primary>
15309 <secondary>XMLTABLE</secondary>
15310 </indexterm>
15311
15312 <synopsis>
15313 <function>XMLTABLE</function> (
15314 <optional> <literal>XMLNAMESPACES</literal> ( <replaceable>namespace_uri</replaceable> <literal>AS</literal> <replaceable>namespace_name</replaceable> <optional>, ...</optional> ), </optional>
15315 <replaceable>row_expression</replaceable> <literal>PASSING</literal> <optional><literal>BY</literal> {<literal>REF</literal>|<literal>VALUE</literal>}</optional> <replaceable>document_expression</replaceable> <optional><literal>BY</literal> {<literal>REF</literal>|<literal>VALUE</literal>}</optional>
15316 <literal>COLUMNS</literal> <replaceable>name</replaceable> { <replaceable>type</replaceable> <optional><literal>PATH</literal> <replaceable>column_expression</replaceable></optional> <optional><literal>DEFAULT</literal> <replaceable>default_expression</replaceable></optional> <optional><literal>NOT NULL</literal> | <literal>NULL</literal></optional>
15317 | <literal>FOR ORDINALITY</literal> }
15318 <optional>, ...</optional>
15319 ) <returnvalue>setof record</returnvalue>
15320 </synopsis>
15321
15322 <para>
15323 The <function>xmltable</function> expression produces a table based
15324 on an XML value, an XPath filter to extract rows, and a
15325 set of column definitions.
15326 Although it syntactically resembles a function, it can only appear
15327 as a table in a query's <literal>FROM</literal> clause.
15328 </para>
15329
15330 <para>
15331 The optional <literal>XMLNAMESPACES</literal> clause gives a
15332 comma-separated list of namespace definitions, where
15333 each <replaceable>namespace_uri</replaceable> is a <type>text</type>
15334 expression and each <replaceable>namespace_name</replaceable> is a simple
15335 identifier. It specifies the XML namespaces used in the document and
15336 their aliases. A default namespace specification is not currently
15337 supported.
15338 </para>
15339
15340 <para>
15341 The required <replaceable>row_expression</replaceable> argument is an
15342 XPath 1.0 expression (given as <type>text</type>) that is evaluated,
15343 passing the XML value <replaceable>document_expression</replaceable> as
15344 its context item, to obtain a set of XML nodes. These nodes are what
15345 <function>xmltable</function> transforms into output rows. No rows
15346 will be produced if the <replaceable>document_expression</replaceable>
15347 is null, nor if the <replaceable>row_expression</replaceable> produces
15348 an empty node-set or any value other than a node-set.
15349 </para>
15350
15351 <para>
15352 <replaceable>document_expression</replaceable> provides the context
15353 item for the <replaceable>row_expression</replaceable>. It must be a
15354 well-formed XML document; fragments/forests are not accepted.
15355 The <literal>BY REF</literal> and <literal>BY VALUE</literal> clauses
15356 are accepted but ignored, as discussed in
15357 <xref linkend="functions-xml-limits-postgresql"/>.
15358 </para>
15359
15360 <para>
15361 In the SQL standard, the <function>xmltable</function> function
15362 evaluates expressions in the XML Query language,
15363 but <productname>PostgreSQL</productname> allows only XPath 1.0
15364 expressions, as discussed in
15365 <xref linkend="functions-xml-limits-xpath1"/>.
15366 </para>
15367
15368 <para>
15369 The required <literal>COLUMNS</literal> clause specifies the
15370 column(s) that will be produced in the output table.
15371 See the syntax summary above for the format.
15372 A name is required for each column, as is a data type
15373 (unless <literal>FOR ORDINALITY</literal> is specified, in which case
15374 type <type>integer</type> is implicit). The path, default and
15375 nullability clauses are optional.
15376 </para>
15377
15378 <para>
15379 A column marked <literal>FOR ORDINALITY</literal> will be populated
15380 with row numbers, starting with 1, in the order of nodes retrieved from
15381 the <replaceable>row_expression</replaceable>'s result node-set.
15382 At most one column may be marked <literal>FOR ORDINALITY</literal>.
15383 </para>
15384
15385 <note>
15386 <para>
15387 XPath 1.0 does not specify an order for nodes in a node-set, so code
15388 that relies on a particular order of the results will be
15389 implementation-dependent. Details can be found in
15390 <xref linkend="xml-xpath-1-specifics"/>.
15391 </para>
15392 </note>
15393
15394 <para>
15395 The <replaceable>column_expression</replaceable> for a column is an
15396 XPath 1.0 expression that is evaluated for each row, with the current
15397 node from the <replaceable>row_expression</replaceable> result as its
15398 context item, to find the value of the column. If
15399 no <replaceable>column_expression</replaceable> is given, then the
15400 column name is used as an implicit path.
15401 </para>
15402
15403 <para>
15404 If a column's XPath expression returns a non-XML value (which is limited
15405 to string, boolean, or double in XPath 1.0) and the column has a
15406 PostgreSQL type other than <type>xml</type>, the column will be set
15407 as if by assigning the value's string representation to the PostgreSQL
15408 type. (If the value is a boolean, its string representation is taken
15409 to be <literal>1</literal> or <literal>0</literal> if the output
15410 column's type category is numeric, otherwise <literal>true</literal> or
15411 <literal>false</literal>.)
15412 </para>
15413
15414 <para>
15415 If a column's XPath expression returns a non-empty set of XML nodes
15416 and the column's PostgreSQL type is <type>xml</type>, the column will
15417 be assigned the expression result exactly, if it is of document or
15418 content form.
15419 <footnote>
15420 <para>
15421 A result containing more than one element node at the top level, or
15422 non-whitespace text outside of an element, is an example of content form.
15423 An XPath result can be of neither form, for example if it returns an
15424 attribute node selected from the element that contains it. Such a result
15425 will be put into content form with each such disallowed node replaced by
15426 its string value, as defined for the XPath 1.0
15427 <function>string</function> function.
15428 </para>
15429 </footnote>
15430 </para>
15431
15432 <para>
15433 A non-XML result assigned to an <type>xml</type> output column produces
15434 content, a single text node with the string value of the result.
15435 An XML result assigned to a column of any other type may not have more than
15436 one node, or an error is raised. If there is exactly one node, the column
15437 will be set as if by assigning the node's string
15438 value (as defined for the XPath 1.0 <function>string</function> function)
15439 to the PostgreSQL type.
15440 </para>
15441
15442 <para>
15443 The string value of an XML element is the concatenation, in document order,
15444 of all text nodes contained in that element and its descendants. The string
15445 value of an element with no descendant text nodes is an
15446 empty string (not <literal>NULL</literal>).
15447 Any <literal>xsi:nil</literal> attributes are ignored.
15448 Note that the whitespace-only <literal>text()</literal> node between two non-text
15449 elements is preserved, and that leading whitespace on a <literal>text()</literal>
15450 node is not flattened.
15451 The XPath 1.0 <function>string</function> function may be consulted for the
15452 rules defining the string value of other XML node types and non-XML values.
15453 </para>
15454
15455 <para>
15456 The conversion rules presented here are not exactly those of the SQL
15457 standard, as discussed in <xref linkend="functions-xml-limits-casts"/>.
15458 </para>
15459
15460 <para>
15461 If the path expression returns an empty node-set
15462 (typically, when it does not match)
15463 for a given row, the column will be set to <literal>NULL</literal>, unless
15464 a <replaceable>default_expression</replaceable> is specified; then the
15465 value resulting from evaluating that expression is used.
15466 </para>
15467
15468 <para>
15469 A <replaceable>default_expression</replaceable>, rather than being
15470 evaluated immediately when <function>xmltable</function> is called,
15471 is evaluated each time a default is needed for the column.
15472 If the expression qualifies as stable or immutable, the repeat
15473 evaluation may be skipped.
15474 This means that you can usefully use volatile functions like
15475 <function>nextval</function> in
15476 <replaceable>default_expression</replaceable>.
15477 </para>
15478
15479 <para>
15480 Columns may be marked <literal>NOT NULL</literal>. If the
15481 <replaceable>column_expression</replaceable> for a <literal>NOT
15482 NULL</literal> column does not match anything and there is
15483 no <literal>DEFAULT</literal> or
15484 the <replaceable>default_expression</replaceable> also evaluates to null,
15485 an error is reported.
15486 </para>
15487
15488 <para>
15489 Examples:
15490 <screen><![CDATA[
15491 CREATE TABLE xmldata AS SELECT
15492 xml $$
15493 <ROWS>
15494 <ROW id="1">
15495 <COUNTRY_ID>AU</COUNTRY_ID>
15496 <COUNTRY_NAME>Australia</COUNTRY_NAME>
15497 </ROW>
15498 <ROW id="5">
15499 <COUNTRY_ID>JP</COUNTRY_ID>
15500 <COUNTRY_NAME>Japan</COUNTRY_NAME>
15501 <PREMIER_NAME>Shinzo Abe</PREMIER_NAME>
15502 <SIZE unit="sq_mi">145935</SIZE>
15503 </ROW>
15504 <ROW id="6">
15505 <COUNTRY_ID>SG</COUNTRY_ID>
15506 <COUNTRY_NAME>Singapore</COUNTRY_NAME>
15507 <SIZE unit="sq_km">697</SIZE>
15508 </ROW>
15509 </ROWS>
15510 $$ AS data;
15511
15512 SELECT xmltable.*
15513 FROM xmldata,
15514 XMLTABLE('//ROWS/ROW'
15515 PASSING data
15516 COLUMNS id int PATH '@id',
15517 ordinality FOR ORDINALITY,
15518 "COUNTRY_NAME" text,
15519 country_id text PATH 'COUNTRY_ID',
15520 size_sq_km float PATH 'SIZE[@unit = "sq_km"]',
15521 size_other text PATH
15522 'concat(SIZE[@unit!="sq_km"], " ", SIZE[@unit!="sq_km"]/@unit)',
15523 premier_name text PATH 'PREMIER_NAME' DEFAULT 'not specified');
15524
15525 id | ordinality | COUNTRY_NAME | country_id | size_sq_km | size_other | premier_name
15526 ----+------------+--------------+------------+------------+--------------+---------------
15527 1 | 1 | Australia | AU | | | not specified
15528 5 | 2 | Japan | JP | | 145935 sq_mi | Shinzo Abe
15529 6 | 3 | Singapore | SG | 697 | | not specified
15530 ]]></screen>
15531
15532 The following example shows concatenation of multiple text() nodes,
15533 usage of the column name as XPath filter, and the treatment of whitespace,
15534 XML comments and processing instructions:
15535
15536 <screen><![CDATA[
15537 CREATE TABLE xmlelements AS SELECT
15538 xml $$
15539 <root>
15540 <element> Hello<!-- xyxxz -->2a2<?aaaaa?> <!--x--> bbb<x>xxx</x>CC </element>
15541 </root>
15542 $$ AS data;
15543
15544 SELECT xmltable.*
15545 FROM xmlelements, XMLTABLE('/root' PASSING data COLUMNS element text);
15546 element
15547 -------------------------
15548 Hello2a2 bbbxxxCC
15549 ]]></screen>
15550 </para>
15551
15552 <para>
15553 The following example illustrates how
15554 the <literal>XMLNAMESPACES</literal> clause can be used to specify
15555 a list of namespaces
15556 used in the XML document as well as in the XPath expressions:
15557
15558 <screen><![CDATA[
15559 WITH xmldata(data) AS (VALUES ('
15560 <example xmlns="http://example.com/myns" xmlns:B="http://example.com/b">
15561 <item foo="1" B:bar="2"/>
15562 <item foo="3" B:bar="4"/>
15563 <item foo="4" B:bar="5"/>
15564 </example>'::xml)
15565 )
15566 SELECT xmltable.*
15567 FROM XMLTABLE(XMLNAMESPACES('http://example.com/myns' AS x,
15568 'http://example.com/b' AS "B"),
15569 '/x:example/x:item'
15570 PASSING (SELECT data FROM xmldata)
15571 COLUMNS foo int PATH '@foo',
15572 bar int PATH '@B:bar');
15573 foo | bar
15574 -----+-----
15575 1 | 2
15576 3 | 4
15577 4 | 5
15578 (3 rows)
15579 ]]></screen>
15580 </para>
15581 </sect3>
15582 </sect2>
15583
15584 <sect2 id="functions-xml-mapping">
15585 <title>Mapping Tables to XML</title>
15586
15587 <indexterm zone="functions-xml-mapping">
15588 <primary>XML export</primary>
15589 </indexterm>
15590
15591 <para>
15592 The following functions map the contents of relational tables to
15593 XML values. They can be thought of as XML export functionality:
15594 <synopsis>
15595 <function>table_to_xml</function> ( <parameter>table</parameter> <type>regclass</type>, <parameter>nulls</parameter> <type>boolean</type>,
15596 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15597 <function>query_to_xml</function> ( <parameter>query</parameter> <type>text</type>, <parameter>nulls</parameter> <type>boolean</type>,
15598 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15599 <function>cursor_to_xml</function> ( <parameter>cursor</parameter> <type>refcursor</type>, <parameter>count</parameter> <type>integer</type>, <parameter>nulls</parameter> <type>boolean</type>,
15600 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15601 </synopsis>
15602 </para>
15603
15604 <para>
15605 <function>table_to_xml</function> maps the content of the named
15606 table, passed as parameter <parameter>table</parameter>. The
15607 <type>regclass</type> type accepts strings identifying tables using the
15608 usual notation, including optional schema qualification and
15609 double quotes (see <xref linkend="datatype-oid"/> for details).
15610 <function>query_to_xml</function> executes the
15611 query whose text is passed as parameter
15612 <parameter>query</parameter> and maps the result set.
15613 <function>cursor_to_xml</function> fetches the indicated number of
15614 rows from the cursor specified by the parameter
15615 <parameter>cursor</parameter>. This variant is recommended if
15616 large tables have to be mapped, because the result value is built
15617 up in memory by each function.
15618 </para>
15619
15620 <para>
15621 If <parameter>tableforest</parameter> is false, then the resulting
15622 XML document looks like this:
15623 <screen><![CDATA[
15624 <tablename>
15625 <row>
15626 <columnname1>data</columnname1>
15627 <columnname2>data</columnname2>
15628 </row>
15629
15630 <row>
15631 ...
15632 </row>
15633
15634 ...
15635 </tablename>
15636 ]]></screen>
15637
15638 If <parameter>tableforest</parameter> is true, the result is an
15639 XML content fragment that looks like this:
15640 <screen><![CDATA[
15641 <tablename>
15642 <columnname1>data</columnname1>
15643 <columnname2>data</columnname2>
15644 </tablename>
15645
15646 <tablename>
15647 ...
15648 </tablename>
15649
15650 ...
15651 ]]></screen>
15652
15653 If no table name is available, that is, when mapping a query or a
15654 cursor, the string <literal>table</literal> is used in the first
15655 format, <literal>row</literal> in the second format.
15656 </para>
15657
15658 <para>
15659 The choice between these formats is up to the user. The first
15660 format is a proper XML document, which will be important in many
15661 applications. The second format tends to be more useful in the
15662 <function>cursor_to_xml</function> function if the result values are to be
15663 reassembled into one document later on. The functions for
15664 producing XML content discussed above, in particular
15665 <function>xmlelement</function>, can be used to alter the results
15666 to taste.
15667 </para>
15668
15669 <para>
15670 The data values are mapped in the same way as described for the
15671 function <function>xmlelement</function> above.
15672 </para>
15673
15674 <para>
15675 The parameter <parameter>nulls</parameter> determines whether null
15676 values should be included in the output. If true, null values in
15677 columns are represented as:
15678 <screen><![CDATA[
15679 <columnname xsi:nil="true"/>
15680 ]]></screen>
15681 where <literal>xsi</literal> is the XML namespace prefix for XML
15682 Schema Instance. An appropriate namespace declaration will be
15683 added to the result value. If false, columns containing null
15684 values are simply omitted from the output.
15685 </para>
15686
15687 <para>
15688 The parameter <parameter>targetns</parameter> specifies the
15689 desired XML namespace of the result. If no particular namespace
15690 is wanted, an empty string should be passed.
15691 </para>
15692
15693 <para>
15694 The following functions return XML Schema documents describing the
15695 mappings performed by the corresponding functions above:
15696 <synopsis>
15697 <function>table_to_xmlschema</function> ( <parameter>table</parameter> <type>regclass</type>, <parameter>nulls</parameter> <type>boolean</type>,
15698 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15699 <function>query_to_xmlschema</function> ( <parameter>query</parameter> <type>text</type>, <parameter>nulls</parameter> <type>boolean</type>,
15700 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15701 <function>cursor_to_xmlschema</function> ( <parameter>cursor</parameter> <type>refcursor</type>, <parameter>nulls</parameter> <type>boolean</type>,
15702 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15703 </synopsis>
15704 It is essential that the same parameters are passed in order to
15705 obtain matching XML data mappings and XML Schema documents.
15706 </para>
15707
15708 <para>
15709 The following functions produce XML data mappings and the
15710 corresponding XML Schema in one document (or forest), linked
15711 together. They can be useful where self-contained and
15712 self-describing results are wanted:
15713 <synopsis>
15714 <function>table_to_xml_and_xmlschema</function> ( <parameter>table</parameter> <type>regclass</type>, <parameter>nulls</parameter> <type>boolean</type>,
15715 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15716 <function>query_to_xml_and_xmlschema</function> ( <parameter>query</parameter> <type>text</type>, <parameter>nulls</parameter> <type>boolean</type>,
15717 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15718 </synopsis>
15719 </para>
15720
15721 <para>
15722 In addition, the following functions are available to produce
15723 analogous mappings of entire schemas or the entire current
15724 database:
15725 <synopsis>
15726 <function>schema_to_xml</function> ( <parameter>schema</parameter> <type>name</type>, <parameter>nulls</parameter> <type>boolean</type>,
15727 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15728 <function>schema_to_xmlschema</function> ( <parameter>schema</parameter> <type>name</type>, <parameter>nulls</parameter> <type>boolean</type>,
15729 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15730 <function>schema_to_xml_and_xmlschema</function> ( <parameter>schema</parameter> <type>name</type>, <parameter>nulls</parameter> <type>boolean</type>,
15731 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15732
15733 <function>database_to_xml</function> ( <parameter>nulls</parameter> <type>boolean</type>,
15734 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15735 <function>database_to_xmlschema</function> ( <parameter>nulls</parameter> <type>boolean</type>,
15736 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15737 <function>database_to_xml_and_xmlschema</function> ( <parameter>nulls</parameter> <type>boolean</type>,
15738 <parameter>tableforest</parameter> <type>boolean</type>, <parameter>targetns</parameter> <type>text</type> ) <returnvalue>xml</returnvalue>
15739 </synopsis>
15740
15741 These functions ignore tables that are not readable by the current user.
15742 The database-wide functions additionally ignore schemas that the current
15743 user does not have <literal>USAGE</literal> (lookup) privilege for.
15744 </para>
15745
15746 <para>
15747 Note that these potentially produce a lot of data, which needs to
15748 be built up in memory. When requesting content mappings of large
15749 schemas or databases, it might be worthwhile to consider mapping the
15750 tables separately instead, possibly even through a cursor.
15751 </para>
15752
15753 <para>
15754 The result of a schema content mapping looks like this:
15755
15756 <screen><![CDATA[
15757 <schemaname>
15758
15759 table1-mapping
15760
15761 table2-mapping
15762
15763 ...
15764
15765 </schemaname>]]></screen>
15766
15767 where the format of a table mapping depends on the
15768 <parameter>tableforest</parameter> parameter as explained above.
15769 </para>
15770
15771 <para>
15772 The result of a database content mapping looks like this:
15773
15774 <screen><![CDATA[
15775 <dbname>
15776
15777 <schema1name>
15778 ...
15779 </schema1name>
15780
15781 <schema2name>
15782 ...
15783 </schema2name>
15784
15785 ...
15786
15787 </dbname>]]></screen>
15788
15789 where the schema mapping is as above.
15790 </para>
15791
15792 <para>
15793 As an example of using the output produced by these functions,
15794 <xref linkend="xslt-xml-html"/> shows an XSLT stylesheet that
15795 converts the output of
15796 <function>table_to_xml_and_xmlschema</function> to an HTML
15797 document containing a tabular rendition of the table data. In a
15798 similar manner, the results from these functions can be
15799 converted into other XML-based formats.
15800 </para>
15801
15802 <example id="xslt-xml-html">
15803 <title>XSLT Stylesheet for Converting SQL/XML Output to HTML</title>
15804 <programlisting><![CDATA[
15805 <?xml version="1.0"?>
15806 <xsl:stylesheet version="1.0"
15807 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
15808 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
15809 xmlns="http://www.w3.org/1999/xhtml"
15810 >
15811
15812 <xsl:output method="xml"
15813 doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
15814 doctype-public="-//W3C/DTD XHTML 1.0 Strict//EN"
15815 indent="yes"/>
15816
15817 <xsl:template match="/*">
15818 <xsl:variable name="schema" select="//xsd:schema"/>
15819 <xsl:variable name="tabletypename"
15820 select="$schema/xsd:element[@name=name(current())]/@type"/>
15821 <xsl:variable name="rowtypename"
15822 select="$schema/xsd:complexType[@name=$tabletypename]/xsd:sequence/xsd:element[@name='row']/@type"/>
15823
15824 <html>
15825 <head>
15826 <title><xsl:value-of select="name(current())"/></title>
15827 </head>
15828 <body>
15829 <table>
15830 <tr>
15831 <xsl:for-each select="$schema/xsd:complexType[@name=$rowtypename]/xsd:sequence/xsd:element/@name">
15832 <th><xsl:value-of select="."/></th>
15833 </xsl:for-each>
15834 </tr>
15835
15836 <xsl:for-each select="row">
15837 <tr>
15838 <xsl:for-each select="*">
15839 <td><xsl:value-of select="."/></td>
15840 </xsl:for-each>
15841 </tr>
15842 </xsl:for-each>
15843 </table>
15844 </body>
15845 </html>
15846 </xsl:template>
15847
15848 </xsl:stylesheet>
15849 ]]></programlisting>
15850 </example>
15851 </sect2>
15852 </sect1>
15853
15854 <sect1 id="functions-json">
15855 <title>JSON Functions and Operators</title>
15856
15857 <indexterm zone="functions-json">
15858 <primary>JSON</primary>
15859 <secondary>functions and operators</secondary>
15860 </indexterm>
15861 <indexterm zone="functions-json">
15862 <primary>SQL/JSON</primary>
15863 <secondary>functions and expressions</secondary>
15864 </indexterm>
15865
15866 <para>
15867 This section describes:
15868
15869 <itemizedlist>
15870 <listitem>
15871 <para>
15872 functions and operators for processing and creating JSON data
15873 </para>
15874 </listitem>
15875 <listitem>
15876 <para>
15877 the SQL/JSON path language
15878 </para>
15879 </listitem>
15880 <listitem>
15881 <para>
15882 the SQL/JSON query functions
15883 </para>
15884 </listitem>
15885 </itemizedlist>
15886 </para>
15887
15888 <para>
15889 To provide native support for JSON data types within the SQL environment,
15890 <productname>PostgreSQL</productname> implements the
15891 <firstterm>SQL/JSON data model</firstterm>.
15892 This model comprises sequences of items. Each item can hold SQL scalar
15893 values, with an additional SQL/JSON null value, and composite data structures
15894 that use JSON arrays and objects. The model is a formalization of the implied
15895 data model in the JSON specification
15896 <ulink url="https://datatracker.ietf.org/doc/html/rfc7159">RFC 7159</ulink>.
15897 </para>
15898
15899 <para>
15900 SQL/JSON allows you to handle JSON data alongside regular SQL data,
15901 with transaction support, including:
15902
15903 <itemizedlist>
15904 <listitem>
15905 <para>
15906 Uploading JSON data into the database and storing it in
15907 regular SQL columns as character or binary strings.
15908 </para>
15909 </listitem>
15910 <listitem>
15911 <para>
15912 Generating JSON objects and arrays from relational data.
15913 </para>
15914 </listitem>
15915 <listitem>
15916 <para>
15917 Querying JSON data using SQL/JSON query functions and
15918 SQL/JSON path language expressions.
15919 </para>
15920 </listitem>
15921 </itemizedlist>
15922 </para>
15923
15924 <para>
15925 To learn more about the SQL/JSON standard, see
15926 <xref linkend="sqltr-19075-6"/>. For details on JSON types
15927 supported in <productname>PostgreSQL</productname>,
15928 see <xref linkend="datatype-json"/>.
15929 </para>
15930
15931 <sect2 id="functions-json-processing">
15932 <title>Processing and Creating JSON Data</title>
15933
15934 <para>
15935 <xref linkend="functions-json-op-table"/> shows the operators that
15936 are available for use with JSON data types (see <xref
15937 linkend="datatype-json"/>).
15938 In addition, the usual comparison operators shown in <xref
15939 linkend="functions-comparison-op-table"/> are available for
15940 <type>jsonb</type>, though not for <type>json</type>. The comparison
15941 operators follow the ordering rules for B-tree operations outlined in
15942 <xref linkend="json-indexing"/>.
15943 See also <xref linkend="functions-aggregate"/> for the aggregate
15944 function <function>json_agg</function> which aggregates record
15945 values as JSON, the aggregate function
15946 <function>json_object_agg</function> which aggregates pairs of values
15947 into a JSON object, and their <type>jsonb</type> equivalents,
15948 <function>jsonb_agg</function> and <function>jsonb_object_agg</function>.
15949 </para>
15950
15951 <table id="functions-json-op-table">
15952 <title><type>json</type> and <type>jsonb</type> Operators</title>
15953 <tgroup cols="1">
15954 <thead>
15955 <row>
15956 <entry role="func_table_entry"><para role="func_signature">
15957 Operator
15958 </para>
15959 <para>
15960 Description
15961 </para>
15962 <para>
15963 Example(s)
15964 </para></entry>
15965 </row>
15966 </thead>
15967
15968 <tbody>
15969 <row>
15970 <entry role="func_table_entry"><para role="func_signature">
15971 <type>json</type> <literal>-&gt;</literal> <type>integer</type>
15972 <returnvalue>json</returnvalue>
15973 </para>
15974 <para role="func_signature">
15975 <type>jsonb</type> <literal>-&gt;</literal> <type>integer</type>
15976 <returnvalue>jsonb</returnvalue>
15977 </para>
15978 <para>
15979 Extracts <parameter>n</parameter>'th element of JSON array
15980 (array elements are indexed from zero, but negative integers count
15981 from the end).
15982 </para>
15983 <para>
15984 <literal>'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json -&gt; 2</literal>
15985 <returnvalue>{"c":"baz"}</returnvalue>
15986 </para>
15987 <para>
15988 <literal>'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json -&gt; -3</literal>
15989 <returnvalue>{"a":"foo"}</returnvalue>
15990 </para></entry>
15991 </row>
15992
15993 <row>
15994 <entry role="func_table_entry"><para role="func_signature">
15995 <type>json</type> <literal>-&gt;</literal> <type>text</type>
15996 <returnvalue>json</returnvalue>
15997 </para>
15998 <para role="func_signature">
15999 <type>jsonb</type> <literal>-&gt;</literal> <type>text</type>
16000 <returnvalue>jsonb</returnvalue>
16001 </para>
16002 <para>
16003 Extracts JSON object field with the given key.
16004 </para>
16005 <para>
16006 <literal>'{"a": {"b":"foo"}}'::json -&gt; 'a'</literal>
16007 <returnvalue>{"b":"foo"}</returnvalue>
16008 </para></entry>
16009 </row>
16010
16011 <row>
16012 <entry role="func_table_entry"><para role="func_signature">
16013 <type>json</type> <literal>-&gt;&gt;</literal> <type>integer</type>
16014 <returnvalue>text</returnvalue>
16015 </para>
16016 <para role="func_signature">
16017 <type>jsonb</type> <literal>-&gt;&gt;</literal> <type>integer</type>
16018 <returnvalue>text</returnvalue>
16019 </para>
16020 <para>
16021 Extracts <parameter>n</parameter>'th element of JSON array,
16022 as <type>text</type>.
16023 </para>
16024 <para>
16025 <literal>'[1,2,3]'::json -&gt;&gt; 2</literal>
16026 <returnvalue>3</returnvalue>
16027 </para></entry>
16028 </row>
16029
16030 <row>
16031 <entry role="func_table_entry"><para role="func_signature">
16032 <type>json</type> <literal>-&gt;&gt;</literal> <type>text</type>
16033 <returnvalue>text</returnvalue>
16034 </para>
16035 <para role="func_signature">
16036 <type>jsonb</type> <literal>-&gt;&gt;</literal> <type>text</type>
16037 <returnvalue>text</returnvalue>
16038 </para>
16039 <para>
16040 Extracts JSON object field with the given key, as <type>text</type>.
16041 </para>
16042 <para>
16043 <literal>'{"a":1,"b":2}'::json -&gt;&gt; 'b'</literal>
16044 <returnvalue>2</returnvalue>
16045 </para></entry>
16046 </row>
16047
16048 <row>
16049 <entry role="func_table_entry"><para role="func_signature">
16050 <type>json</type> <literal>#&gt;</literal> <type>text[]</type>
16051 <returnvalue>json</returnvalue>
16052 </para>
16053 <para role="func_signature">
16054 <type>jsonb</type> <literal>#&gt;</literal> <type>text[]</type>
16055 <returnvalue>jsonb</returnvalue>
16056 </para>
16057 <para>
16058 Extracts JSON sub-object at the specified path, where path elements
16059 can be either field keys or array indexes.
16060 </para>
16061 <para>
16062 <literal>'{"a": {"b": ["foo","bar"]}}'::json #&gt; '{a,b,1}'</literal>
16063 <returnvalue>"bar"</returnvalue>
16064 </para></entry>
16065 </row>
16066
16067 <row>
16068 <entry role="func_table_entry"><para role="func_signature">
16069 <type>json</type> <literal>#&gt;&gt;</literal> <type>text[]</type>
16070 <returnvalue>text</returnvalue>
16071 </para>
16072 <para role="func_signature">
16073 <type>jsonb</type> <literal>#&gt;&gt;</literal> <type>text[]</type>
16074 <returnvalue>text</returnvalue>
16075 </para>
16076 <para>
16077 Extracts JSON sub-object at the specified path as <type>text</type>.
16078 </para>
16079 <para>
16080 <literal>'{"a": {"b": ["foo","bar"]}}'::json #&gt;&gt; '{a,b,1}'</literal>
16081 <returnvalue>bar</returnvalue>
16082 </para></entry>
16083 </row>
16084 </tbody>
16085 </tgroup>
16086 </table>
16087
16088 <note>
16089 <para>
16090 The field/element/path extraction operators return NULL, rather than
16091 failing, if the JSON input does not have the right structure to match
16092 the request; for example if no such key or array element exists.
16093 </para>
16094 </note>
16095
16096 <para>
16097 Some further operators exist only for <type>jsonb</type>, as shown
16098 in <xref linkend="functions-jsonb-op-table"/>.
16099 <xref linkend="json-indexing"/>
16100 describes how these operators can be used to effectively search indexed
16101 <type>jsonb</type> data.
16102 </para>
16103
16104 <table id="functions-jsonb-op-table">
16105 <title>Additional <type>jsonb</type> Operators</title>
16106 <tgroup cols="1">
16107 <thead>
16108 <row>
16109 <entry role="func_table_entry"><para role="func_signature">
16110 Operator
16111 </para>
16112 <para>
16113 Description
16114 </para>
16115 <para>
16116 Example(s)
16117 </para></entry>
16118 </row>
16119 </thead>
16120
16121 <tbody>
16122 <row>
16123 <entry role="func_table_entry"><para role="func_signature">
16124 <type>jsonb</type> <literal>@&gt;</literal> <type>jsonb</type>
16125 <returnvalue>boolean</returnvalue>
16126 </para>
16127 <para>
16128 Does the first JSON value contain the second?
16129 (See <xref linkend="json-containment"/> for details about containment.)
16130 </para>
16131 <para>
16132 <literal>'{"a":1, "b":2}'::jsonb &#64;&gt; '{"b":2}'::jsonb</literal>
16133 <returnvalue>t</returnvalue>
16134 </para></entry>
16135 </row>
16136
16137 <row>
16138 <entry role="func_table_entry"><para role="func_signature">
16139 <type>jsonb</type> <literal>&lt;@</literal> <type>jsonb</type>
16140 <returnvalue>boolean</returnvalue>
16141 </para>
16142 <para>
16143 Is the first JSON value contained in the second?
16144 </para>
16145 <para>
16146 <literal>'{"b":2}'::jsonb &lt;@ '{"a":1, "b":2}'::jsonb</literal>
16147 <returnvalue>t</returnvalue>
16148 </para></entry>
16149 </row>
16150
16151 <row>
16152 <entry role="func_table_entry"><para role="func_signature">
16153 <type>jsonb</type> <literal>?</literal> <type>text</type>
16154 <returnvalue>boolean</returnvalue>
16155 </para>
16156 <para>
16157 Does the text string exist as a top-level key or array element within
16158 the JSON value?
16159 </para>
16160 <para>
16161 <literal>'{"a":1, "b":2}'::jsonb ? 'b'</literal>
16162 <returnvalue>t</returnvalue>
16163 </para>
16164 <para>
16165 <literal>'["a", "b", "c"]'::jsonb ? 'b'</literal>
16166 <returnvalue>t</returnvalue>
16167 </para></entry>
16168 </row>
16169
16170 <row>
16171 <entry role="func_table_entry"><para role="func_signature">
16172 <type>jsonb</type> <literal>?|</literal> <type>text[]</type>
16173 <returnvalue>boolean</returnvalue>
16174 </para>
16175 <para>
16176 Do any of the strings in the text array exist as top-level keys or
16177 array elements?
16178 </para>
16179 <para>
16180 <literal>'{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'd']</literal>
16181 <returnvalue>t</returnvalue>
16182 </para></entry>
16183 </row>
16184
16185 <row>
16186 <entry role="func_table_entry"><para role="func_signature">
16187 <type>jsonb</type> <literal>?&amp;</literal> <type>text[]</type>
16188 <returnvalue>boolean</returnvalue>
16189 </para>
16190 <para>
16191 Do all of the strings in the text array exist as top-level keys or
16192 array elements?
16193 </para>
16194 <para>
16195 <literal>'["a", "b", "c"]'::jsonb ?&amp; array['a', 'b']</literal>
16196 <returnvalue>t</returnvalue>
16197 </para></entry>
16198 </row>
16199
16200 <row>
16201 <entry role="func_table_entry"><para role="func_signature">
16202 <type>jsonb</type> <literal>||</literal> <type>jsonb</type>
16203 <returnvalue>jsonb</returnvalue>
16204 </para>
16205 <para>
16206 Concatenates two <type>jsonb</type> values.
16207 Concatenating two arrays generates an array containing all the
16208 elements of each input. Concatenating two objects generates an
16209 object containing the union of their
16210 keys, taking the second object's value when there are duplicate keys.
16211 All other cases are treated by converting a non-array input into a
16212 single-element array, and then proceeding as for two arrays.
16213 Does not operate recursively: only the top-level array or object
16214 structure is merged.
16215 </para>
16216 <para>
16217 <literal>'["a", "b"]'::jsonb || '["a", "d"]'::jsonb</literal>
16218 <returnvalue>["a", "b", "a", "d"]</returnvalue>
16219 </para>
16220 <para>
16221 <literal>'{"a": "b"}'::jsonb || '{"c": "d"}'::jsonb</literal>
16222 <returnvalue>{"a": "b", "c": "d"}</returnvalue>
16223 </para>
16224 <para>
16225 <literal>'[1, 2]'::jsonb || '3'::jsonb</literal>
16226 <returnvalue>[1, 2, 3]</returnvalue>
16227 </para>
16228 <para>
16229 <literal>'{"a": "b"}'::jsonb || '42'::jsonb</literal>
16230 <returnvalue>[{"a": "b"}, 42]</returnvalue>
16231 </para>
16232 <para>
16233 To append an array to another array as a single entry, wrap it
16234 in an additional layer of array, for example:
16235 </para>
16236 <para>
16237 <literal>'[1, 2]'::jsonb || jsonb_build_array('[3, 4]'::jsonb)</literal>
16238 <returnvalue>[1, 2, [3, 4]]</returnvalue>
16239 </para></entry>
16240 </row>
16241
16242 <row>
16243 <entry role="func_table_entry"><para role="func_signature">
16244 <type>jsonb</type> <literal>-</literal> <type>text</type>
16245 <returnvalue>jsonb</returnvalue>
16246 </para>
16247 <para>
16248 Deletes a key (and its value) from a JSON object, or matching string
16249 value(s) from a JSON array.
16250 </para>
16251 <para>
16252 <literal>'{"a": "b", "c": "d"}'::jsonb - 'a'</literal>
16253 <returnvalue>{"c": "d"}</returnvalue>
16254 </para>
16255 <para>
16256 <literal>'["a", "b", "c", "b"]'::jsonb - 'b'</literal>
16257 <returnvalue>["a", "c"]</returnvalue>
16258 </para></entry>
16259 </row>
16260
16261 <row>
16262 <entry role="func_table_entry"><para role="func_signature">
16263 <type>jsonb</type> <literal>-</literal> <type>text[]</type>
16264 <returnvalue>jsonb</returnvalue>
16265 </para>
16266 <para>
16267 Deletes all matching keys or array elements from the left operand.
16268 </para>
16269 <para>
16270 <literal>'{"a": "b", "c": "d"}'::jsonb - '{a,c}'::text[]</literal>
16271 <returnvalue>{}</returnvalue>
16272 </para></entry>
16273 </row>
16274
16275 <row>
16276 <entry role="func_table_entry"><para role="func_signature">
16277 <type>jsonb</type> <literal>-</literal> <type>integer</type>
16278 <returnvalue>jsonb</returnvalue>
16279 </para>
16280 <para>
16281 Deletes the array element with specified index (negative
16282 integers count from the end). Throws an error if JSON value
16283 is not an array.
16284 </para>
16285 <para>
16286 <literal>'["a", "b"]'::jsonb - 1 </literal>
16287 <returnvalue>["a"]</returnvalue>
16288 </para></entry>
16289 </row>
16290
16291 <row>
16292 <entry role="func_table_entry"><para role="func_signature">
16293 <type>jsonb</type> <literal>#-</literal> <type>text[]</type>
16294 <returnvalue>jsonb</returnvalue>
16295 </para>
16296 <para>
16297 Deletes the field or array element at the specified path, where path
16298 elements can be either field keys or array indexes.
16299 </para>
16300 <para>
16301 <literal>'["a", {"b":1}]'::jsonb #- '{1,b}'</literal>
16302 <returnvalue>["a", {}]</returnvalue>
16303 </para></entry>
16304 </row>
16305
16306 <row>
16307 <entry role="func_table_entry"><para role="func_signature">
16308 <type>jsonb</type> <literal>@?</literal> <type>jsonpath</type>
16309 <returnvalue>boolean</returnvalue>
16310 </para>
16311 <para>
16312 Does JSON path return any item for the specified JSON value?
16313 (This is useful only with SQL-standard JSON path expressions, not
16314 <link linkend="functions-sqljson-check-expressions">predicate check
16315 expressions</link>, since those always return a value.)
16316 </para>
16317 <para>
16318 <literal>'{"a":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)'</literal>
16319 <returnvalue>t</returnvalue>
16320 </para></entry>
16321 </row>
16322
16323 <row>
16324 <entry role="func_table_entry"><para role="func_signature">
16325 <type>jsonb</type> <literal>@@</literal> <type>jsonpath</type>
16326 <returnvalue>boolean</returnvalue>
16327 </para>
16328 <para>
16329 Returns the result of a JSON path predicate check for the
16330 specified JSON value.
16331 (This is useful only
16332 with <link linkend="functions-sqljson-check-expressions">predicate
16333 check expressions</link>, not SQL-standard JSON path expressions,
16334 since it will return <literal>NULL</literal> if the path result is
16335 not a single boolean value.)
16336 </para>
16337 <para>
16338 <literal>'{"a":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2'</literal>
16339 <returnvalue>t</returnvalue>
16340 </para></entry>
16341 </row>
16342 </tbody>
16343 </tgroup>
16344 </table>
16345
16346 <note>
16347 <para>
16348 The <type>jsonpath</type> operators <literal>@?</literal>
16349 and <literal>@@</literal> suppress the following errors: missing object
16350 field or array element, unexpected JSON item type, datetime and numeric
16351 errors. The <type>jsonpath</type>-related functions described below can
16352 also be told to suppress these types of errors. This behavior might be
16353 helpful when searching JSON document collections of varying structure.
16354 </para>
16355 </note>
16356
16357 <para>
16358 <xref linkend="functions-json-creation-table"/> shows the functions that are
16359 available for constructing <type>json</type> and <type>jsonb</type> values.
16360 Some functions in this table have a <literal>RETURNING</literal> clause,
16361 which specifies the data type returned. It must be one of <type>json</type>,
16362 <type>jsonb</type>, <type>bytea</type>, a character string type (<type>text</type>,
16363 <type>char</type>, or <type>varchar</type>), or a type
16364 that can be cast to <type>json</type>.
16365 By default, the <type>json</type> type is returned.
16366 </para>
16367
16368 <table id="functions-json-creation-table">
16369 <title>JSON Creation Functions</title>
16370 <tgroup cols="1">
16371 <thead>
16372 <row>
16373 <entry role="func_table_entry"><para role="func_signature">
16374 Function
16375 </para>
16376 <para>
16377 Description
16378 </para>
16379 <para>
16380 Example(s)
16381 </para></entry>
16382 </row>
16383 </thead>
16384
16385 <tbody>
16386 <row>
16387 <entry role="func_table_entry"><para role="func_signature">
16388 <indexterm>
16389 <primary>to_json</primary>
16390 </indexterm>
16391 <function>to_json</function> ( <type>anyelement</type> )
16392 <returnvalue>json</returnvalue>
16393 </para>
16394 <para role="func_signature">
16395 <indexterm>
16396 <primary>to_jsonb</primary>
16397 </indexterm>
16398 <function>to_jsonb</function> ( <type>anyelement</type> )
16399 <returnvalue>jsonb</returnvalue>
16400 </para>
16401 <para>
16402 Converts any SQL value to <type>json</type> or <type>jsonb</type>.
16403 Arrays and composites are converted recursively to arrays and
16404 objects (multidimensional arrays become arrays of arrays in JSON).
16405 Otherwise, if there is a cast from the SQL data type
16406 to <type>json</type>, the cast function will be used to perform the
16407 conversion;<footnote>
16408 <para>
16409 For example, the <xref linkend="hstore"/> extension has a cast
16410 from <type>hstore</type> to <type>json</type>, so that
16411 <type>hstore</type> values converted via the JSON creation functions
16412 will be represented as JSON objects, not as primitive string values.
16413 </para>
16414 </footnote>
16415 otherwise, a scalar JSON value is produced. For any scalar other than
16416 a number, a Boolean, or a null value, the text representation will be
16417 used, with escaping as necessary to make it a valid JSON string value.
16418 </para>
16419 <para>
16420 <literal>to_json('Fred said "Hi."'::text)</literal>
16421 <returnvalue>"Fred said \"Hi.\""</returnvalue>
16422 </para>
16423 <para>
16424 <literal>to_jsonb(row(42, 'Fred said "Hi."'::text))</literal>
16425 <returnvalue>{"f1": 42, "f2": "Fred said \"Hi.\""}</returnvalue>
16426 </para></entry>
16427 </row>
16428
16429 <row>
16430 <entry role="func_table_entry"><para role="func_signature">
16431 <indexterm>
16432 <primary>array_to_json</primary>
16433 </indexterm>
16434 <function>array_to_json</function> ( <type>anyarray</type> <optional>, <type>boolean</type> </optional> )
16435 <returnvalue>json</returnvalue>
16436 </para>
16437 <para>
16438 Converts an SQL array to a JSON array. The behavior is the same
16439 as <function>to_json</function> except that line feeds will be added
16440 between top-level array elements if the optional boolean parameter is
16441 true.
16442 </para>
16443 <para>
16444 <literal>array_to_json('{{1,5},{99,100}}'::int[])</literal>
16445 <returnvalue>[[1,5],[99,100]]</returnvalue>
16446 </para></entry>
16447 </row>
16448
16449 <row>
16450 <!--
16451 Note that this is barely legible in the output; it looks like a
16452 salad of braces and brackets. It would be better to split it out
16453 in multiple lines, but that's surprisingly hard to do in a way that
16454 matches in HTML and PDF output. Other standard SQL/JSON functions
16455 have the same problem.
16456 -->
16457 <entry role="func_table_entry"><para role="func_signature">
16458 <indexterm><primary>json_array</primary></indexterm>
16459 <function>json_array</function> (
16460 <optional> { <replaceable>value_expression</replaceable> <optional> <literal>FORMAT JSON</literal> </optional> } <optional>, ...</optional> </optional>
16461 <optional> { <literal>NULL</literal> | <literal>ABSENT</literal> } <literal>ON NULL</literal> </optional>
16462 <optional> <literal>RETURNING</literal> <replaceable>data_type</replaceable> <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional> </optional> </optional>)
16463 </para>
16464 <para role="func_signature">
16465 <function>json_array</function> (
16466 <optional> <replaceable>query_expression</replaceable> </optional>
16467 <optional> <literal>RETURNING</literal> <replaceable>data_type</replaceable> <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional> </optional> </optional>)
16468 </para>
16469 <para>
16470 Constructs a JSON array from either a series of
16471 <replaceable>value_expression</replaceable> parameters or from the results
16472 of <replaceable>query_expression</replaceable>,
16473 which must be a SELECT query returning a single column. If
16474 <literal>ABSENT ON NULL</literal> is specified, NULL values are ignored.
16475 This is always the case if a
16476 <replaceable>query_expression</replaceable> is used.
16477 </para>
16478 <para>
16479 <literal>json_array(1,true,json '{"a":null}')</literal>
16480 <returnvalue>[1, true, {"a":null}]</returnvalue>
16481 </para>
16482 <para>
16483 <literal>json_array(SELECT * FROM (VALUES(1),(2)) t)</literal>
16484 <returnvalue>[1, 2]</returnvalue>
16485 </para></entry>
16486 </row>
16487
16488 <row>
16489 <entry role="func_table_entry"><para role="func_signature">
16490 <indexterm>
16491 <primary>row_to_json</primary>
16492 </indexterm>
16493 <function>row_to_json</function> ( <type>record</type> <optional>, <type>boolean</type> </optional> )
16494 <returnvalue>json</returnvalue>
16495 </para>
16496 <para>
16497 Converts an SQL composite value to a JSON object. The behavior is the
16498 same as <function>to_json</function> except that line feeds will be
16499 added between top-level elements if the optional boolean parameter is
16500 true.
16501 </para>
16502 <para>
16503 <literal>row_to_json(row(1,'foo'))</literal>
16504 <returnvalue>{"f1":1,"f2":"foo"}</returnvalue>
16505 </para></entry>
16506 </row>
16507
16508 <row>
16509 <entry role="func_table_entry"><para role="func_signature">
16510 <indexterm>
16511 <primary>json_build_array</primary>
16512 </indexterm>
16513 <function>json_build_array</function> ( <literal>VARIADIC</literal> <type>"any"</type> )
16514 <returnvalue>json</returnvalue>
16515 </para>
16516 <para role="func_signature">
16517 <indexterm>
16518 <primary>jsonb_build_array</primary>
16519 </indexterm>
16520 <function>jsonb_build_array</function> ( <literal>VARIADIC</literal> <type>"any"</type> )
16521 <returnvalue>jsonb</returnvalue>
16522 </para>
16523 <para>
16524 Builds a possibly-heterogeneously-typed JSON array out of a variadic
16525 argument list. Each argument is converted as
16526 per <function>to_json</function> or <function>to_jsonb</function>.
16527 </para>
16528 <para>
16529 <literal>json_build_array(1, 2, 'foo', 4, 5)</literal>
16530 <returnvalue>[1, 2, "foo", 4, 5]</returnvalue>
16531 </para></entry>
16532 </row>
16533
16534 <row>
16535 <entry role="func_table_entry"><para role="func_signature">
16536 <indexterm>
16537 <primary>json_build_object</primary>
16538 </indexterm>
16539 <function>json_build_object</function> ( <literal>VARIADIC</literal> <type>"any"</type> )
16540 <returnvalue>json</returnvalue>
16541 </para>
16542 <para role="func_signature">
16543 <indexterm>
16544 <primary>jsonb_build_object</primary>
16545 </indexterm>
16546 <function>jsonb_build_object</function> ( <literal>VARIADIC</literal> <type>"any"</type> )
16547 <returnvalue>jsonb</returnvalue>
16548 </para>
16549 <para>
16550 Builds a JSON object out of a variadic argument list. By convention,
16551 the argument list consists of alternating keys and values. Key
16552 arguments are coerced to text; value arguments are converted as
16553 per <function>to_json</function> or <function>to_jsonb</function>.
16554 </para>
16555 <para>
16556 <literal>json_build_object('foo', 1, 2, row(3,'bar'))</literal>
16557 <returnvalue>{"foo" : 1, "2" : {"f1":3,"f2":"bar"}}</returnvalue>
16558 </para></entry>
16559 </row>
16560
16561 <row>
16562 <entry role="func_table_entry"><para role="func_signature">
16563 <indexterm><primary>json_object</primary></indexterm>
16564 <function>json_object</function> (
16565 <optional> { <replaceable>key_expression</replaceable> { <literal>VALUE</literal> | ':' }
16566 <replaceable>value_expression</replaceable> <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional> </optional> }<optional>, ...</optional> </optional>
16567 <optional> { <literal>NULL</literal> | <literal>ABSENT</literal> } <literal>ON NULL</literal> </optional>
16568 <optional> { <literal>WITH</literal> | <literal>WITHOUT</literal> } <literal>UNIQUE</literal> <optional> <literal>KEYS</literal> </optional> </optional>
16569 <optional> <literal>RETURNING</literal> <replaceable>data_type</replaceable> <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional> </optional> </optional>)
16570 </para>
16571 <para>
16572 Constructs a JSON object of all the key/value pairs given,
16573 or an empty object if none are given.
16574 <replaceable>key_expression</replaceable> is a scalar expression
16575 defining the <acronym>JSON</acronym> key, which is
16576 converted to the <type>text</type> type.
16577 It cannot be <literal>NULL</literal> nor can it
16578 belong to a type that has a cast to the <type>json</type> type.
16579 If <literal>WITH UNIQUE KEYS</literal> is specified, there must not
16580 be any duplicate <replaceable>key_expression</replaceable>.
16581 Any pair for which the <replaceable>value_expression</replaceable>
16582 evaluates to <literal>NULL</literal> is omitted from the output
16583 if <literal>ABSENT ON NULL</literal> is specified;
16584 if <literal>NULL ON NULL</literal> is specified or the clause
16585 omitted, the key is included with value <literal>NULL</literal>.
16586 </para>
16587 <para>
16588 <literal>json_object('code' VALUE 'P123', 'title': 'Jaws')</literal>
16589 <returnvalue>{"code" : "P123", "title" : "Jaws"}</returnvalue>
16590 </para></entry>
16591 </row>
16592
16593 <row>
16594 <entry role="func_table_entry"><para role="func_signature">
16595 <indexterm>
16596 <primary>json_object</primary>
16597 </indexterm>
16598 <function>json_object</function> ( <type>text[]</type> )
16599 <returnvalue>json</returnvalue>
16600 </para>
16601 <para role="func_signature">
16602 <indexterm>
16603 <primary>jsonb_object</primary>
16604 </indexterm>
16605 <function>jsonb_object</function> ( <type>text[]</type> )
16606 <returnvalue>jsonb</returnvalue>
16607 </para>
16608 <para>
16609 Builds a JSON object out of a text array. The array must have either
16610 exactly one dimension with an even number of members, in which case
16611 they are taken as alternating key/value pairs, or two dimensions
16612 such that each inner array has exactly two elements, which
16613 are taken as a key/value pair. All values are converted to JSON
16614 strings.
16615 </para>
16616 <para>
16617 <literal>json_object('{a, 1, b, "def", c, 3.5}')</literal>
16618 <returnvalue>{"a" : "1", "b" : "def", "c" : "3.5"}</returnvalue>
16619 </para>
16620 <para><literal>json_object('{{a, 1}, {b, "def"}, {c, 3.5}}')</literal>
16621 <returnvalue>{"a" : "1", "b" : "def", "c" : "3.5"}</returnvalue>
16622 </para></entry>
16623 </row>
16624
16625 <row>
16626 <entry role="func_table_entry"><para role="func_signature">
16627 <function>json_object</function> ( <parameter>keys</parameter> <type>text[]</type>, <parameter>values</parameter> <type>text[]</type> )
16628 <returnvalue>json</returnvalue>
16629 </para>
16630 <para role="func_signature">
16631 <function>jsonb_object</function> ( <parameter>keys</parameter> <type>text[]</type>, <parameter>values</parameter> <type>text[]</type> )
16632 <returnvalue>jsonb</returnvalue>
16633 </para>
16634 <para>
16635 This form of <function>json_object</function> takes keys and values
16636 pairwise from separate text arrays. Otherwise it is identical to
16637 the one-argument form.
16638 </para>
16639 <para>
16640 <literal>json_object('{a,b}', '{1,2}')</literal>
16641 <returnvalue>{"a": "1", "b": "2"}</returnvalue>
16642 </para></entry>
16643 </row>
16644 <row>
16645 <entry role="func_table_entry">
16646 <para role="func_signature">
16647 <indexterm><primary>json constructor</primary></indexterm>
16648 <function>json</function> (
16649 <replaceable>expression</replaceable>
16650 <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional></optional>
16651 <optional> { <literal>WITH</literal> | <literal>WITHOUT</literal> } <literal>UNIQUE</literal> <optional> <literal>KEYS</literal> </optional></optional> )
16652 <returnvalue>json</returnvalue>
16653 </para>
16654 <para>
16655 Converts a given expression specified as <type>text</type> or
16656 <type>bytea</type> string (in UTF8 encoding) into a JSON
16657 value. If <replaceable>expression</replaceable> is NULL, an
16658 <acronym>SQL</acronym> null value is returned.
16659 If <literal>WITH UNIQUE</literal> is specified, the
16660 <replaceable>expression</replaceable> must not contain any duplicate
16661 object keys.
16662 </para>
16663 <para>
16664 <literal>json('{"a":123, "b":[true,"foo"], "a":"bar"}')</literal>
16665 <returnvalue>{"a":123, "b":[true,"foo"], "a":"bar"}</returnvalue>
16666 </para>
16667 </entry>
16668 </row>
16669 <row>
16670 <entry role="func_table_entry">
16671 <para role="func_signature">
16672 <indexterm><primary>json_scalar</primary></indexterm>
16673 <function>json_scalar</function> ( <replaceable>expression</replaceable> )
16674 </para>
16675 <para>
16676 Converts a given SQL scalar value into a JSON scalar value.
16677 If the input is NULL, an <acronym>SQL</acronym> null is returned. If
16678 the input is number or a boolean value, a corresponding JSON number
16679 or boolean value is returned. For any other value, a JSON string is
16680 returned.
16681 </para>
16682 <para>
16683 <literal>json_scalar(123.45)</literal>
16684 <returnvalue>123.45</returnvalue>
16685 </para>
16686 <para>
16687 <literal>json_scalar(CURRENT_TIMESTAMP)</literal>
16688 <returnvalue>"2022-05-10T10:51:04.62128-04:00"</returnvalue>
16689 </para></entry>
16690 </row>
16691 <row>
16692 <entry role="func_table_entry">
16693 <para role="func_signature">
16694 <function>json_serialize</function> (
16695 <replaceable>expression</replaceable> <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional> </optional>
16696 <optional> <literal>RETURNING</literal> <replaceable>data_type</replaceable> <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional> </optional> </optional> )
16697 </para>
16698 <para>
16699 Converts an SQL/JSON expression into a character or binary string. The
16700 <replaceable>expression</replaceable> can be of any JSON type, any
16701 character string type, or <type>bytea</type> in UTF8 encoding.
16702 The returned type used in <literal> RETURNING</literal> can be any
16703 character string type or <type>bytea</type>. The default is
16704 <type>text</type>.
16705 </para>
16706 <para>
16707 <literal>json_serialize('{ "a" : 1 } ' RETURNING bytea)</literal>
16708 <returnvalue>\x7b20226122203a2031207d20</returnvalue>
16709 </para></entry>
16710 </row>
16711 </tbody>
16712 </tgroup>
16713 </table>
16714
16715 <para>
16716 <xref linkend="functions-sqljson-misc" /> details SQL/JSON
16717 facilities for testing JSON.
16718 </para>
16719
16720 <table id="functions-sqljson-misc">
16721 <title>SQL/JSON Testing Functions</title>
16722 <tgroup cols="1">
16723 <thead>
16724 <row>
16725 <entry role="func_table_entry"><para role="func_signature">
16726 Function signature
16727 </para>
16728 <para>
16729 Description
16730 </para>
16731 <para>
16732 Example(s)
16733 </para></entry>
16734 </row>
16735 </thead>
16736 <tbody>
16737 <row>
16738 <entry role="func_table_entry"><para role="func_signature">
16739 <indexterm><primary>IS JSON</primary></indexterm>
16740 <replaceable>expression</replaceable> <literal>IS</literal> <optional> <literal>NOT</literal> </optional> <literal>JSON</literal>
16741 <optional> { <literal>VALUE</literal> | <literal>SCALAR</literal> | <literal>ARRAY</literal> | <literal>OBJECT</literal> } </optional>
16742 <optional> { <literal>WITH</literal> | <literal>WITHOUT</literal> } <literal>UNIQUE</literal> <optional> <literal>KEYS</literal> </optional> </optional>
16743 </para>
16744 <para>
16745 This predicate tests whether <replaceable>expression</replaceable> can be
16746 parsed as JSON, possibly of a specified type.
16747 If <literal>SCALAR</literal> or <literal>ARRAY</literal> or
16748 <literal>OBJECT</literal> is specified, the
16749 test is whether or not the JSON is of that particular type. If
16750 <literal>WITH UNIQUE KEYS</literal> is specified, then any object in the
16751 <replaceable>expression</replaceable> is also tested to see if it
16752 has duplicate keys.
16753 </para>
16754 <para>
16755 <programlisting>
16756 SELECT js,
16757 js IS JSON "json?",
16758 js IS JSON SCALAR "scalar?",
16759 js IS JSON OBJECT "object?",
16760 js IS JSON ARRAY "array?"
16761 FROM (VALUES
16762 ('123'), ('"abc"'), ('{"a": "b"}'), ('[1,2]'),('abc')) foo(js);
16763 js | json? | scalar? | object? | array?
16764 ------------+-------+---------+---------+--------
16765 123 | t | t | f | f
16766 "abc" | t | t | f | f
16767 {"a": "b"} | t | f | t | f
16768 [1,2] | t | f | f | t
16769 abc | f | f | f | f
16770 </programlisting>
16771 </para>
16772 <para>
16773 <programlisting>
16774 SELECT js,
16775 js IS JSON OBJECT "object?",
16776 js IS JSON ARRAY "array?",
16777 js IS JSON ARRAY WITH UNIQUE KEYS "array w. UK?",
16778 js IS JSON ARRAY WITHOUT UNIQUE KEYS "array w/o UK?"
16779 FROM (VALUES ('[{"a":"1"},
16780 {"b":"2","b":"3"}]')) foo(js);
16781 -[ RECORD 1 ]-+--------------------
16782 js | [{"a":"1"}, +
16783 | {"b":"2","b":"3"}]
16784 object? | f
16785 array? | t
16786 array w. UK? | f
16787 array w/o UK? | t
16788 </programlisting>
16789 </para></entry>
16790 </row>
16791 </tbody>
16792 </tgroup>
16793 </table>
16794
16795 <para>
16796 <xref linkend="functions-json-processing-table"/> shows the functions that
16797 are available for processing <type>json</type> and <type>jsonb</type> values.
16798 </para>
16799
16800 <table id="functions-json-processing-table">
16801 <title>JSON Processing Functions</title>
16802 <tgroup cols="1">
16803 <thead>
16804 <row>
16805 <entry role="func_table_entry"><para role="func_signature">
16806 Function
16807 </para>
16808 <para>
16809 Description
16810 </para>
16811 <para>
16812 Example(s)
16813 </para></entry>
16814 </row>
16815 </thead>
16816
16817 <tbody>
16818 <row>
16819 <entry role="func_table_entry"><para role="func_signature">
16820 <indexterm>
16821 <primary>json_array_elements</primary>
16822 </indexterm>
16823 <function>json_array_elements</function> ( <type>json</type> )
16824 <returnvalue>setof json</returnvalue>
16825 </para>
16826 <para role="func_signature">
16827 <indexterm>
16828 <primary>jsonb_array_elements</primary>
16829 </indexterm>
16830 <function>jsonb_array_elements</function> ( <type>jsonb</type> )
16831 <returnvalue>setof jsonb</returnvalue>
16832 </para>
16833 <para>
16834 Expands the top-level JSON array into a set of JSON values.
16835 </para>
16836 <para>
16837 <literal>select * from json_array_elements('[1,true, [2,false]]')</literal>
16838 <returnvalue></returnvalue>
16839 <programlisting>
16840 value
16841 -----------
16842 1
16843 true
16844 [2,false]
16845 </programlisting>
16846 </para></entry>
16847 </row>
16848
16849 <row>
16850 <entry role="func_table_entry"><para role="func_signature">
16851 <indexterm>
16852 <primary>json_array_elements_text</primary>
16853 </indexterm>
16854 <function>json_array_elements_text</function> ( <type>json</type> )
16855 <returnvalue>setof text</returnvalue>
16856 </para>
16857 <para role="func_signature">
16858 <indexterm>
16859 <primary>jsonb_array_elements_text</primary>
16860 </indexterm>
16861 <function>jsonb_array_elements_text</function> ( <type>jsonb</type> )
16862 <returnvalue>setof text</returnvalue>
16863 </para>
16864 <para>
16865 Expands the top-level JSON array into a set of <type>text</type> values.
16866 </para>
16867 <para>
16868 <literal>select * from json_array_elements_text('["foo", "bar"]')</literal>
16869 <returnvalue></returnvalue>
16870 <programlisting>
16871 value
16872 -----------
16873 foo
16874 bar
16875 </programlisting>
16876 </para></entry>
16877 </row>
16878
16879 <row>
16880 <entry role="func_table_entry"><para role="func_signature">
16881 <indexterm>
16882 <primary>json_array_length</primary>
16883 </indexterm>
16884 <function>json_array_length</function> ( <type>json</type> )
16885 <returnvalue>integer</returnvalue>
16886 </para>
16887 <para role="func_signature">
16888 <indexterm>
16889 <primary>jsonb_array_length</primary>
16890 </indexterm>
16891 <function>jsonb_array_length</function> ( <type>jsonb</type> )
16892 <returnvalue>integer</returnvalue>
16893 </para>
16894 <para>
16895 Returns the number of elements in the top-level JSON array.
16896 </para>
16897 <para>
16898 <literal>json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]')</literal>
16899 <returnvalue>5</returnvalue>
16900 </para>
16901 <para>
16902 <literal>jsonb_array_length('[]')</literal>
16903 <returnvalue>0</returnvalue>
16904 </para></entry>
16905 </row>
16906
16907 <row>
16908 <entry role="func_table_entry"><para role="func_signature">
16909 <indexterm>
16910 <primary>json_each</primary>
16911 </indexterm>
16912 <function>json_each</function> ( <type>json</type> )
16913 <returnvalue>setof record</returnvalue>
16914 ( <parameter>key</parameter> <type>text</type>,
16915 <parameter>value</parameter> <type>json</type> )
16916 </para>
16917 <para role="func_signature">
16918 <indexterm>
16919 <primary>jsonb_each</primary>
16920 </indexterm>
16921 <function>jsonb_each</function> ( <type>jsonb</type> )
16922 <returnvalue>setof record</returnvalue>
16923 ( <parameter>key</parameter> <type>text</type>,
16924 <parameter>value</parameter> <type>jsonb</type> )
16925 </para>
16926 <para>
16927 Expands the top-level JSON object into a set of key/value pairs.
16928 </para>
16929 <para>
16930 <literal>select * from json_each('{"a":"foo", "b":"bar"}')</literal>
16931 <returnvalue></returnvalue>
16932 <programlisting>
16933 key | value
16934 -----+-------
16935 a | "foo"
16936 b | "bar"
16937 </programlisting>
16938 </para></entry>
16939 </row>
16940
16941 <row>
16942 <entry role="func_table_entry"><para role="func_signature">
16943 <indexterm>
16944 <primary>json_each_text</primary>
16945 </indexterm>
16946 <function>json_each_text</function> ( <type>json</type> )
16947 <returnvalue>setof record</returnvalue>
16948 ( <parameter>key</parameter> <type>text</type>,
16949 <parameter>value</parameter> <type>text</type> )
16950 </para>
16951 <para role="func_signature">
16952 <indexterm>
16953 <primary>jsonb_each_text</primary>
16954 </indexterm>
16955 <function>jsonb_each_text</function> ( <type>jsonb</type> )
16956 <returnvalue>setof record</returnvalue>
16957 ( <parameter>key</parameter> <type>text</type>,
16958 <parameter>value</parameter> <type>text</type> )
16959 </para>
16960 <para>
16961 Expands the top-level JSON object into a set of key/value pairs.
16962 The returned <parameter>value</parameter>s will be of
16963 type <type>text</type>.
16964 </para>
16965 <para>
16966 <literal>select * from json_each_text('{"a":"foo", "b":"bar"}')</literal>
16967 <returnvalue></returnvalue>
16968 <programlisting>
16969 key | value
16970 -----+-------
16971 a | foo
16972 b | bar
16973 </programlisting>
16974 </para></entry>
16975 </row>
16976
16977 <row>
16978 <entry role="func_table_entry"><para role="func_signature">
16979 <indexterm>
16980 <primary>json_extract_path</primary>
16981 </indexterm>
16982 <function>json_extract_path</function> ( <parameter>from_json</parameter> <type>json</type>, <literal>VARIADIC</literal> <parameter>path_elems</parameter> <type>text[]</type> )
16983 <returnvalue>json</returnvalue>
16984 </para>
16985 <para role="func_signature">
16986 <indexterm>
16987 <primary>jsonb_extract_path</primary>
16988 </indexterm>
16989 <function>jsonb_extract_path</function> ( <parameter>from_json</parameter> <type>jsonb</type>, <literal>VARIADIC</literal> <parameter>path_elems</parameter> <type>text[]</type> )
16990 <returnvalue>jsonb</returnvalue>
16991 </para>
16992 <para>
16993 Extracts JSON sub-object at the specified path.
16994 (This is functionally equivalent to the <literal>#&gt;</literal>
16995 operator, but writing the path out as a variadic list can be more
16996 convenient in some cases.)
16997 </para>
16998 <para>
16999 <literal>json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}', 'f4', 'f6')</literal>
17000 <returnvalue>"foo"</returnvalue>
17001 </para></entry>
17002 </row>
17003
17004 <row>
17005 <entry role="func_table_entry"><para role="func_signature">
17006 <indexterm>
17007 <primary>json_extract_path_text</primary>
17008 </indexterm>
17009 <function>json_extract_path_text</function> ( <parameter>from_json</parameter> <type>json</type>, <literal>VARIADIC</literal> <parameter>path_elems</parameter> <type>text[]</type> )
17010 <returnvalue>text</returnvalue>
17011 </para>
17012 <para role="func_signature">
17013 <indexterm>
17014 <primary>jsonb_extract_path_text</primary>
17015 </indexterm>
17016 <function>jsonb_extract_path_text</function> ( <parameter>from_json</parameter> <type>jsonb</type>, <literal>VARIADIC</literal> <parameter>path_elems</parameter> <type>text[]</type> )
17017 <returnvalue>text</returnvalue>
17018 </para>
17019 <para>
17020 Extracts JSON sub-object at the specified path as <type>text</type>.
17021 (This is functionally equivalent to the <literal>#&gt;&gt;</literal>
17022 operator.)
17023 </para>
17024 <para>
17025 <literal>json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}', 'f4', 'f6')</literal>
17026 <returnvalue>foo</returnvalue>
17027 </para></entry>
17028 </row>
17029
17030 <row>
17031 <entry role="func_table_entry"><para role="func_signature">
17032 <indexterm>
17033 <primary>json_object_keys</primary>
17034 </indexterm>
17035 <function>json_object_keys</function> ( <type>json</type> )
17036 <returnvalue>setof text</returnvalue>
17037 </para>
17038 <para role="func_signature">
17039 <indexterm>
17040 <primary>jsonb_object_keys</primary>
17041 </indexterm>
17042 <function>jsonb_object_keys</function> ( <type>jsonb</type> )
17043 <returnvalue>setof text</returnvalue>
17044 </para>
17045 <para>
17046 Returns the set of keys in the top-level JSON object.
17047 </para>
17048 <para>
17049 <literal>select * from json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')</literal>
17050 <returnvalue></returnvalue>
17051 <programlisting>
17052 json_object_keys
17053 ------------------
17054 f1
17055 f2
17056 </programlisting>
17057 </para></entry>
17058 </row>
17059
17060 <row>
17061 <entry role="func_table_entry"><para role="func_signature">
17062 <indexterm>
17063 <primary>json_populate_record</primary>
17064 </indexterm>
17065 <function>json_populate_record</function> ( <parameter>base</parameter> <type>anyelement</type>, <parameter>from_json</parameter> <type>json</type> )
17066 <returnvalue>anyelement</returnvalue>
17067 </para>
17068 <para role="func_signature">
17069 <indexterm>
17070 <primary>jsonb_populate_record</primary>
17071 </indexterm>
17072 <function>jsonb_populate_record</function> ( <parameter>base</parameter> <type>anyelement</type>, <parameter>from_json</parameter> <type>jsonb</type> )
17073 <returnvalue>anyelement</returnvalue>
17074 </para>
17075 <para>
17076 Expands the top-level JSON object to a row having the composite type
17077 of the <parameter>base</parameter> argument. The JSON object
17078 is scanned for fields whose names match column names of the output row
17079 type, and their values are inserted into those columns of the output.
17080 (Fields that do not correspond to any output column name are ignored.)
17081 In typical use, the value of <parameter>base</parameter> is just
17082 <literal>NULL</literal>, which means that any output columns that do
17083 not match any object field will be filled with nulls. However,
17084 if <parameter>base</parameter> isn't <literal>NULL</literal> then
17085 the values it contains will be used for unmatched columns.
17086 </para>
17087 <para>
17088 To convert a JSON value to the SQL type of an output column, the
17089 following rules are applied in sequence:
17090 <itemizedlist spacing="compact">
17091 <listitem>
17092 <para>
17093 A JSON null value is converted to an SQL null in all cases.
17094 </para>
17095 </listitem>
17096 <listitem>
17097 <para>
17098 If the output column is of type <type>json</type>
17099 or <type>jsonb</type>, the JSON value is just reproduced exactly.
17100 </para>
17101 </listitem>
17102 <listitem>
17103 <para>
17104 If the output column is a composite (row) type, and the JSON value
17105 is a JSON object, the fields of the object are converted to columns
17106 of the output row type by recursive application of these rules.
17107 </para>
17108 </listitem>
17109 <listitem>
17110 <para>
17111 Likewise, if the output column is an array type and the JSON value
17112 is a JSON array, the elements of the JSON array are converted to
17113 elements of the output array by recursive application of these
17114 rules.
17115 </para>
17116 </listitem>
17117 <listitem>
17118 <para>
17119 Otherwise, if the JSON value is a string, the contents of the
17120 string are fed to the input conversion function for the column's
17121 data type.
17122 </para>
17123 </listitem>
17124 <listitem>
17125 <para>
17126 Otherwise, the ordinary text representation of the JSON value is
17127 fed to the input conversion function for the column's data type.
17128 </para>
17129 </listitem>
17130 </itemizedlist>
17131 </para>
17132 <para>
17133 While the example below uses a constant JSON value, typical use would
17134 be to reference a <type>json</type> or <type>jsonb</type> column
17135 laterally from another table in the query's <literal>FROM</literal>
17136 clause. Writing <function>json_populate_record</function> in
17137 the <literal>FROM</literal> clause is good practice, since all of the
17138 extracted columns are available for use without duplicate function
17139 calls.
17140 </para>
17141 <para>
17142 <literal>create type subrowtype as (d int, e text);</literal>
17143 <literal>create type myrowtype as (a int, b text[], c subrowtype);</literal>
17144 </para>
17145 <para>
17146 <literal>select * from json_populate_record(null::myrowtype,
17147 '{"a": 1, "b": ["2", "a b"], "c": {"d": 4, "e": "a b c"}, "x": "foo"}')</literal>
17148 <returnvalue></returnvalue>
17149 <programlisting>
17150 a | b | c
17151 ---+-----------+-------------
17152 1 | {2,"a b"} | (4,"a b c")
17153 </programlisting>
17154 </para></entry>
17155 </row>
17156
17157 <row>
17158 <entry role="func_table_entry"><para role="func_signature">
17159 <indexterm>
17160 <primary>jsonb_populate_record_valid</primary>
17161 </indexterm>
17162 <function>jsonb_populate_record_valid</function> ( <parameter>base</parameter> <type>anyelement</type>, <parameter>from_json</parameter> <type>json</type> )
17163 <returnvalue>boolean</returnvalue>
17164 </para>
17165 <para>
17166 Function for testing <function>jsonb_populate_record</function>. Returns
17167 <literal>true</literal> if the input <function>jsonb_populate_record</function>
17168 would finish without an error for the given input JSON object; that is, it's
17169 valid input, <literal>false</literal> otherwise.
17170 </para>
17171 <para>
17172 <literal>create type jsb_char2 as (a char(2));</literal>
17173 </para>
17174 <para>
17175 <literal>select jsonb_populate_record_valid(NULL::jsb_char2, '{"a": "aaa"}');</literal>
17176 <returnvalue></returnvalue>
17177 <programlisting>
17178 jsonb_populate_record_valid
17179 -----------------------------
17180 f
17181 (1 row)
17182 </programlisting>
17183
17184 <literal>select * from jsonb_populate_record(NULL::jsb_char2, '{"a": "aaa"}') q;</literal>
17185 <returnvalue></returnvalue>
17186 <programlisting>
17187 ERROR: value too long for type character(2)
17188 </programlisting>
17189 <literal>select jsonb_populate_record_valid(NULL::jsb_char2, '{"a": "aa"}');</literal>
17190 <returnvalue></returnvalue>
17191 <programlisting>
17192 jsonb_populate_record_valid
17193 -----------------------------
17194 t
17195 (1 row)
17196 </programlisting>
17197
17198 <literal>select * from jsonb_populate_record(NULL::jsb_char2, '{"a": "aa"}') q;</literal>
17199 <returnvalue></returnvalue>
17200 <programlisting>
17201 a
17202 ----
17203 aa
17204 (1 row)
17205 </programlisting>
17206 </para></entry>
17207 </row>
17208
17209 <row>
17210 <entry role="func_table_entry"><para role="func_signature">
17211 <indexterm>
17212 <primary>json_populate_recordset</primary>
17213 </indexterm>
17214 <function>json_populate_recordset</function> ( <parameter>base</parameter> <type>anyelement</type>, <parameter>from_json</parameter> <type>json</type> )
17215 <returnvalue>setof anyelement</returnvalue>
17216 </para>
17217 <para role="func_signature">
17218 <indexterm>
17219 <primary>jsonb_populate_recordset</primary>
17220 </indexterm>
17221 <function>jsonb_populate_recordset</function> ( <parameter>base</parameter> <type>anyelement</type>, <parameter>from_json</parameter> <type>jsonb</type> )
17222 <returnvalue>setof anyelement</returnvalue>
17223 </para>
17224 <para>
17225 Expands the top-level JSON array of objects to a set of rows having
17226 the composite type of the <parameter>base</parameter> argument.
17227 Each element of the JSON array is processed as described above
17228 for <function>json[b]_populate_record</function>.
17229 </para>
17230 <para>
17231 <literal>create type twoints as (a int, b int);</literal>
17232 </para>
17233 <para>
17234 <literal>select * from json_populate_recordset(null::twoints, '[{"a":1,"b":2}, {"a":3,"b":4}]')</literal>
17235 <returnvalue></returnvalue>
17236 <programlisting>
17237 a | b
17238 ---+---
17239 1 | 2
17240 3 | 4
17241 </programlisting>
17242 </para></entry>
17243 </row>
17244
17245 <row>
17246 <entry role="func_table_entry"><para role="func_signature">
17247 <indexterm>
17248 <primary>json_to_record</primary>
17249 </indexterm>
17250 <function>json_to_record</function> ( <type>json</type> )
17251 <returnvalue>record</returnvalue>
17252 </para>
17253 <para role="func_signature">
17254 <indexterm>
17255 <primary>jsonb_to_record</primary>
17256 </indexterm>
17257 <function>jsonb_to_record</function> ( <type>jsonb</type> )
17258 <returnvalue>record</returnvalue>
17259 </para>
17260 <para>
17261 Expands the top-level JSON object to a row having the composite type
17262 defined by an <literal>AS</literal> clause. (As with all functions
17263 returning <type>record</type>, the calling query must explicitly
17264 define the structure of the record with an <literal>AS</literal>
17265 clause.) The output record is filled from fields of the JSON object,
17266 in the same way as described above
17267 for <function>json[b]_populate_record</function>. Since there is no
17268 input record value, unmatched columns are always filled with nulls.
17269 </para>
17270 <para>
17271 <literal>create type myrowtype as (a int, b text);</literal>
17272 </para>
17273 <para>
17274 <literal>select * from json_to_record('{"a":1,"b":[1,2,3],"c":[1,2,3],"e":"bar","r": {"a": 123, "b": "a b c"}}') as x(a int, b text, c int[], d text, r myrowtype)</literal>
17275 <returnvalue></returnvalue>
17276 <programlisting>
17277 a | b | c | d | r
17278 ---+---------+---------+---+---------------
17279 1 | [1,2,3] | {1,2,3} | | (123,"a b c")
17280 </programlisting>
17281 </para></entry>
17282 </row>
17283
17284 <row>
17285 <entry role="func_table_entry"><para role="func_signature">
17286 <indexterm>
17287 <primary>json_to_recordset</primary>
17288 </indexterm>
17289 <function>json_to_recordset</function> ( <type>json</type> )
17290 <returnvalue>setof record</returnvalue>
17291 </para>
17292 <para role="func_signature">
17293 <indexterm>
17294 <primary>jsonb_to_recordset</primary>
17295 </indexterm>
17296 <function>jsonb_to_recordset</function> ( <type>jsonb</type> )
17297 <returnvalue>setof record</returnvalue>
17298 </para>
17299 <para>
17300 Expands the top-level JSON array of objects to a set of rows having
17301 the composite type defined by an <literal>AS</literal> clause. (As
17302 with all functions returning <type>record</type>, the calling query
17303 must explicitly define the structure of the record with
17304 an <literal>AS</literal> clause.) Each element of the JSON array is
17305 processed as described above
17306 for <function>json[b]_populate_record</function>.
17307 </para>
17308 <para>
17309 <literal>select * from json_to_recordset('[{"a":1,"b":"foo"}, {"a":"2","c":"bar"}]') as x(a int, b text)</literal>
17310 <returnvalue></returnvalue>
17311 <programlisting>
17312 a | b
17313 ---+-----
17314 1 | foo
17315 2 |
17316 </programlisting>
17317 </para></entry>
17318 </row>
17319
17320 <row>
17321 <entry role="func_table_entry"><para role="func_signature">
17322 <indexterm>
17323 <primary>jsonb_set</primary>
17324 </indexterm>
17325 <function>jsonb_set</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>text[]</type>, <parameter>new_value</parameter> <type>jsonb</type> <optional>, <parameter>create_if_missing</parameter> <type>boolean</type> </optional> )
17326 <returnvalue>jsonb</returnvalue>
17327 </para>
17328 <para>
17329 Returns <parameter>target</parameter>
17330 with the item designated by <parameter>path</parameter>
17331 replaced by <parameter>new_value</parameter>, or with
17332 <parameter>new_value</parameter> added if
17333 <parameter>create_if_missing</parameter> is true (which is the
17334 default) and the item designated by <parameter>path</parameter>
17335 does not exist.
17336 All earlier steps in the path must exist, or
17337 the <parameter>target</parameter> is returned unchanged.
17338 As with the path oriented operators, negative integers that
17339 appear in the <parameter>path</parameter> count from the end
17340 of JSON arrays.
17341 If the last path step is an array index that is out of range,
17342 and <parameter>create_if_missing</parameter> is true, the new
17343 value is added at the beginning of the array if the index is negative,
17344 or at the end of the array if it is positive.
17345 </para>
17346 <para>
17347 <literal>jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}', '[2,3,4]', false)</literal>
17348 <returnvalue>[{"f1": [2, 3, 4], "f2": null}, 2, null, 3]</returnvalue>
17349 </para>
17350 <para>
17351 <literal>jsonb_set('[{"f1":1,"f2":null},2]', '{0,f3}', '[2,3,4]')</literal>
17352 <returnvalue>[{"f1": 1, "f2": null, "f3": [2, 3, 4]}, 2]</returnvalue>
17353 </para></entry>
17354 </row>
17355
17356 <row>
17357 <entry role="func_table_entry"><para role="func_signature">
17358 <indexterm>
17359 <primary>jsonb_set_lax</primary>
17360 </indexterm>
17361 <function>jsonb_set_lax</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>text[]</type>, <parameter>new_value</parameter> <type>jsonb</type> <optional>, <parameter>create_if_missing</parameter> <type>boolean</type> <optional>, <parameter>null_value_treatment</parameter> <type>text</type> </optional></optional> )
17362 <returnvalue>jsonb</returnvalue>
17363 </para>
17364 <para>
17365 If <parameter>new_value</parameter> is not <literal>NULL</literal>,
17366 behaves identically to <literal>jsonb_set</literal>. Otherwise behaves
17367 according to the value
17368 of <parameter>null_value_treatment</parameter> which must be one
17369 of <literal>'raise_exception'</literal>,
17370 <literal>'use_json_null'</literal>, <literal>'delete_key'</literal>, or
17371 <literal>'return_target'</literal>. The default is
17372 <literal>'use_json_null'</literal>.
17373 </para>
17374 <para>
17375 <literal>jsonb_set_lax('[{"f1":1,"f2":null},2,null,3]', '{0,f1}', null)</literal>
17376 <returnvalue>[{"f1": null, "f2": null}, 2, null, 3]</returnvalue>
17377 </para>
17378 <para>
17379 <literal>jsonb_set_lax('[{"f1":99,"f2":null},2]', '{0,f3}', null, true, 'return_target')</literal>
17380 <returnvalue>[{"f1": 99, "f2": null}, 2]</returnvalue>
17381 </para></entry>
17382 </row>
17383
17384 <row>
17385 <entry role="func_table_entry"><para role="func_signature">
17386 <indexterm>
17387 <primary>jsonb_insert</primary>
17388 </indexterm>
17389 <function>jsonb_insert</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>text[]</type>, <parameter>new_value</parameter> <type>jsonb</type> <optional>, <parameter>insert_after</parameter> <type>boolean</type> </optional> )
17390 <returnvalue>jsonb</returnvalue>
17391 </para>
17392 <para>
17393 Returns <parameter>target</parameter>
17394 with <parameter>new_value</parameter> inserted. If the item
17395 designated by the <parameter>path</parameter> is an array
17396 element, <parameter>new_value</parameter> will be inserted before
17397 that item if <parameter>insert_after</parameter> is false (which
17398 is the default), or after it
17399 if <parameter>insert_after</parameter> is true. If the item
17400 designated by the <parameter>path</parameter> is an object
17401 field, <parameter>new_value</parameter> will be inserted only if
17402 the object does not already contain that key.
17403 All earlier steps in the path must exist, or
17404 the <parameter>target</parameter> is returned unchanged.
17405 As with the path oriented operators, negative integers that
17406 appear in the <parameter>path</parameter> count from the end
17407 of JSON arrays.
17408 If the last path step is an array index that is out of range, the new
17409 value is added at the beginning of the array if the index is negative,
17410 or at the end of the array if it is positive.
17411 </para>
17412 <para>
17413 <literal>jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"')</literal>
17414 <returnvalue>{"a": [0, "new_value", 1, 2]}</returnvalue>
17415 </para>
17416 <para>
17417 <literal>jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"', true)</literal>
17418 <returnvalue>{"a": [0, 1, "new_value", 2]}</returnvalue>
17419 </para></entry>
17420 </row>
17421
17422 <row>
17423 <entry role="func_table_entry"><para role="func_signature">
17424 <indexterm>
17425 <primary>json_strip_nulls</primary>
17426 </indexterm>
17427 <function>json_strip_nulls</function> ( <parameter>target</parameter> <type>json</type> <optional>,<parameter>strip_in_arrays</parameter> <type>boolean</type> </optional> )
17428 <returnvalue>json</returnvalue>
17429 </para>
17430 <para role="func_signature">
17431 <indexterm>
17432 <primary>jsonb_strip_nulls</primary>
17433 </indexterm>
17434 <function>jsonb_strip_nulls</function> ( <parameter>target</parameter> <type>jsonb</type> <optional>,<parameter>strip_in_arrays</parameter> <type>boolean</type> </optional> )
17435 <returnvalue>jsonb</returnvalue>
17436 </para>
17437 <para>
17438 Deletes all object fields that have null values from the given JSON
17439 value, recursively.
17440 If <parameter>strip_in_arrays</parameter> is true (the default is false),
17441 null array elements are also stripped.
17442 Otherwise they are not stripped. Bare null values are never stripped.
17443 </para>
17444 <para>
17445 <literal>json_strip_nulls('[{"f1":1, "f2":null}, 2, null, 3]')</literal>
17446 <returnvalue>[{"f1":1},2,null,3]</returnvalue>
17447 </para>
17448 <para>
17449 <literal>jsonb_strip_nulls('[1,2,null,3,4]', true)</literal>
17450 <returnvalue>[1,2,3,4]</returnvalue>
17451 </para>
17452 </entry>
17453 </row>
17454
17455 <row>
17456 <entry role="func_table_entry"><para role="func_signature">
17457 <indexterm>
17458 <primary>jsonb_path_exists</primary>
17459 </indexterm>
17460 <function>jsonb_path_exists</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17461 <returnvalue>boolean</returnvalue>
17462 </para>
17463 <para>
17464 Checks whether the JSON path returns any item for the specified JSON
17465 value.
17466 (This is useful only with SQL-standard JSON path expressions, not
17467 <link linkend="functions-sqljson-check-expressions">predicate check
17468 expressions</link>, since those always return a value.)
17469 If the <parameter>vars</parameter> argument is specified, it must
17470 be a JSON object, and its fields provide named values to be
17471 substituted into the <type>jsonpath</type> expression.
17472 If the <parameter>silent</parameter> argument is specified and
17473 is <literal>true</literal>, the function suppresses the same errors
17474 as the <literal>@?</literal> and <literal>@@</literal> operators do.
17475 </para>
17476 <para>
17477 <literal>jsonb_path_exists('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max)', '{"min":2, "max":4}')</literal>
17478 <returnvalue>t</returnvalue>
17479 </para></entry>
17480 </row>
17481
17482 <row>
17483 <entry role="func_table_entry"><para role="func_signature">
17484 <indexterm>
17485 <primary>jsonb_path_match</primary>
17486 </indexterm>
17487 <function>jsonb_path_match</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17488 <returnvalue>boolean</returnvalue>
17489 </para>
17490 <para>
17491 Returns the SQL boolean result of a JSON path predicate check
17492 for the specified JSON value.
17493 (This is useful only
17494 with <link linkend="functions-sqljson-check-expressions">predicate
17495 check expressions</link>, not SQL-standard JSON path expressions,
17496 since it will either fail or return <literal>NULL</literal> if the
17497 path result is not a single boolean value.)
17498 The optional <parameter>vars</parameter>
17499 and <parameter>silent</parameter> arguments act the same as
17500 for <function>jsonb_path_exists</function>.
17501 </para>
17502 <para>
17503 <literal>jsonb_path_match('{"a":[1,2,3,4,5]}', 'exists($.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max))', '{"min":2, "max":4}')</literal>
17504 <returnvalue>t</returnvalue>
17505 </para></entry>
17506 </row>
17507
17508 <row>
17509 <entry role="func_table_entry"><para role="func_signature">
17510 <indexterm>
17511 <primary>jsonb_path_query</primary>
17512 </indexterm>
17513 <function>jsonb_path_query</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17514 <returnvalue>setof jsonb</returnvalue>
17515 </para>
17516 <para>
17517 Returns all JSON items returned by the JSON path for the specified
17518 JSON value.
17519 For SQL-standard JSON path expressions it returns the JSON
17520 values selected from <parameter>target</parameter>.
17521 For <link linkend="functions-sqljson-check-expressions">predicate
17522 check expressions</link> it returns the result of the predicate
17523 check: <literal>true</literal>, <literal>false</literal>,
17524 or <literal>null</literal>.
17525 The optional <parameter>vars</parameter>
17526 and <parameter>silent</parameter> arguments act the same as
17527 for <function>jsonb_path_exists</function>.
17528 </para>
17529 <para>
17530 <literal>select * from jsonb_path_query('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max)', '{"min":2, "max":4}')</literal>
17531 <returnvalue></returnvalue>
17532 <programlisting>
17533 jsonb_path_query
17534 ------------------
17535 2
17536 3
17537 4
17538 </programlisting>
17539 </para></entry>
17540 </row>
17541
17542 <row>
17543 <entry role="func_table_entry"><para role="func_signature">
17544 <indexterm>
17545 <primary>jsonb_path_query_array</primary>
17546 </indexterm>
17547 <function>jsonb_path_query_array</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17548 <returnvalue>jsonb</returnvalue>
17549 </para>
17550 <para>
17551 Returns all JSON items returned by the JSON path for the specified
17552 JSON value, as a JSON array.
17553 The parameters are the same as
17554 for <function>jsonb_path_query</function>.
17555 </para>
17556 <para>
17557 <literal>jsonb_path_query_array('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max)', '{"min":2, "max":4}')</literal>
17558 <returnvalue>[2, 3, 4]</returnvalue>
17559 </para></entry>
17560 </row>
17561
17562 <row>
17563 <entry role="func_table_entry"><para role="func_signature">
17564 <indexterm>
17565 <primary>jsonb_path_query_first</primary>
17566 </indexterm>
17567 <function>jsonb_path_query_first</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17568 <returnvalue>jsonb</returnvalue>
17569 </para>
17570 <para>
17571 Returns the first JSON item returned by the JSON path for the
17572 specified JSON value, or <literal>NULL</literal> if there are no
17573 results.
17574 The parameters are the same as
17575 for <function>jsonb_path_query</function>.
17576 </para>
17577 <para>
17578 <literal>jsonb_path_query_first('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max)', '{"min":2, "max":4}')</literal>
17579 <returnvalue>2</returnvalue>
17580 </para></entry>
17581 </row>
17582
17583 <row>
17584 <entry role="func_table_entry"><para role="func_signature">
17585 <indexterm>
17586 <primary>jsonb_path_exists_tz</primary>
17587 </indexterm>
17588 <function>jsonb_path_exists_tz</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17589 <returnvalue>boolean</returnvalue>
17590 </para>
17591 <para role="func_signature">
17592 <indexterm>
17593 <primary>jsonb_path_match_tz</primary>
17594 </indexterm>
17595 <function>jsonb_path_match_tz</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17596 <returnvalue>boolean</returnvalue>
17597 </para>
17598 <para role="func_signature">
17599 <indexterm>
17600 <primary>jsonb_path_query_tz</primary>
17601 </indexterm>
17602 <function>jsonb_path_query_tz</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17603 <returnvalue>setof jsonb</returnvalue>
17604 </para>
17605 <para role="func_signature">
17606 <indexterm>
17607 <primary>jsonb_path_query_array_tz</primary>
17608 </indexterm>
17609 <function>jsonb_path_query_array_tz</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17610 <returnvalue>jsonb</returnvalue>
17611 </para>
17612 <para role="func_signature">
17613 <indexterm>
17614 <primary>jsonb_path_query_first_tz</primary>
17615 </indexterm>
17616 <function>jsonb_path_query_first_tz</function> ( <parameter>target</parameter> <type>jsonb</type>, <parameter>path</parameter> <type>jsonpath</type> <optional>, <parameter>vars</parameter> <type>jsonb</type> <optional>, <parameter>silent</parameter> <type>boolean</type> </optional></optional> )
17617 <returnvalue>jsonb</returnvalue>
17618 </para>
17619 <para>
17620 These functions act like their counterparts described above without
17621 the <literal>_tz</literal> suffix, except that these functions support
17622 comparisons of date/time values that require timezone-aware
17623 conversions. The example below requires interpretation of the
17624 date-only value <literal>2015-08-02</literal> as a timestamp with time
17625 zone, so the result depends on the current
17626 <xref linkend="guc-timezone"/> setting. Due to this dependency, these
17627 functions are marked as stable, which means these functions cannot be
17628 used in indexes. Their counterparts are immutable, and so can be used
17629 in indexes; but they will throw errors if asked to make such
17630 comparisons.
17631 </para>
17632 <para>
17633 <literal>jsonb_path_exists_tz('["2015-08-01 12:00:00-05"]', '$[*] ? (@.datetime() &lt; "2015-08-02".datetime())')</literal>
17634 <returnvalue>t</returnvalue>
17635 </para></entry>
17636 </row>
17637
17638 <row>
17639 <entry role="func_table_entry"><para role="func_signature">
17640 <indexterm>
17641 <primary>jsonb_pretty</primary>
17642 </indexterm>
17643 <function>jsonb_pretty</function> ( <type>jsonb</type> )
17644 <returnvalue>text</returnvalue>
17645 </para>
17646 <para>
17647 Converts the given JSON value to pretty-printed, indented text.
17648 </para>
17649 <para>
17650 <literal>jsonb_pretty('[{"f1":1,"f2":null}, 2]')</literal>
17651 <returnvalue></returnvalue>
17652 <programlisting>
17653 [
17654 {
17655 "f1": 1,
17656 "f2": null
17657 },
17658 2
17659 ]
17660 </programlisting>
17661 </para></entry>
17662 </row>
17663
17664 <row>
17665 <entry role="func_table_entry"><para role="func_signature">
17666 <indexterm>
17667 <primary>json_typeof</primary>
17668 </indexterm>
17669 <function>json_typeof</function> ( <type>json</type> )
17670 <returnvalue>text</returnvalue>
17671 </para>
17672 <para role="func_signature">
17673 <indexterm>
17674 <primary>jsonb_typeof</primary>
17675 </indexterm>
17676 <function>jsonb_typeof</function> ( <type>jsonb</type> )
17677 <returnvalue>text</returnvalue>
17678 </para>
17679 <para>
17680 Returns the type of the top-level JSON value as a text string.
17681 Possible types are
17682 <literal>object</literal>, <literal>array</literal>,
17683 <literal>string</literal>, <literal>number</literal>,
17684 <literal>boolean</literal>, and <literal>null</literal>.
17685 (The <literal>null</literal> result should not be confused
17686 with an SQL NULL; see the examples.)
17687 </para>
17688 <para>
17689 <literal>json_typeof('-123.4')</literal>
17690 <returnvalue>number</returnvalue>
17691 </para>
17692 <para>
17693 <literal>json_typeof('null'::json)</literal>
17694 <returnvalue>null</returnvalue>
17695 </para>
17696 <para>
17697 <literal>json_typeof(NULL::json) IS NULL</literal>
17698 <returnvalue>t</returnvalue>
17699 </para></entry>
17700 </row>
17701 </tbody>
17702 </tgroup>
17703 </table>
17704 </sect2>
17705
17706 <sect2 id="functions-sqljson-path">
17707 <title>The SQL/JSON Path Language</title>
17708
17709 <indexterm zone="functions-sqljson-path">
17710 <primary>SQL/JSON path language</primary>
17711 </indexterm>
17712
17713 <para>
17714 SQL/JSON path expressions specify item(s) to be retrieved
17715 from a JSON value, similarly to XPath expressions used
17716 for access to XML content. In <productname>PostgreSQL</productname>,
17717 path expressions are implemented as the <type>jsonpath</type>
17718 data type and can use any elements described in
17719 <xref linkend="datatype-jsonpath"/>.
17720 </para>
17721
17722 <para>
17723 JSON query functions and operators
17724 pass the provided path expression to the <firstterm>path engine</firstterm>
17725 for evaluation. If the expression matches the queried JSON data,
17726 the corresponding JSON item, or set of items, is returned.
17727 If there is no match, the result will be <literal>NULL</literal>,
17728 <literal>false</literal>, or an error, depending on the function.
17729 Path expressions are written in the SQL/JSON path language
17730 and can include arithmetic expressions and functions.
17731 </para>
17732
17733 <para>
17734 A path expression consists of a sequence of elements allowed
17735 by the <type>jsonpath</type> data type.
17736 The path expression is normally evaluated from left to right, but
17737 you can use parentheses to change the order of operations.
17738 If the evaluation is successful, a sequence of JSON items is produced,
17739 and the evaluation result is returned to the JSON query function
17740 that completes the specified computation.
17741 </para>
17742
17743 <para>
17744 To refer to the JSON value being queried (the
17745 <firstterm>context item</firstterm>), use the <literal>$</literal> variable
17746 in the path expression. The first element of a path must always
17747 be <literal>$</literal>. It can be followed by one or more
17748 <link linkend="type-jsonpath-accessors">accessor operators</link>,
17749 which go down the JSON structure level by level to retrieve sub-items
17750 of the context item. Each accessor operator acts on the
17751 result(s) of the previous evaluation step, producing zero, one, or more
17752 output items from each input item.
17753 </para>
17754
17755 <para>
17756 For example, suppose you have some JSON data from a GPS tracker that you
17757 would like to parse, such as:
17758 <programlisting>
17759 SELECT '{
17760 "track": {
17761 "segments": [
17762 {
17763 "location": [ 47.763, 13.4034 ],
17764 "start time": "2018-10-14 10:05:14",
17765 "HR": 73
17766 },
17767 {
17768 "location": [ 47.706, 13.2635 ],
17769 "start time": "2018-10-14 10:39:21",
17770 "HR": 135
17771 }
17772 ]
17773 }
17774 }' AS json \gset
17775 </programlisting>
17776 (The above example can be copied-and-pasted
17777 into <application>psql</application> to set things up for the following
17778 examples. Then <application>psql</application> will
17779 expand <literal>:'json'</literal> into a suitably-quoted string
17780 constant containing the JSON value.)
17781 </para>
17782
17783 <para>
17784 To retrieve the available track segments, you need to use the
17785 <literal>.<replaceable>key</replaceable></literal> accessor
17786 operator to descend through surrounding JSON objects, for example:
17787 <screen>
17788 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments');</userinput>
17789 jsonb_path_query
17790 -----------------------------------------------------------&zwsp;-----------------------------------------------------------&zwsp;---------------------------------------------
17791 [{"HR": 73, "location": [47.763, 13.4034], "start time": "2018-10-14 10:05:14"}, {"HR": 135, "location": [47.706, 13.2635], "start time": "2018-10-14 10:39:21"}]
17792 </screen>
17793 </para>
17794
17795 <para>
17796 To retrieve the contents of an array, you typically use the
17797 <literal>[*]</literal> operator.
17798 The following example will return the location coordinates for all
17799 the available track segments:
17800 <screen>
17801 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments[*].location');</userinput>
17802 jsonb_path_query
17803 -------------------
17804 [47.763, 13.4034]
17805 [47.706, 13.2635]
17806 </screen>
17807 Here we started with the whole JSON input value (<literal>$</literal>),
17808 then the <literal>.track</literal> accessor selected the JSON object
17809 associated with the <literal>"track"</literal> object key, then
17810 the <literal>.segments</literal> accessor selected the JSON array
17811 associated with the <literal>"segments"</literal> key within that
17812 object, then the <literal>[*]</literal> accessor selected each element
17813 of that array (producing a series of items), then
17814 the <literal>.location</literal> accessor selected the JSON array
17815 associated with the <literal>"location"</literal> key within each of
17816 those objects. In this example, each of those objects had
17817 a <literal>"location"</literal> key; but if any of them did not,
17818 the <literal>.location</literal> accessor would have simply produced no
17819 output for that input item.
17820 </para>
17821
17822 <para>
17823 To return the coordinates of the first segment only, you can
17824 specify the corresponding subscript in the <literal>[]</literal>
17825 accessor operator. Recall that JSON array indexes are 0-relative:
17826 <screen>
17827 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments[0].location');</userinput>
17828 jsonb_path_query
17829 -------------------
17830 [47.763, 13.4034]
17831 </screen>
17832 </para>
17833
17834 <para>
17835 The result of each path evaluation step can be processed
17836 by one or more of the <type>jsonpath</type> operators and methods
17837 listed in <xref linkend="functions-sqljson-path-operators"/>.
17838 Each method name must be preceded by a dot. For example,
17839 you can get the size of an array:
17840 <screen>
17841 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments.size()');</userinput>
17842 jsonb_path_query
17843 ------------------
17844 2
17845 </screen>
17846 More examples of using <type>jsonpath</type> operators
17847 and methods within path expressions appear below in
17848 <xref linkend="functions-sqljson-path-operators"/>.
17849 </para>
17850
17851 <para>
17852 A path can also contain
17853 <firstterm>filter expressions</firstterm> that work similarly to the
17854 <literal>WHERE</literal> clause in SQL. A filter expression begins with
17855 a question mark and provides a condition in parentheses:
17856
17857 <synopsis>
17858 ? (<replaceable>condition</replaceable>)
17859 </synopsis>
17860 </para>
17861
17862 <para>
17863 Filter expressions must be written just after the path evaluation step
17864 to which they should apply. The result of that step is filtered to include
17865 only those items that satisfy the provided condition. SQL/JSON defines
17866 three-valued logic, so the condition can
17867 produce <literal>true</literal>, <literal>false</literal>,
17868 or <literal>unknown</literal>. The <literal>unknown</literal> value
17869 plays the same role as SQL <literal>NULL</literal> and can be tested
17870 for with the <literal>is unknown</literal> predicate. Further path
17871 evaluation steps use only those items for which the filter expression
17872 returned <literal>true</literal>.
17873 </para>
17874
17875 <para>
17876 The functions and operators that can be used in filter expressions are
17877 listed in <xref linkend="functions-sqljson-filter-ex-table"/>. Within a
17878 filter expression, the <literal>@</literal> variable denotes the value
17879 being considered (i.e., one result of the preceding path step). You can
17880 write accessor operators after <literal>@</literal> to retrieve component
17881 items.
17882 </para>
17883
17884 <para>
17885 For example, suppose you would like to retrieve all heart rate values higher
17886 than 130. You can achieve this as follows:
17887 <screen>
17888 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments[*].HR ? (@ &gt; 130)');</userinput>
17889 jsonb_path_query
17890 ------------------
17891 135
17892 </screen>
17893 </para>
17894
17895 <para>
17896 To get the start times of segments with such values, you have to
17897 filter out irrelevant segments before selecting the start times, so the
17898 filter expression is applied to the previous step, and the path used
17899 in the condition is different:
17900 <screen>
17901 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments[*] ? (@.HR &gt; 130)."start time"');</userinput>
17902 jsonb_path_query
17903 -----------------------
17904 "2018-10-14 10:39:21"
17905 </screen>
17906 </para>
17907
17908 <para>
17909 You can use several filter expressions in sequence, if required.
17910 The following example selects start times of all segments that
17911 contain locations with relevant coordinates and high heart rate values:
17912 <screen>
17913 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments[*] ? (@.location[1] &lt; 13.4) ? (@.HR &gt; 130)."start time"');</userinput>
17914 jsonb_path_query
17915 -----------------------
17916 "2018-10-14 10:39:21"
17917 </screen>
17918 </para>
17919
17920 <para>
17921 Using filter expressions at different nesting levels is also allowed.
17922 The following example first filters all segments by location, and then
17923 returns high heart rate values for these segments, if available:
17924 <screen>
17925 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments[*] ? (@.location[1] &lt; 13.4).HR ? (@ &gt; 130)');</userinput>
17926 jsonb_path_query
17927 ------------------
17928 135
17929 </screen>
17930 </para>
17931
17932 <para>
17933 You can also nest filter expressions within each other.
17934 This example returns the size of the track if it contains any
17935 segments with high heart rate values, or an empty sequence otherwise:
17936 <screen>
17937 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track ? (exists(@.segments[*] ? (@.HR &gt; 130))).segments.size()');</userinput>
17938 jsonb_path_query
17939 ------------------
17940 2
17941 </screen>
17942 </para>
17943
17944 <sect3 id="functions-sqljson-deviations">
17945 <title>Deviations from the SQL Standard</title>
17946 <para>
17947 <productname>PostgreSQL</productname>'s implementation of the SQL/JSON path
17948 language has the following deviations from the SQL/JSON standard.
17949 </para>
17950
17951 <sect4 id="functions-sqljson-check-expressions">
17952 <title>Boolean Predicate Check Expressions</title>
17953 <para>
17954 As an extension to the SQL standard,
17955 a <productname>PostgreSQL</productname> path expression can be a
17956 Boolean predicate, whereas the SQL standard allows predicates only within
17957 filters. While SQL-standard path expressions return the relevant
17958 element(s) of the queried JSON value, predicate check expressions
17959 return the single three-valued <type>jsonb</type> result of the
17960 predicate: <literal>true</literal>,
17961 <literal>false</literal>, or <literal>null</literal>.
17962 For example, we could write this SQL-standard filter expression:
17963 <screen>
17964 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments ?(@[*].HR &gt; 130)');</userinput>
17965 jsonb_path_query
17966 -----------------------------------------------------------&zwsp;----------------------
17967 {"HR": 135, "location": [47.706, 13.2635], "start time": "2018-10-14 10:39:21"}
17968 </screen>
17969 The similar predicate check expression simply
17970 returns <literal>true</literal>, indicating that a match exists:
17971 <screen>
17972 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', '$.track.segments[*].HR &gt; 130');</userinput>
17973 jsonb_path_query
17974 ------------------
17975 true
17976 </screen>
17977 </para>
17978
17979 <note>
17980 <para>
17981 Predicate check expressions are required in the
17982 <literal>@@</literal> operator (and the
17983 <function>jsonb_path_match</function> function), and should not be used
17984 with the <literal>@?</literal> operator (or the
17985 <function>jsonb_path_exists</function> function).
17986 </para>
17987 </note>
17988 </sect4>
17989
17990 <sect4 id="functions-sqljson-regular-expression-deviation">
17991 <title>Regular Expression Interpretation</title>
17992 <para>
17993 There are minor differences in the interpretation of regular
17994 expression patterns used in <literal>like_regex</literal> filters, as
17995 described in <xref linkend="jsonpath-regular-expressions"/>.
17996 </para>
17997 </sect4>
17998 </sect3>
17999
18000 <sect3 id="functions-sqljson-strict-and-lax-modes">
18001 <title>Strict and Lax Modes</title>
18002 <para>
18003 When you query JSON data, the path expression may not match the
18004 actual JSON data structure. An attempt to access a non-existent
18005 member of an object or element of an array is defined as a
18006 structural error. SQL/JSON path expressions have two modes
18007 of handling structural errors:
18008 </para>
18009
18010 <itemizedlist>
18011 <listitem>
18012 <para>
18013 lax (default) &mdash; the path engine implicitly adapts
18014 the queried data to the specified path.
18015 Any structural errors that cannot be fixed as described below
18016 are suppressed, producing no match.
18017 </para>
18018 </listitem>
18019 <listitem>
18020 <para>
18021 strict &mdash; if a structural error occurs, an error is raised.
18022 </para>
18023 </listitem>
18024 </itemizedlist>
18025
18026 <para>
18027 Lax mode facilitates matching of a JSON document and path
18028 expression when the JSON data does not conform to the expected schema.
18029 If an operand does not match the requirements of a particular operation,
18030 it can be automatically wrapped as an SQL/JSON array, or unwrapped by
18031 converting its elements into an SQL/JSON sequence before performing
18032 the operation. Also, comparison operators automatically unwrap their
18033 operands in lax mode, so you can compare SQL/JSON arrays
18034 out-of-the-box. An array of size 1 is considered equal to its sole element.
18035 Automatic unwrapping is not performed when:
18036 <itemizedlist>
18037 <listitem>
18038 <para>
18039 The path expression contains <literal>type()</literal> or
18040 <literal>size()</literal> methods that return the type
18041 and the number of elements in the array, respectively.
18042 </para>
18043 </listitem>
18044 <listitem>
18045 <para>
18046 The queried JSON data contain nested arrays. In this case, only
18047 the outermost array is unwrapped, while all the inner arrays
18048 remain unchanged. Thus, implicit unwrapping can only go one
18049 level down within each path evaluation step.
18050 </para>
18051 </listitem>
18052 </itemizedlist>
18053 </para>
18054
18055 <para>
18056 For example, when querying the GPS data listed above, you can
18057 abstract from the fact that it stores an array of segments
18058 when using lax mode:
18059 <screen>
18060 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', 'lax $.track.segments.location');</userinput>
18061 jsonb_path_query
18062 -------------------
18063 [47.763, 13.4034]
18064 [47.706, 13.2635]
18065 </screen>
18066 </para>
18067
18068 <para>
18069 In strict mode, the specified path must exactly match the structure of
18070 the queried JSON document, so using this path
18071 expression will cause an error:
18072 <screen>
18073 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', 'strict $.track.segments.location');</userinput>
18074 ERROR: jsonpath member accessor can only be applied to an object
18075 </screen>
18076 To get the same result as in lax mode, you have to explicitly unwrap the
18077 <literal>segments</literal> array:
18078 <screen>
18079 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', 'strict $.track.segments[*].location');</userinput>
18080 jsonb_path_query
18081 -------------------
18082 [47.763, 13.4034]
18083 [47.706, 13.2635]
18084 </screen>
18085 </para>
18086
18087 <para>
18088 The unwrapping behavior of lax mode can lead to surprising results. For
18089 instance, the following query using the <literal>.**</literal> accessor
18090 selects every <literal>HR</literal> value twice:
18091 <screen>
18092 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', 'lax $.**.HR');</userinput>
18093 jsonb_path_query
18094 ------------------
18095 73
18096 135
18097 73
18098 135
18099 </screen>
18100 This happens because the <literal>.**</literal> accessor selects both
18101 the <literal>segments</literal> array and each of its elements, while
18102 the <literal>.HR</literal> accessor automatically unwraps arrays when
18103 using lax mode. To avoid surprising results, we recommend using
18104 the <literal>.**</literal> accessor only in strict mode. The
18105 following query selects each <literal>HR</literal> value just once:
18106 <screen>
18107 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', 'strict $.**.HR');</userinput>
18108 jsonb_path_query
18109 ------------------
18110 73
18111 135
18112 </screen>
18113 </para>
18114
18115 <para>
18116 The unwrapping of arrays can also lead to unexpected results. Consider this
18117 example, which selects all the <literal>location</literal> arrays:
18118 <screen>
18119 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', 'lax $.track.segments[*].location');</userinput>
18120 jsonb_path_query
18121 -------------------
18122 [47.763, 13.4034]
18123 [47.706, 13.2635]
18124 (2 rows)
18125 </screen>
18126 As expected it returns the full arrays. But applying a filter expression
18127 causes the arrays to be unwrapped to evaluate each item, returning only the
18128 items that match the expression:
18129 <screen>
18130 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', 'lax $.track.segments[*].location ?(@[*] &gt; 15)');</userinput>
18131 jsonb_path_query
18132 ------------------
18133 47.763
18134 47.706
18135 (2 rows)
18136 </screen>
18137 This despite the fact that the full arrays are selected by the path
18138 expression. Use strict mode to restore selecting the arrays:
18139 <screen>
18140 <prompt>=&gt;</prompt> <userinput>select jsonb_path_query(:'json', 'strict $.track.segments[*].location ?(@[*] &gt; 15)');</userinput>
18141 jsonb_path_query
18142 -------------------
18143 [47.763, 13.4034]
18144 [47.706, 13.2635]
18145 (2 rows)
18146 </screen>
18147 </para>
18148 </sect3>
18149
18150 <sect3 id="functions-sqljson-path-operators">
18151 <title>SQL/JSON Path Operators and Methods</title>
18152
18153 <para>
18154 <xref linkend="functions-sqljson-op-table"/> shows the operators and
18155 methods available in <type>jsonpath</type>. Note that while the unary
18156 operators and methods can be applied to multiple values resulting from a
18157 preceding path step, the binary operators (addition etc.) can only be
18158 applied to single values. In lax mode, methods applied to an array will be
18159 executed for each value in the array. The exceptions are
18160 <literal>.type()</literal> and <literal>.size()</literal>, which apply to
18161 the array itself.
18162 </para>
18163
18164 <table id="functions-sqljson-op-table">
18165 <title><type>jsonpath</type> Operators and Methods</title>
18166 <tgroup cols="1">
18167 <thead>
18168 <row>
18169 <entry role="func_table_entry"><para role="func_signature">
18170 Operator/Method
18171 </para>
18172 <para>
18173 Description
18174 </para>
18175 <para>
18176 Example(s)
18177 </para></entry>
18178 </row>
18179 </thead>
18180
18181 <tbody>
18182 <row>
18183 <entry role="func_table_entry"><para role="func_signature">
18184 <replaceable>number</replaceable> <literal>+</literal> <replaceable>number</replaceable>
18185 <returnvalue><replaceable>number</replaceable></returnvalue>
18186 </para>
18187 <para>
18188 Addition
18189 </para>
18190 <para>
18191 <literal>jsonb_path_query('[2]', '$[0] + 3')</literal>
18192 <returnvalue>5</returnvalue>
18193 </para></entry>
18194 </row>
18195
18196 <row>
18197 <entry role="func_table_entry"><para role="func_signature">
18198 <literal>+</literal> <replaceable>number</replaceable>
18199 <returnvalue><replaceable>number</replaceable></returnvalue>
18200 </para>
18201 <para>
18202 Unary plus (no operation); unlike addition, this can iterate over
18203 multiple values
18204 </para>
18205 <para>
18206 <literal>jsonb_path_query_array('{"x": [2,3,4]}', '+ $.x')</literal>
18207 <returnvalue>[2, 3, 4]</returnvalue>
18208 </para></entry>
18209 </row>
18210
18211 <row>
18212 <entry role="func_table_entry"><para role="func_signature">
18213 <replaceable>number</replaceable> <literal>-</literal> <replaceable>number</replaceable>
18214 <returnvalue><replaceable>number</replaceable></returnvalue>
18215 </para>
18216 <para>
18217 Subtraction
18218 </para>
18219 <para>
18220 <literal>jsonb_path_query('[2]', '7 - $[0]')</literal>
18221 <returnvalue>5</returnvalue>
18222 </para></entry>
18223 </row>
18224
18225 <row>
18226 <entry role="func_table_entry"><para role="func_signature">
18227 <literal>-</literal> <replaceable>number</replaceable>
18228 <returnvalue><replaceable>number</replaceable></returnvalue>
18229 </para>
18230 <para>
18231 Negation; unlike subtraction, this can iterate over
18232 multiple values
18233 </para>
18234 <para>
18235 <literal>jsonb_path_query_array('{"x": [2,3,4]}', '- $.x')</literal>
18236 <returnvalue>[-2, -3, -4]</returnvalue>
18237 </para></entry>
18238 </row>
18239
18240 <row>
18241 <entry role="func_table_entry"><para role="func_signature">
18242 <replaceable>number</replaceable> <literal>*</literal> <replaceable>number</replaceable>
18243 <returnvalue><replaceable>number</replaceable></returnvalue>
18244 </para>
18245 <para>
18246 Multiplication
18247 </para>
18248 <para>
18249 <literal>jsonb_path_query('[4]', '2 * $[0]')</literal>
18250 <returnvalue>8</returnvalue>
18251 </para></entry>
18252 </row>
18253
18254 <row>
18255 <entry role="func_table_entry"><para role="func_signature">
18256 <replaceable>number</replaceable> <literal>/</literal> <replaceable>number</replaceable>
18257 <returnvalue><replaceable>number</replaceable></returnvalue>
18258 </para>
18259 <para>
18260 Division
18261 </para>
18262 <para>
18263 <literal>jsonb_path_query('[8.5]', '$[0] / 2')</literal>
18264 <returnvalue>4.2500000000000000</returnvalue>
18265 </para></entry>
18266 </row>
18267
18268 <row>
18269 <entry role="func_table_entry"><para role="func_signature">
18270 <replaceable>number</replaceable> <literal>%</literal> <replaceable>number</replaceable>
18271 <returnvalue><replaceable>number</replaceable></returnvalue>
18272 </para>
18273 <para>
18274 Modulo (remainder)
18275 </para>
18276 <para>
18277 <literal>jsonb_path_query('[32]', '$[0] % 10')</literal>
18278 <returnvalue>2</returnvalue>
18279 </para></entry>
18280 </row>
18281
18282 <row>
18283 <entry role="func_table_entry"><para role="func_signature">
18284 <replaceable>value</replaceable> <literal>.</literal> <literal>type()</literal>
18285 <returnvalue><replaceable>string</replaceable></returnvalue>
18286 </para>
18287 <para>
18288 Type of the JSON item (see <function>json_typeof</function>)
18289 </para>
18290 <para>
18291 <literal>jsonb_path_query_array('[1, "2", {}]', '$[*].type()')</literal>
18292 <returnvalue>["number", "string", "object"]</returnvalue>
18293 </para></entry>
18294 </row>
18295
18296 <row>
18297 <entry role="func_table_entry"><para role="func_signature">
18298 <replaceable>value</replaceable> <literal>.</literal> <literal>size()</literal>
18299 <returnvalue><replaceable>number</replaceable></returnvalue>
18300 </para>
18301 <para>
18302 Size of the JSON item (number of array elements, or 1 if not an
18303 array)
18304 </para>
18305 <para>
18306 <literal>jsonb_path_query('{"m": [11, 15]}', '$.m.size()')</literal>
18307 <returnvalue>2</returnvalue>
18308 </para></entry>
18309 </row>
18310
18311 <row>
18312 <entry role="func_table_entry"><para role="func_signature">
18313 <replaceable>value</replaceable> <literal>.</literal> <literal>boolean()</literal>
18314 <returnvalue><replaceable>boolean</replaceable></returnvalue>
18315 </para>
18316 <para>
18317 Boolean value converted from a JSON boolean, number, or string
18318 </para>
18319 <para>
18320 <literal>jsonb_path_query_array('[1, "yes", false]', '$[*].boolean()')</literal>
18321 <returnvalue>[true, true, false]</returnvalue>
18322 </para></entry>
18323 </row>
18324
18325 <row>
18326 <entry role="func_table_entry"><para role="func_signature">
18327 <replaceable>value</replaceable> <literal>.</literal> <literal>string()</literal>
18328 <returnvalue><replaceable>string</replaceable></returnvalue>
18329 </para>
18330 <para>
18331 String value converted from a JSON boolean, number, string, or
18332 datetime
18333 </para>
18334 <para>
18335 <literal>jsonb_path_query_array('[1.23, "xyz", false]', '$[*].string()')</literal>
18336 <returnvalue>["1.23", "xyz", "false"]</returnvalue>
18337 </para>
18338 <para>
18339 <literal>jsonb_path_query('"2023-08-15 12:34:56"', '$.timestamp().string()')</literal>
18340 <returnvalue>"2023-08-15T12:34:56"</returnvalue>
18341 </para></entry>
18342 </row>
18343
18344 <row>
18345 <entry role="func_table_entry"><para role="func_signature">
18346 <replaceable>value</replaceable> <literal>.</literal> <literal>double()</literal>
18347 <returnvalue><replaceable>number</replaceable></returnvalue>
18348 </para>
18349 <para>
18350 Approximate floating-point number converted from a JSON number or
18351 string
18352 </para>
18353 <para>
18354 <literal>jsonb_path_query('{"len": "1.9"}', '$.len.double() * 2')</literal>
18355 <returnvalue>3.8</returnvalue>
18356 </para></entry>
18357 </row>
18358
18359 <row>
18360 <entry role="func_table_entry"><para role="func_signature">
18361 <replaceable>number</replaceable> <literal>.</literal> <literal>ceiling()</literal>
18362 <returnvalue><replaceable>number</replaceable></returnvalue>
18363 </para>
18364 <para>
18365 Nearest integer greater than or equal to the given number
18366 </para>
18367 <para>
18368 <literal>jsonb_path_query('{"h": 1.3}', '$.h.ceiling()')</literal>
18369 <returnvalue>2</returnvalue>
18370 </para></entry>
18371 </row>
18372
18373 <row>
18374 <entry role="func_table_entry"><para role="func_signature">
18375 <replaceable>number</replaceable> <literal>.</literal> <literal>floor()</literal>
18376 <returnvalue><replaceable>number</replaceable></returnvalue>
18377 </para>
18378 <para>
18379 Nearest integer less than or equal to the given number
18380 </para>
18381 <para>
18382 <literal>jsonb_path_query('{"h": 1.7}', '$.h.floor()')</literal>
18383 <returnvalue>1</returnvalue>
18384 </para></entry>
18385 </row>
18386
18387 <row>
18388 <entry role="func_table_entry"><para role="func_signature">
18389 <replaceable>number</replaceable> <literal>.</literal> <literal>abs()</literal>
18390 <returnvalue><replaceable>number</replaceable></returnvalue>
18391 </para>
18392 <para>
18393 Absolute value of the given number
18394 </para>
18395 <para>
18396 <literal>jsonb_path_query('{"z": -0.3}', '$.z.abs()')</literal>
18397 <returnvalue>0.3</returnvalue>
18398 </para></entry>
18399 </row>
18400
18401 <row>
18402 <entry role="func_table_entry"><para role="func_signature">
18403 <replaceable>value</replaceable> <literal>.</literal> <literal>bigint()</literal>
18404 <returnvalue><replaceable>bigint</replaceable></returnvalue>
18405 </para>
18406 <para>
18407 Big integer value converted from a JSON number or string
18408 </para>
18409 <para>
18410 <literal>jsonb_path_query('{"len": "9876543219"}', '$.len.bigint()')</literal>
18411 <returnvalue>9876543219</returnvalue>
18412 </para></entry>
18413 </row>
18414
18415 <row>
18416 <entry role="func_table_entry"><para role="func_signature">
18417 <replaceable>value</replaceable> <literal>.</literal> <literal>decimal( [ <replaceable>precision</replaceable> [ , <replaceable>scale</replaceable> ] ] )</literal>
18418 <returnvalue><replaceable>decimal</replaceable></returnvalue>
18419 </para>
18420 <para>
18421 Rounded decimal value converted from a JSON number or string
18422 (<literal>precision</literal> and <literal>scale</literal> must be
18423 integer values)
18424 </para>
18425 <para>
18426 <literal>jsonb_path_query('1234.5678', '$.decimal(6, 2)')</literal>
18427 <returnvalue>1234.57</returnvalue>
18428 </para></entry>
18429 </row>
18430
18431 <row>
18432 <entry role="func_table_entry"><para role="func_signature">
18433 <replaceable>value</replaceable> <literal>.</literal> <literal>integer()</literal>
18434 <returnvalue><replaceable>integer</replaceable></returnvalue>
18435 </para>
18436 <para>
18437 Integer value converted from a JSON number or string
18438 </para>
18439 <para>
18440 <literal>jsonb_path_query('{"len": "12345"}', '$.len.integer()')</literal>
18441 <returnvalue>12345</returnvalue>
18442 </para></entry>
18443 </row>
18444
18445 <row>
18446 <entry role="func_table_entry"><para role="func_signature">
18447 <replaceable>value</replaceable> <literal>.</literal> <literal>number()</literal>
18448 <returnvalue><replaceable>numeric</replaceable></returnvalue>
18449 </para>
18450 <para>
18451 Numeric value converted from a JSON number or string
18452 </para>
18453 <para>
18454 <literal>jsonb_path_query('{"len": "123.45"}', '$.len.number()')</literal>
18455 <returnvalue>123.45</returnvalue>
18456 </para></entry>
18457 </row>
18458
18459 <row>
18460 <entry role="func_table_entry"><para role="func_signature">
18461 <replaceable>string</replaceable> <literal>.</literal> <literal>datetime()</literal>
18462 <returnvalue><replaceable>datetime_type</replaceable></returnvalue>
18463 (see note)
18464 </para>
18465 <para>
18466 Date/time value converted from a string
18467 </para>
18468 <para>
18469 <literal>jsonb_path_query('["2015-8-1", "2015-08-12"]', '$[*] ? (@.datetime() &lt; "2015-08-2".datetime())')</literal>
18470 <returnvalue>"2015-8-1"</returnvalue>
18471 </para></entry>
18472 </row>
18473
18474 <row>
18475 <entry role="func_table_entry"><para role="func_signature">
18476 <replaceable>string</replaceable> <literal>.</literal> <literal>datetime(<replaceable>template</replaceable>)</literal>
18477 <returnvalue><replaceable>datetime_type</replaceable></returnvalue>
18478 (see note)
18479 </para>
18480 <para>
18481 Date/time value converted from a string using the
18482 specified <function>to_timestamp</function> template
18483 </para>
18484 <para>
18485 <literal>jsonb_path_query_array('["12:30", "18:40"]', '$[*].datetime("HH24:MI")')</literal>
18486 <returnvalue>["12:30:00", "18:40:00"]</returnvalue>
18487 </para></entry>
18488 </row>
18489
18490 <row>
18491 <entry role="func_table_entry"><para role="func_signature">
18492 <replaceable>string</replaceable> <literal>.</literal> <literal>date()</literal>
18493 <returnvalue><replaceable>date</replaceable></returnvalue>
18494 </para>
18495 <para>
18496 Date value converted from a string
18497 </para>
18498 <para>
18499 <literal>jsonb_path_query('"2023-08-15"', '$.date()')</literal>
18500 <returnvalue>"2023-08-15"</returnvalue>
18501 </para></entry>
18502 </row>
18503
18504 <row>
18505 <entry role="func_table_entry"><para role="func_signature">
18506 <replaceable>string</replaceable> <literal>.</literal> <literal>time()</literal>
18507 <returnvalue><replaceable>time without time zone</replaceable></returnvalue>
18508 </para>
18509 <para>
18510 Time without time zone value converted from a string
18511 </para>
18512 <para>
18513 <literal>jsonb_path_query('"12:34:56"', '$.time()')</literal>
18514 <returnvalue>"12:34:56"</returnvalue>
18515 </para></entry>
18516 </row>
18517
18518 <row>
18519 <entry role="func_table_entry"><para role="func_signature">
18520 <replaceable>string</replaceable> <literal>.</literal> <literal>time(<replaceable>precision</replaceable>)</literal>
18521 <returnvalue><replaceable>time without time zone</replaceable></returnvalue>
18522 </para>
18523 <para>
18524 Time without time zone value converted from a string, with fractional
18525 seconds adjusted to the given precision
18526 </para>
18527 <para>
18528 <literal>jsonb_path_query('"12:34:56.789"', '$.time(2)')</literal>
18529 <returnvalue>"12:34:56.79"</returnvalue>
18530 </para></entry>
18531 </row>
18532
18533 <row>
18534 <entry role="func_table_entry"><para role="func_signature">
18535 <replaceable>string</replaceable> <literal>.</literal> <literal>time_tz()</literal>
18536 <returnvalue><replaceable>time with time zone</replaceable></returnvalue>
18537 </para>
18538 <para>
18539 Time with time zone value converted from a string
18540 </para>
18541 <para>
18542 <literal>jsonb_path_query('"12:34:56 +05:30"', '$.time_tz()')</literal>
18543 <returnvalue>"12:34:56+05:30"</returnvalue>
18544 </para></entry>
18545 </row>
18546
18547 <row>
18548 <entry role="func_table_entry"><para role="func_signature">
18549 <replaceable>string</replaceable> <literal>.</literal> <literal>time_tz(<replaceable>precision</replaceable>)</literal>
18550 <returnvalue><replaceable>time with time zone</replaceable></returnvalue>
18551 </para>
18552 <para>
18553 Time with time zone value converted from a string, with fractional
18554 seconds adjusted to the given precision
18555 </para>
18556 <para>
18557 <literal>jsonb_path_query('"12:34:56.789 +05:30"', '$.time_tz(2)')</literal>
18558 <returnvalue>"12:34:56.79+05:30"</returnvalue>
18559 </para></entry>
18560 </row>
18561
18562 <row>
18563 <entry role="func_table_entry"><para role="func_signature">
18564 <replaceable>string</replaceable> <literal>.</literal> <literal>timestamp()</literal>
18565 <returnvalue><replaceable>timestamp without time zone</replaceable></returnvalue>
18566 </para>
18567 <para>
18568 Timestamp without time zone value converted from a string
18569 </para>
18570 <para>
18571 <literal>jsonb_path_query('"2023-08-15 12:34:56"', '$.timestamp()')</literal>
18572 <returnvalue>"2023-08-15T12:34:56"</returnvalue>
18573 </para></entry>
18574 </row>
18575
18576 <row>
18577 <entry role="func_table_entry"><para role="func_signature">
18578 <replaceable>string</replaceable> <literal>.</literal> <literal>timestamp(<replaceable>precision</replaceable>)</literal>
18579 <returnvalue><replaceable>timestamp without time zone</replaceable></returnvalue>
18580 </para>
18581 <para>
18582 Timestamp without time zone value converted from a string, with
18583 fractional seconds adjusted to the given precision
18584 </para>
18585 <para>
18586 <literal>jsonb_path_query('"2023-08-15 12:34:56.789"', '$.timestamp(2)')</literal>
18587 <returnvalue>"2023-08-15T12:34:56.79"</returnvalue>
18588 </para></entry>
18589 </row>
18590
18591 <row>
18592 <entry role="func_table_entry"><para role="func_signature">
18593 <replaceable>string</replaceable> <literal>.</literal> <literal>timestamp_tz()</literal>
18594 <returnvalue><replaceable>timestamp with time zone</replaceable></returnvalue>
18595 </para>
18596 <para>
18597 Timestamp with time zone value converted from a string
18598 </para>
18599 <para>
18600 <literal>jsonb_path_query('"2023-08-15 12:34:56 +05:30"', '$.timestamp_tz()')</literal>
18601 <returnvalue>"2023-08-15T12:34:56+05:30"</returnvalue>
18602 </para></entry>
18603 </row>
18604
18605 <row>
18606 <entry role="func_table_entry"><para role="func_signature">
18607 <replaceable>string</replaceable> <literal>.</literal> <literal>timestamp_tz(<replaceable>precision</replaceable>)</literal>
18608 <returnvalue><replaceable>timestamp with time zone</replaceable></returnvalue>
18609 </para>
18610 <para>
18611 Timestamp with time zone value converted from a string, with fractional
18612 seconds adjusted to the given precision
18613 </para>
18614 <para>
18615 <literal>jsonb_path_query('"2023-08-15 12:34:56.789 +05:30"', '$.timestamp_tz(2)')</literal>
18616 <returnvalue>"2023-08-15T12:34:56.79+05:30"</returnvalue>
18617 </para></entry>
18618 </row>
18619
18620 <row>
18621 <entry role="func_table_entry"><para role="func_signature">
18622 <replaceable>object</replaceable> <literal>.</literal> <literal>keyvalue()</literal>
18623 <returnvalue><replaceable>array</replaceable></returnvalue>
18624 </para>
18625 <para>
18626 The object's key-value pairs, represented as an array of objects
18627 containing three fields: <literal>"key"</literal>,
18628 <literal>"value"</literal>, and <literal>"id"</literal>;
18629 <literal>"id"</literal> is a unique identifier of the object the
18630 key-value pair belongs to
18631 </para>
18632 <para>
18633 <literal>jsonb_path_query_array('{"x": "20", "y": 32}', '$.keyvalue()')</literal>
18634 <returnvalue>[{"id": 0, "key": "x", "value": "20"}, {"id": 0, "key": "y", "value": 32}]</returnvalue>
18635 </para></entry>
18636 </row>
18637 </tbody>
18638 </tgroup>
18639 </table>
18640
18641 <note>
18642 <para>
18643 The result type of the <literal>datetime()</literal> and
18644 <literal>datetime(<replaceable>template</replaceable>)</literal>
18645 methods can be <type>date</type>, <type>timetz</type>, <type>time</type>,
18646 <type>timestamptz</type>, or <type>timestamp</type>.
18647 Both methods determine their result type dynamically.
18648 </para>
18649 <para>
18650 The <literal>datetime()</literal> method sequentially tries to
18651 match its input string to the ISO formats
18652 for <type>date</type>, <type>timetz</type>, <type>time</type>,
18653 <type>timestamptz</type>, and <type>timestamp</type>. It stops on
18654 the first matching format and emits the corresponding data type.
18655 </para>
18656 <para>
18657 The <literal>datetime(<replaceable>template</replaceable>)</literal>
18658 method determines the result type according to the fields used in the
18659 provided template string.
18660 </para>
18661 <para>
18662 The <literal>datetime()</literal> and
18663 <literal>datetime(<replaceable>template</replaceable>)</literal> methods
18664 use the same parsing rules as the <literal>to_timestamp</literal> SQL
18665 function does (see <xref linkend="functions-formatting"/>), with three
18666 exceptions. First, these methods don't allow unmatched template
18667 patterns. Second, only the following separators are allowed in the
18668 template string: minus sign, period, solidus (slash), comma, apostrophe,
18669 semicolon, colon and space. Third, separators in the template string
18670 must exactly match the input string.
18671 </para>
18672 <para>
18673 If different date/time types need to be compared, an implicit cast is
18674 applied. A <type>date</type> value can be cast to <type>timestamp</type>
18675 or <type>timestamptz</type>, <type>timestamp</type> can be cast to
18676 <type>timestamptz</type>, and <type>time</type> to <type>timetz</type>.
18677 However, all but the first of these conversions depend on the current
18678 <xref linkend="guc-timezone"/> setting, and thus can only be performed
18679 within timezone-aware <type>jsonpath</type> functions. Similarly, other
18680 date/time-related methods that convert strings to date/time types
18681 also do this casting, which may involve the current
18682 <xref linkend="guc-timezone"/> setting. Therefore, these conversions can
18683 also only be performed within timezone-aware <type>jsonpath</type>
18684 functions.
18685 </para>
18686 </note>
18687
18688 <para>
18689 <xref linkend="functions-sqljson-filter-ex-table"/> shows the available
18690 filter expression elements.
18691 </para>
18692
18693 <table id="functions-sqljson-filter-ex-table">
18694 <title><type>jsonpath</type> Filter Expression Elements</title>
18695 <tgroup cols="1">
18696 <thead>
18697 <row>
18698 <entry role="func_table_entry"><para role="func_signature">
18699 Predicate/Value
18700 </para>
18701 <para>
18702 Description
18703 </para>
18704 <para>
18705 Example(s)
18706 </para></entry>
18707 </row>
18708 </thead>
18709
18710 <tbody>
18711 <row>
18712 <entry role="func_table_entry"><para role="func_signature">
18713 <replaceable>value</replaceable> <literal>==</literal> <replaceable>value</replaceable>
18714 <returnvalue>boolean</returnvalue>
18715 </para>
18716 <para>
18717 Equality comparison (this, and the other comparison operators, work on
18718 all JSON scalar values)
18719 </para>
18720 <para>
18721 <literal>jsonb_path_query_array('[1, "a", 1, 3]', '$[*] ? (@ == 1)')</literal>
18722 <returnvalue>[1, 1]</returnvalue>
18723 </para>
18724 <para>
18725 <literal>jsonb_path_query_array('[1, "a", 1, 3]', '$[*] ? (@ == "a")')</literal>
18726 <returnvalue>["a"]</returnvalue>
18727 </para></entry>
18728 </row>
18729
18730 <row>
18731 <entry role="func_table_entry"><para role="func_signature">
18732 <replaceable>value</replaceable> <literal>!=</literal> <replaceable>value</replaceable>
18733 <returnvalue>boolean</returnvalue>
18734 </para>
18735 <para role="func_signature">
18736 <replaceable>value</replaceable> <literal>&lt;&gt;</literal> <replaceable>value</replaceable>
18737 <returnvalue>boolean</returnvalue>
18738 </para>
18739 <para>
18740 Non-equality comparison
18741 </para>
18742 <para>
18743 <literal>jsonb_path_query_array('[1, 2, 1, 3]', '$[*] ? (@ != 1)')</literal>
18744 <returnvalue>[2, 3]</returnvalue>
18745 </para>
18746 <para>
18747 <literal>jsonb_path_query_array('["a", "b", "c"]', '$[*] ? (@ &lt;&gt; "b")')</literal>
18748 <returnvalue>["a", "c"]</returnvalue>
18749 </para></entry>
18750 </row>
18751
18752 <row>
18753 <entry role="func_table_entry"><para role="func_signature">
18754 <replaceable>value</replaceable> <literal>&lt;</literal> <replaceable>value</replaceable>
18755 <returnvalue>boolean</returnvalue>
18756 </para>
18757 <para>
18758 Less-than comparison
18759 </para>
18760 <para>
18761 <literal>jsonb_path_query_array('[1, 2, 3]', '$[*] ? (@ &lt; 2)')</literal>
18762 <returnvalue>[1]</returnvalue>
18763 </para></entry>
18764 </row>
18765
18766 <row>
18767 <entry role="func_table_entry"><para role="func_signature">
18768 <replaceable>value</replaceable> <literal>&lt;=</literal> <replaceable>value</replaceable>
18769 <returnvalue>boolean</returnvalue>
18770 </para>
18771 <para>
18772 Less-than-or-equal-to comparison
18773 </para>
18774 <para>
18775 <literal>jsonb_path_query_array('["a", "b", "c"]', '$[*] ? (@ &lt;= "b")')</literal>
18776 <returnvalue>["a", "b"]</returnvalue>
18777 </para></entry>
18778 </row>
18779
18780 <row>
18781 <entry role="func_table_entry"><para role="func_signature">
18782 <replaceable>value</replaceable> <literal>&gt;</literal> <replaceable>value</replaceable>
18783 <returnvalue>boolean</returnvalue>
18784 </para>
18785 <para>
18786 Greater-than comparison
18787 </para>
18788 <para>
18789 <literal>jsonb_path_query_array('[1, 2, 3]', '$[*] ? (@ &gt; 2)')</literal>
18790 <returnvalue>[3]</returnvalue>
18791 </para></entry>
18792 </row>
18793
18794 <row>
18795 <entry role="func_table_entry"><para role="func_signature">
18796 <replaceable>value</replaceable> <literal>&gt;=</literal> <replaceable>value</replaceable>
18797 <returnvalue>boolean</returnvalue>
18798 </para>
18799 <para>
18800 Greater-than-or-equal-to comparison
18801 </para>
18802 <para>
18803 <literal>jsonb_path_query_array('[1, 2, 3]', '$[*] ? (@ &gt;= 2)')</literal>
18804 <returnvalue>[2, 3]</returnvalue>
18805 </para></entry>
18806 </row>
18807
18808 <row>
18809 <entry role="func_table_entry"><para role="func_signature">
18810 <literal>true</literal>
18811 <returnvalue>boolean</returnvalue>
18812 </para>
18813 <para>
18814 JSON constant <literal>true</literal>
18815 </para>
18816 <para>
18817 <literal>jsonb_path_query('[{"name": "John", "parent": false}, {"name": "Chris", "parent": true}]', '$[*] ? (@.parent == true)')</literal>
18818 <returnvalue>{"name": "Chris", "parent": true}</returnvalue>
18819 </para></entry>
18820 </row>
18821
18822 <row>
18823 <entry role="func_table_entry"><para role="func_signature">
18824 <literal>false</literal>
18825 <returnvalue>boolean</returnvalue>
18826 </para>
18827 <para>
18828 JSON constant <literal>false</literal>
18829 </para>
18830 <para>
18831 <literal>jsonb_path_query('[{"name": "John", "parent": false}, {"name": "Chris", "parent": true}]', '$[*] ? (@.parent == false)')</literal>
18832 <returnvalue>{"name": "John", "parent": false}</returnvalue>
18833 </para></entry>
18834 </row>
18835
18836 <row>
18837 <entry role="func_table_entry"><para role="func_signature">
18838 <literal>null</literal>
18839 <returnvalue><replaceable>value</replaceable></returnvalue>
18840 </para>
18841 <para>
18842 JSON constant <literal>null</literal> (note that, unlike in SQL,
18843 comparison to <literal>null</literal> works normally)
18844 </para>
18845 <para>
18846 <literal>jsonb_path_query('[{"name": "Mary", "job": null}, {"name": "Michael", "job": "driver"}]', '$[*] ? (@.job == null) .name')</literal>
18847 <returnvalue>"Mary"</returnvalue>
18848 </para></entry>
18849 </row>
18850
18851 <row>
18852 <entry role="func_table_entry"><para role="func_signature">
18853 <replaceable>boolean</replaceable> <literal>&amp;&amp;</literal> <replaceable>boolean</replaceable>
18854 <returnvalue>boolean</returnvalue>
18855 </para>
18856 <para>
18857 Boolean AND
18858 </para>
18859 <para>
18860 <literal>jsonb_path_query('[1, 3, 7]', '$[*] ? (@ &gt; 1 &amp;&amp; @ &lt; 5)')</literal>
18861 <returnvalue>3</returnvalue>
18862 </para></entry>
18863 </row>
18864
18865 <row>
18866 <entry role="func_table_entry"><para role="func_signature">
18867 <replaceable>boolean</replaceable> <literal>||</literal> <replaceable>boolean</replaceable>
18868 <returnvalue>boolean</returnvalue>
18869 </para>
18870 <para>
18871 Boolean OR
18872 </para>
18873 <para>
18874 <literal>jsonb_path_query('[1, 3, 7]', '$[*] ? (@ &lt; 1 || @ &gt; 5)')</literal>
18875 <returnvalue>7</returnvalue>
18876 </para></entry>
18877 </row>
18878
18879 <row>
18880 <entry role="func_table_entry"><para role="func_signature">
18881 <literal>!</literal> <replaceable>boolean</replaceable>
18882 <returnvalue>boolean</returnvalue>
18883 </para>
18884 <para>
18885 Boolean NOT
18886 </para>
18887 <para>
18888 <literal>jsonb_path_query('[1, 3, 7]', '$[*] ? (!(@ &lt; 5))')</literal>
18889 <returnvalue>7</returnvalue>
18890 </para></entry>
18891 </row>
18892
18893 <row>
18894 <entry role="func_table_entry"><para role="func_signature">
18895 <replaceable>boolean</replaceable> <literal>is unknown</literal>
18896 <returnvalue>boolean</returnvalue>
18897 </para>
18898 <para>
18899 Tests whether a Boolean condition is <literal>unknown</literal>.
18900 </para>
18901 <para>
18902 <literal>jsonb_path_query('[-1, 2, 7, "foo"]', '$[*] ? ((@ > 0) is unknown)')</literal>
18903 <returnvalue>"foo"</returnvalue>
18904 </para></entry>
18905 </row>
18906
18907 <row>
18908 <entry role="func_table_entry"><para role="func_signature">
18909 <replaceable>string</replaceable> <literal>like_regex</literal> <replaceable>string</replaceable> <optional> <literal>flag</literal> <replaceable>string</replaceable> </optional>
18910 <returnvalue>boolean</returnvalue>
18911 </para>
18912 <para>
18913 Tests whether the first operand matches the regular expression
18914 given by the second operand, optionally with modifications
18915 described by a string of <literal>flag</literal> characters (see
18916 <xref linkend="jsonpath-regular-expressions"/>).
18917 </para>
18918 <para>
18919 <literal>jsonb_path_query_array('["abc", "abd", "aBdC", "abdacb", "babc"]', '$[*] ? (@ like_regex "^ab.*c")')</literal>
18920 <returnvalue>["abc", "abdacb"]</returnvalue>
18921 </para>
18922 <para>
18923 <literal>jsonb_path_query_array('["abc", "abd", "aBdC", "abdacb", "babc"]', '$[*] ? (@ like_regex "^ab.*c" flag "i")')</literal>
18924 <returnvalue>["abc", "aBdC", "abdacb"]</returnvalue>
18925 </para></entry>
18926 </row>
18927
18928 <row>
18929 <entry role="func_table_entry"><para role="func_signature">
18930 <replaceable>string</replaceable> <literal>starts with</literal> <replaceable>string</replaceable>
18931 <returnvalue>boolean</returnvalue>
18932 </para>
18933 <para>
18934 Tests whether the second operand is an initial substring of the first
18935 operand.
18936 </para>
18937 <para>
18938 <literal>jsonb_path_query('["John Smith", "Mary Stone", "Bob Johnson"]', '$[*] ? (@ starts with "John")')</literal>
18939 <returnvalue>"John Smith"</returnvalue>
18940 </para></entry>
18941 </row>
18942
18943 <row>
18944 <entry role="func_table_entry"><para role="func_signature">
18945 <literal>exists</literal> <literal>(</literal> <replaceable>path_expression</replaceable> <literal>)</literal>
18946 <returnvalue>boolean</returnvalue>
18947 </para>
18948 <para>
18949 Tests whether a path expression matches at least one SQL/JSON item.
18950 Returns <literal>unknown</literal> if the path expression would result
18951 in an error; the second example uses this to avoid a no-such-key error
18952 in strict mode.
18953 </para>
18954 <para>
18955 <literal>jsonb_path_query('{"x": [1, 2], "y": [2, 4]}', 'strict $.* ? (exists (@ ? (@[*] &gt; 2)))')</literal>
18956 <returnvalue>[2, 4]</returnvalue>
18957 </para>
18958 <para>
18959 <literal>jsonb_path_query_array('{"value": 41}', 'strict $ ? (exists (@.name)) .name')</literal>
18960 <returnvalue>[]</returnvalue>
18961 </para></entry>
18962 </row>
18963 </tbody>
18964 </tgroup>
18965 </table>
18966
18967 </sect3>
18968
18969 <sect3 id="jsonpath-regular-expressions">
18970 <title>SQL/JSON Regular Expressions</title>
18971
18972 <indexterm zone="jsonpath-regular-expressions">
18973 <primary><literal>LIKE_REGEX</literal></primary>
18974 <secondary>in SQL/JSON</secondary>
18975 </indexterm>
18976
18977 <para>
18978 SQL/JSON path expressions allow matching text to a regular expression
18979 with the <literal>like_regex</literal> filter. For example, the
18980 following SQL/JSON path query would case-insensitively match all
18981 strings in an array that start with an English vowel:
18982 <programlisting>
18983 $[*] ? (@ like_regex "^[aeiou]" flag "i")
18984 </programlisting>
18985 </para>
18986
18987 <para>
18988 The optional <literal>flag</literal> string may include one or more of
18989 the characters
18990 <literal>i</literal> for case-insensitive match,
18991 <literal>m</literal> to allow <literal>^</literal>
18992 and <literal>$</literal> to match at newlines,
18993 <literal>s</literal> to allow <literal>.</literal> to match a newline,
18994 and <literal>q</literal> to quote the whole pattern (reducing the
18995 behavior to a simple substring match).
18996 </para>
18997
18998 <para>
18999 The SQL/JSON standard borrows its definition for regular expressions
19000 from the <literal>LIKE_REGEX</literal> operator, which in turn uses the
19001 XQuery standard. PostgreSQL does not currently support the
19002 <literal>LIKE_REGEX</literal> operator. Therefore,
19003 the <literal>like_regex</literal> filter is implemented using the
19004 POSIX regular expression engine described in
19005 <xref linkend="functions-posix-regexp"/>. This leads to various minor
19006 discrepancies from standard SQL/JSON behavior, which are cataloged in
19007 <xref linkend="posix-vs-xquery"/>.
19008 Note, however, that the flag-letter incompatibilities described there
19009 do not apply to SQL/JSON, as it translates the XQuery flag letters to
19010 match what the POSIX engine expects.
19011 </para>
19012
19013 <para>
19014 Keep in mind that the pattern argument of <literal>like_regex</literal>
19015 is a JSON path string literal, written according to the rules given in
19016 <xref linkend="datatype-jsonpath"/>. This means in particular that any
19017 backslashes you want to use in the regular expression must be doubled.
19018 For example, to match string values of the root document that contain
19019 only digits:
19020 <programlisting>
19021 $.* ? (@ like_regex "^\\d+$")
19022 </programlisting>
19023 </para>
19024 </sect3>
19025 </sect2>
19026
19027 <sect2 id="sqljson-query-functions">
19028 <title>SQL/JSON Query Functions</title>
19029 <para>
19030 SQL/JSON functions <literal>JSON_EXISTS()</literal>,
19031 <literal>JSON_QUERY()</literal>, and <literal>JSON_VALUE()</literal>
19032 described in <xref linkend="functions-sqljson-querying"/> can be used
19033 to query JSON documents. Each of these functions apply a
19034 <replaceable>path_expression</replaceable> (an SQL/JSON path query) to a
19035 <replaceable>context_item</replaceable> (the document). See
19036 <xref linkend="functions-sqljson-path"/> for more details on what
19037 the <replaceable>path_expression</replaceable> can contain. The
19038 <replaceable>path_expression</replaceable> can also reference variables,
19039 whose values are specified with their respective names in the
19040 <literal>PASSING</literal> clause that is supported by each function.
19041 <replaceable>context_item</replaceable> can be a <type>jsonb</type> value
19042 or a character string that can be successfully cast to <type>jsonb</type>.
19043 </para>
19044
19045 <table id="functions-sqljson-querying">
19046 <title>SQL/JSON Query Functions</title>
19047 <tgroup cols="1">
19048 <thead>
19049 <row>
19050 <entry role="func_table_entry"><para role="func_signature">
19051 Function signature
19052 </para>
19053 <para>
19054 Description
19055 </para>
19056 <para>
19057 Example(s)
19058 </para></entry>
19059 </row>
19060 </thead>
19061 <tbody>
19062 <row>
19063 <entry role="func_table_entry"><para role="func_signature">
19064 <indexterm><primary>json_exists</primary></indexterm>
19065 <synopsis>
19066 <function>JSON_EXISTS</function> (
19067 <replaceable>context_item</replaceable>, <replaceable>path_expression</replaceable>
19068 <optional> <literal>PASSING</literal> { <replaceable>value</replaceable> <literal>AS</literal> <replaceable>varname</replaceable> } <optional>, ...</optional></optional>
19069 <optional>{ <literal>TRUE</literal> | <literal>FALSE</literal> |<literal> UNKNOWN</literal> | <literal>ERROR</literal> } <literal>ON ERROR</literal> </optional>) <returnvalue>boolean</returnvalue>
19070 </synopsis>
19071 </para>
19072 <itemizedlist>
19073 <listitem>
19074 <para>
19075 Returns true if the SQL/JSON <replaceable>path_expression</replaceable>
19076 applied to the <replaceable>context_item</replaceable> yields any
19077 items, false otherwise.
19078 </para>
19079 </listitem>
19080 <listitem>
19081 <para>
19082 The <literal>ON ERROR</literal> clause specifies the behavior if
19083 an error occurs during <replaceable>path_expression</replaceable>
19084 evaluation. Specifying <literal>ERROR</literal> will cause an error to
19085 be thrown with the appropriate message. Other options include
19086 returning <type>boolean</type> values <literal>FALSE</literal> or
19087 <literal>TRUE</literal> or the value <literal>UNKNOWN</literal> which
19088 is actually an SQL NULL. The default when no <literal>ON ERROR</literal>
19089 clause is specified is to return the <type>boolean</type> value
19090 <literal>FALSE</literal>.
19091 </para>
19092 </listitem>
19093 </itemizedlist>
19094 <para>
19095 Examples:
19096 </para>
19097 <para>
19098 <literal>JSON_EXISTS(jsonb '{"key1": [1,2,3]}', 'strict $.key1[*] ? (@ > $x)' PASSING 2 AS x)</literal>
19099 <returnvalue>t</returnvalue>
19100 </para>
19101 <para>
19102 <literal>JSON_EXISTS(jsonb '{"a": [1,2,3]}', 'lax $.a[5]' ERROR ON ERROR)</literal>
19103 <returnvalue>f</returnvalue>
19104 </para>
19105 <para>
19106 <literal>JSON_EXISTS(jsonb '{"a": [1,2,3]}', 'strict $.a[5]' ERROR ON ERROR)</literal>
19107 <returnvalue></returnvalue>
19108 <programlisting>
19109 ERROR: jsonpath array subscript is out of bounds
19110 </programlisting>
19111 </para></entry>
19112 </row>
19113 <row>
19114 <entry role="func_table_entry"><para role="func_signature">
19115 <indexterm><primary>json_query</primary></indexterm>
19116 <synopsis>
19117 <function>JSON_QUERY</function> (
19118 <replaceable>context_item</replaceable>, <replaceable>path_expression</replaceable>
19119 <optional> <literal>PASSING</literal> { <replaceable>value</replaceable> <literal>AS</literal> <replaceable>varname</replaceable> } <optional>, ...</optional></optional>
19120 <optional> <literal>RETURNING</literal> <replaceable>data_type</replaceable> <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional> </optional> </optional>
19121 <optional> { <literal>WITHOUT</literal> | <literal>WITH</literal> { <literal>CONDITIONAL</literal> | <optional><literal>UNCONDITIONAL</literal></optional> } } <optional> <literal>ARRAY</literal> </optional> <literal>WRAPPER</literal> </optional>
19122 <optional> { <literal>KEEP</literal> | <literal>OMIT</literal> } <literal>QUOTES</literal> <optional> <literal>ON SCALAR STRING</literal> </optional> </optional>
19123 <optional> { <literal>ERROR</literal> | <literal>NULL</literal> | <literal>EMPTY</literal> { <optional> <literal>ARRAY</literal> </optional> | <literal>OBJECT</literal> } | <literal>DEFAULT</literal> <replaceable>expression</replaceable> } <literal>ON EMPTY</literal> </optional>
19124 <optional> { <literal>ERROR</literal> | <literal>NULL</literal> | <literal>EMPTY</literal> { <optional> <literal>ARRAY</literal> </optional> | <literal>OBJECT</literal> } | <literal>DEFAULT</literal> <replaceable>expression</replaceable> } <literal>ON ERROR</literal> </optional>) <returnvalue>jsonb</returnvalue>
19125 </synopsis>
19126 </para>
19127 <itemizedlist>
19128 <listitem>
19129 <para>
19130 Returns the result of applying the SQL/JSON
19131 <replaceable>path_expression</replaceable> to the
19132 <replaceable>context_item</replaceable>.
19133 </para>
19134 </listitem>
19135 <listitem>
19136 <para>
19137 By default, the result is returned as a value of type <type>jsonb</type>,
19138 though the <literal>RETURNING</literal> clause can be used to return
19139 as some other type to which it can be successfully coerced.
19140 </para>
19141 </listitem>
19142 <listitem>
19143 <para>
19144 If the path expression may return multiple values, it might be necessary
19145 to wrap those values using the <literal>WITH WRAPPER</literal> clause to
19146 make it a valid JSON string, because the default behavior is to not wrap
19147 them, as if <literal>WITHOUT WRAPPER</literal> were specified. The
19148 <literal>WITH WRAPPER</literal> clause is by default taken to mean
19149 <literal>WITH UNCONDITIONAL WRAPPER</literal>, which means that even a
19150 single result value will be wrapped. To apply the wrapper only when
19151 multiple values are present, specify <literal>WITH CONDITIONAL WRAPPER</literal>.
19152 Getting multiple values in result will be treated as an error if
19153 <literal>WITHOUT WRAPPER</literal> is specified.
19154 </para>
19155 </listitem>
19156 <listitem>
19157 <para>
19158 If the result is a scalar string, by default, the returned value will
19159 be surrounded by quotes, making it a valid JSON value. It can be made
19160 explicit by specifying <literal>KEEP QUOTES</literal>. Conversely,
19161 quotes can be omitted by specifying <literal>OMIT QUOTES</literal>.
19162 To ensure that the result is a valid JSON value, <literal>OMIT QUOTES</literal>
19163 cannot be specified when <literal>WITH WRAPPER</literal> is also
19164 specified.
19165 </para>
19166 </listitem>
19167 <listitem>
19168 <para>
19169 The <literal>ON EMPTY</literal> clause specifies the behavior if
19170 evaluating <replaceable>path_expression</replaceable> yields an empty
19171 set. The <literal>ON ERROR</literal> clause specifies the behavior
19172 if an error occurs when evaluating <replaceable>path_expression</replaceable>,
19173 when coercing the result value to the <literal>RETURNING</literal> type,
19174 or when evaluating the <literal>ON EMPTY</literal> expression if the
19175 <replaceable>path_expression</replaceable> evaluation returns an empty
19176 set.
19177 </para>
19178 </listitem>
19179 <listitem>
19180 <para>
19181 For both <literal>ON EMPTY</literal> and <literal>ON ERROR</literal>,
19182 specifying <literal>ERROR</literal> will cause an error to be thrown with
19183 the appropriate message. Other options include returning an SQL NULL, an
19184 empty array (<literal>EMPTY <optional>ARRAY</optional></literal>),
19185 an empty object (<literal>EMPTY OBJECT</literal>), or a user-specified
19186 expression (<literal>DEFAULT</literal> <replaceable>expression</replaceable>)
19187 that can be coerced to jsonb or the type specified in <literal>RETURNING</literal>.
19188 The default when <literal>ON EMPTY</literal> or <literal>ON ERROR</literal>
19189 is not specified is to return an SQL NULL value.
19190 </para>
19191 </listitem>
19192 </itemizedlist>
19193 <para>
19194 Examples:
19195 </para>
19196 <para>
19197 <literal>JSON_QUERY(jsonb '[1,[2,3],null]', 'lax $[*][$off]' PASSING 1 AS off WITH CONDITIONAL WRAPPER)</literal>
19198 <returnvalue>3</returnvalue>
19199 </para>
19200 <para>
19201 <literal>JSON_QUERY(jsonb '{"a": "[1, 2]"}', 'lax $.a' OMIT QUOTES)</literal>
19202 <returnvalue>[1, 2]</returnvalue>
19203 </para>
19204 <para>
19205 <literal>JSON_QUERY(jsonb '{"a": "[1, 2]"}', 'lax $.a' RETURNING int[] OMIT QUOTES ERROR ON ERROR)</literal>
19206 <returnvalue></returnvalue>
19207 <programlisting>
19208 ERROR: malformed array literal: "[1, 2]"
19209 DETAIL: Missing "]" after array dimensions.
19210 </programlisting>
19211 </para>
19212 </entry>
19213 </row>
19214 <row>
19215 <entry role="func_table_entry"><para role="func_signature">
19216 <indexterm><primary>json_value</primary></indexterm>
19217 <synopsis>
19218 <function>JSON_VALUE</function> (
19219 <replaceable>context_item</replaceable>, <replaceable>path_expression</replaceable>
19220 <optional> <literal>PASSING</literal> { <replaceable>value</replaceable> <literal>AS</literal> <replaceable>varname</replaceable> } <optional>, ...</optional></optional>
19221 <optional> <literal>RETURNING</literal> <replaceable>data_type</replaceable> </optional>
19222 <optional> { <literal>ERROR</literal> | <literal>NULL</literal> | <literal>DEFAULT</literal> <replaceable>expression</replaceable> } <literal>ON EMPTY</literal> </optional>
19223 <optional> { <literal>ERROR</literal> | <literal>NULL</literal> | <literal>DEFAULT</literal> <replaceable>expression</replaceable> } <literal>ON ERROR</literal> </optional>) <returnvalue>text</returnvalue>
19224 </synopsis>
19225 </para>
19226 <itemizedlist>
19227 <listitem>
19228 <para>
19229 Returns the result of applying the SQL/JSON
19230 <replaceable>path_expression</replaceable> to the
19231 <replaceable>context_item</replaceable>.
19232 </para>
19233 </listitem>
19234 <listitem>
19235 <para>
19236 Only use <function>JSON_VALUE()</function> if the extracted value is
19237 expected to be a single <acronym>SQL/JSON</acronym> scalar item;
19238 getting multiple values will be treated as an error. If you expect that
19239 extracted value might be an object or an array, use the
19240 <function>JSON_QUERY</function> function instead.
19241 </para>
19242 </listitem>
19243 <listitem>
19244 <para>
19245 By default, the result, which must be a single scalar value, is
19246 returned as a value of type <type>text</type>, though the
19247 <literal>RETURNING</literal> clause can be used to return as some
19248 other type to which it can be successfully coerced.
19249 </para>
19250 </listitem>
19251 <listitem>
19252 <para>
19253 The <literal>ON ERROR</literal> and <literal>ON EMPTY</literal>
19254 clauses have similar semantics as mentioned in the description of
19255 <function>JSON_QUERY</function>, except the set of values returned in
19256 lieu of throwing an error is different.
19257 </para>
19258 </listitem>
19259 <listitem>
19260 <para>
19261 Note that scalar strings returned by <function>JSON_VALUE</function>
19262 always have their quotes removed, equivalent to specifying
19263 <literal>OMIT QUOTES</literal> in <function>JSON_QUERY</function>.
19264 </para>
19265 </listitem>
19266 </itemizedlist>
19267 <para>
19268 Examples:
19269 </para>
19270 <para>
19271 <literal>JSON_VALUE(jsonb '"123.45"', '$' RETURNING float)</literal>
19272 <returnvalue>123.45</returnvalue>
19273 </para>
19274 <para>
19275 <literal>JSON_VALUE(jsonb '"03:04 2015-02-01"', '$.datetime("HH24:MI&nbsp;YYYY-MM-DD")' RETURNING date)</literal>
19276 <returnvalue>2015-02-01</returnvalue>
19277 </para>
19278 <para>
19279 <literal>JSON_VALUE(jsonb '[1,2]', 'strict $[$off]' PASSING 1 as off)</literal>
19280 <returnvalue>2</returnvalue>
19281 </para>
19282 <para>
19283 <literal>JSON_VALUE(jsonb '[1,2]', 'strict $[*]' DEFAULT 9 ON ERROR)</literal>
19284 <returnvalue>9</returnvalue>
19285 </para>
19286 </entry>
19287 </row>
19288 </tbody>
19289 </tgroup>
19290 </table>
19291 <note>
19292 <para>
19293 The <replaceable>context_item</replaceable> expression is converted to
19294 <type>jsonb</type> by an implicit cast if the expression is not already of
19295 type <type>jsonb</type>. Note, however, that any parsing errors that occur
19296 during that conversion are thrown unconditionally, that is, are not
19297 handled according to the (specified or implicit) <literal>ON ERROR</literal>
19298 clause.
19299 </para>
19300 </note>
19301 <note>
19302 <para>
19303 <function>JSON_VALUE()</function> returns an SQL NULL if
19304 <replaceable>path_expression</replaceable> returns a JSON
19305 <literal>null</literal>, whereas <function>JSON_QUERY()</function> returns
19306 the JSON <literal>null</literal> as is.
19307 </para>
19308 </note>
19309 </sect2>
19310
19311 <sect2 id="functions-sqljson-table">
19312 <title>JSON_TABLE</title>
19313 <indexterm>
19314 <primary>json_table</primary>
19315 </indexterm>
19316
19317 <para>
19318 <function>JSON_TABLE</function> is an SQL/JSON function which
19319 queries <acronym>JSON</acronym> data
19320 and presents the results as a relational view, which can be accessed as a
19321 regular SQL table. You can use <function>JSON_TABLE</function> inside
19322 the <literal>FROM</literal> clause of a <literal>SELECT</literal>,
19323 <literal>UPDATE</literal>, or <literal>DELETE</literal> and as data source
19324 in a <literal>MERGE</literal> statement.
19325 </para>
19326
19327 <para>
19328 Taking JSON data as input, <function>JSON_TABLE</function> uses a JSON path
19329 expression to extract a part of the provided data to use as a
19330 <firstterm>row pattern</firstterm> for the constructed view. Each SQL/JSON
19331 value given by the row pattern serves as source for a separate row in the
19332 constructed view.
19333 </para>
19334
19335 <para>
19336 To split the row pattern into columns, <function>JSON_TABLE</function>
19337 provides the <literal>COLUMNS</literal> clause that defines the
19338 schema of the created view. For each column, a separate JSON path expression
19339 can be specified to be evaluated against the row pattern to get an SQL/JSON
19340 value that will become the value for the specified column in a given output
19341 row.
19342 </para>
19343
19344 <para>
19345 JSON data stored at a nested level of the row pattern can be extracted using
19346 the <literal>NESTED PATH</literal> clause. Each
19347 <literal>NESTED PATH</literal> clause can be used to generate one or more
19348 columns using the data from a nested level of the row pattern. Those
19349 columns can be specified using a <literal>COLUMNS</literal> clause that
19350 looks similar to the top-level COLUMNS clause. Rows constructed from
19351 NESTED COLUMNS are called <firstterm>child rows</firstterm> and are joined
19352 against the row constructed from the columns specified in the parent
19353 <literal>COLUMNS</literal> clause to get the row in the final view. Child
19354 columns themselves may contain a <literal>NESTED PATH</literal>
19355 specification thus allowing to extract data located at arbitrary nesting
19356 levels. Columns produced by multiple <literal>NESTED PATH</literal>s at the
19357 same level are considered to be <firstterm>siblings</firstterm> of each
19358 other and their rows after joining with the parent row are combined using
19359 UNION.
19360 </para>
19361
19362 <para>
19363 The rows produced by <function>JSON_TABLE</function> are laterally
19364 joined to the row that generated them, so you do not have to explicitly join
19365 the constructed view with the original table holding <acronym>JSON</acronym>
19366 data.
19367 </para>
19368
19369 <para>
19370 The syntax is:
19371 </para>
19372
19373 <synopsis>
19374 JSON_TABLE (
19375 <replaceable>context_item</replaceable>, <replaceable>path_expression</replaceable> <optional> AS <replaceable>json_path_name</replaceable> </optional> <optional> PASSING { <replaceable>value</replaceable> AS <replaceable>varname</replaceable> } <optional>, ...</optional> </optional>
19376 COLUMNS ( <replaceable class="parameter">json_table_column</replaceable> <optional>, ...</optional> )
19377 <optional> { <literal>ERROR</literal> | <literal>EMPTY</literal> <optional>ARRAY</optional>} <literal>ON ERROR</literal> </optional>
19378 )
19379
19380 <phrase>
19381 where <replaceable class="parameter">json_table_column</replaceable> is:
19382 </phrase>
19383 <replaceable>name</replaceable> FOR ORDINALITY
19384 | <replaceable>name</replaceable> <replaceable>type</replaceable>
19385 <optional> FORMAT JSON <optional>ENCODING <literal>UTF8</literal></optional></optional>
19386 <optional> PATH <replaceable>path_expression</replaceable> </optional>
19387 <optional> { WITHOUT | WITH { CONDITIONAL | <optional>UNCONDITIONAL</optional> } } <optional> ARRAY </optional> WRAPPER </optional>
19388 <optional> { KEEP | OMIT } QUOTES <optional> ON SCALAR STRING </optional> </optional>
19389 <optional> { ERROR | NULL | EMPTY { <optional>ARRAY</optional> | OBJECT } | DEFAULT <replaceable>expression</replaceable> } ON EMPTY </optional>
19390 <optional> { ERROR | NULL | EMPTY { <optional>ARRAY</optional> | OBJECT } | DEFAULT <replaceable>expression</replaceable> } ON ERROR </optional>
19391 | <replaceable>name</replaceable> <replaceable>type</replaceable> EXISTS <optional> PATH <replaceable>path_expression</replaceable> </optional>
19392 <optional> { ERROR | TRUE | FALSE | UNKNOWN } ON ERROR </optional>
19393 | NESTED <optional> PATH </optional> <replaceable>path_expression</replaceable> <optional> AS <replaceable>json_path_name</replaceable> </optional> COLUMNS ( <replaceable>json_table_column</replaceable> <optional>, ...</optional> )
19394 </synopsis>
19395
19396 <para>
19397 Each syntax element is described below in more detail.
19398 </para>
19399
19400 <variablelist>
19401 <varlistentry>
19402 <term>
19403 <literal><replaceable>context_item</replaceable>, <replaceable>path_expression</replaceable> <optional> <literal>AS</literal> <replaceable>json_path_name</replaceable> </optional> <optional> <literal>PASSING</literal> { <replaceable>value</replaceable> <literal>AS</literal> <replaceable>varname</replaceable> } <optional>, ...</optional></optional></literal>
19404 </term>
19405 <listitem>
19406 <para>
19407 The <replaceable>context_item</replaceable> specifies the input document
19408 to query, the <replaceable>path_expression</replaceable> is an SQL/JSON
19409 path expression defining the query, and <replaceable>json_path_name</replaceable>
19410 is an optional name for the <replaceable>path_expression</replaceable>.
19411 The optional <literal>PASSING</literal> clause provides data values for
19412 the variables mentioned in the <replaceable>path_expression</replaceable>.
19413 The result of the input data evaluation using the aforementioned elements
19414 is called the <firstterm>row pattern</firstterm>, which is used as the
19415 source for row values in the constructed view.
19416 </para>
19417 </listitem>
19418 </varlistentry>
19419
19420 <varlistentry>
19421 <term>
19422 <literal>COLUMNS</literal> ( <replaceable>json_table_column</replaceable> <optional>, ...</optional> )
19423 </term>
19424 <listitem>
19425
19426 <para>
19427 The <literal>COLUMNS</literal> clause defining the schema of the
19428 constructed view. In this clause, you can specify each column to be
19429 filled with an SQL/JSON value obtained by applying a JSON path expression
19430 against the row pattern. <replaceable>json_table_column</replaceable> has
19431 the following variants:
19432 </para>
19433
19434 <variablelist>
19435 <varlistentry>
19436 <term>
19437 <replaceable>name</replaceable> <literal>FOR ORDINALITY</literal>
19438 </term>
19439 <listitem>
19440 <para>
19441 Adds an ordinality column that provides sequential row numbering starting
19442 from 1. Each <literal>NESTED PATH</literal> (see below) gets its own
19443 counter for any nested ordinality columns.
19444 </para>
19445 </listitem>
19446 </varlistentry>
19447
19448 <varlistentry>
19449 <term>
19450 <literal><replaceable>name</replaceable> <replaceable>type</replaceable>
19451 <optional><literal>FORMAT JSON</literal> <optional>ENCODING <literal>UTF8</literal></optional></optional>
19452 <optional> <literal>PATH</literal> <replaceable>path_expression</replaceable> </optional></literal>
19453 </term>
19454 <listitem>
19455 <para>
19456 Inserts an SQL/JSON value obtained by applying
19457 <replaceable>path_expression</replaceable> against the row pattern into
19458 the view's output row after coercing it to specified
19459 <replaceable>type</replaceable>.
19460 </para>
19461 <para>
19462 Specifying <literal>FORMAT JSON</literal> makes it explicit that you
19463 expect the value to be a valid <type>json</type> object. It only
19464 makes sense to specify <literal>FORMAT JSON</literal> if
19465 <replaceable>type</replaceable> is one of <type>bpchar</type>,
19466 <type>bytea</type>, <type>character varying</type>, <type>name</type>,
19467 <type>json</type>, <type>jsonb</type>, <type>text</type>, or a domain over
19468 these types.
19469 </para>
19470 <para>
19471 Optionally, you can specify <literal>WRAPPER</literal> and
19472 <literal>QUOTES</literal> clauses to format the output. Note that
19473 specifying <literal>OMIT QUOTES</literal> overrides
19474 <literal>FORMAT JSON</literal> if also specified, because unquoted
19475 literals do not constitute valid <type>json</type> values.
19476 </para>
19477 <para>
19478 Optionally, you can use <literal>ON EMPTY</literal> and
19479 <literal>ON ERROR</literal> clauses to specify whether to throw the error
19480 or return the specified value when the result of JSON path evaluation is
19481 empty and when an error occurs during JSON path evaluation or when
19482 coercing the SQL/JSON value to the specified type, respectively. The
19483 default for both is to return a <literal>NULL</literal> value.
19484 </para>
19485 <note>
19486 <para>
19487 This clause is internally turned into and has the same semantics as
19488 <function>JSON_VALUE</function> or <function>JSON_QUERY</function>.
19489 The latter if the specified type is not a scalar type or if either of
19490 <literal>FORMAT JSON</literal>, <literal>WRAPPER</literal>, or
19491 <literal>QUOTES</literal> clause is present.
19492 </para>
19493 </note>
19494 </listitem>
19495 </varlistentry>
19496
19497 <varlistentry>
19498 <term>
19499 <replaceable>name</replaceable> <replaceable>type</replaceable>
19500 <literal>EXISTS</literal> <optional> <literal>PATH</literal> <replaceable>path_expression</replaceable> </optional>
19501 </term>
19502 <listitem>
19503 <para>
19504 Inserts a boolean value obtained by applying
19505 <replaceable>path_expression</replaceable> against the row pattern
19506 into the view's output row after coercing it to specified
19507 <replaceable>type</replaceable>.
19508 </para>
19509 <para>
19510 The value corresponds to whether applying the <literal>PATH</literal>
19511 expression to the row pattern yields any values.
19512 </para>
19513 <para>
19514 The specified <replaceable>type</replaceable> should have a cast from the
19515 <type>boolean</type> type.
19516 </para>
19517 <para>
19518 Optionally, you can use <literal>ON ERROR</literal> to specify whether to
19519 throw the error or return the specified value when an error occurs during
19520 JSON path evaluation or when coercing SQL/JSON value to the specified
19521 type. The default is to return a boolean value
19522 <literal>FALSE</literal>.
19523 </para>
19524 <note>
19525 <para>
19526 This clause is internally turned into and has the same semantics as
19527 <function>JSON_EXISTS</function>.
19528 </para>
19529 </note>
19530 </listitem>
19531 </varlistentry>
19532
19533 <varlistentry>
19534 <term>
19535 <literal>NESTED <optional> PATH </optional></literal> <replaceable>path_expression</replaceable> <optional> <literal>AS</literal> <replaceable>json_path_name</replaceable> </optional>
19536 <literal>COLUMNS</literal> ( <replaceable>json_table_column</replaceable> <optional>, ...</optional> )
19537 </term>
19538 <listitem>
19539
19540 <para>
19541 Extracts SQL/JSON values from nested levels of the row pattern,
19542 generates one or more columns as defined by the <literal>COLUMNS</literal>
19543 subclause, and inserts the extracted SQL/JSON values into those
19544 columns. The <replaceable>json_table_column</replaceable>
19545 expression in the <literal>COLUMNS</literal> subclause uses the same
19546 syntax as in the parent <literal>COLUMNS</literal> clause.
19547 </para>
19548
19549 <para>
19550 The <literal>NESTED PATH</literal> syntax is recursive,
19551 so you can go down multiple nested levels by specifying several
19552 <literal>NESTED PATH</literal> subclauses within each other.
19553 It allows to unnest the hierarchy of JSON objects and arrays
19554 in a single function invocation rather than chaining several
19555 <function>JSON_TABLE</function> expressions in an SQL statement.
19556 </para>
19557 </listitem>
19558 </varlistentry>
19559 </variablelist>
19560
19561 <note>
19562 <para>
19563 In each variant of <replaceable>json_table_column</replaceable> described
19564 above, if the <literal>PATH</literal> clause is omitted, path expression
19565 <literal>$.<replaceable>name</replaceable></literal> is used, where
19566 <replaceable>name</replaceable> is the provided column name.
19567 </para>
19568 </note>
19569
19570 </listitem>
19571 </varlistentry>
19572
19573 <varlistentry>
19574 <term>
19575 <literal>AS</literal> <replaceable>json_path_name</replaceable>
19576 </term>
19577 <listitem>
19578
19579 <para>
19580 The optional <replaceable>json_path_name</replaceable> serves as an
19581 identifier of the provided <replaceable>path_expression</replaceable>.
19582 The name must be unique and distinct from the column names.
19583 </para>
19584 </listitem>
19585 </varlistentry>
19586
19587 <varlistentry>
19588 <term>
19589 { <literal>ERROR</literal> | <literal>EMPTY</literal> } <literal>ON ERROR</literal>
19590 </term>
19591 <listitem>
19592
19593 <para>
19594 The optional <literal>ON ERROR</literal> can be used to specify how to
19595 handle errors when evaluating the top-level
19596 <replaceable>path_expression</replaceable>. Use <literal>ERROR</literal>
19597 if you want the errors to be thrown and <literal>EMPTY</literal> to
19598 return an empty table, that is, a table containing 0 rows. Note that
19599 this clause does not affect the errors that occur when evaluating
19600 columns, for which the behavior depends on whether the
19601 <literal>ON ERROR</literal> clause is specified against a given column.
19602 </para>
19603 </listitem>
19604 </varlistentry>
19605 </variablelist>
19606
19607 <para>Examples</para>
19608
19609 <para>
19610 In the examples that follow, the following table containing JSON data
19611 will be used:
19612
19613 <programlisting>
19614 CREATE TABLE my_films ( js jsonb );
19615
19616 INSERT INTO my_films VALUES (
19617 '{ "favorites" : [
19618 { "kind" : "comedy", "films" : [
19619 { "title" : "Bananas",
19620 "director" : "Woody Allen"},
19621 { "title" : "The Dinner Game",
19622 "director" : "Francis Veber" } ] },
19623 { "kind" : "horror", "films" : [
19624 { "title" : "Psycho",
19625 "director" : "Alfred Hitchcock" } ] },
19626 { "kind" : "thriller", "films" : [
19627 { "title" : "Vertigo",
19628 "director" : "Alfred Hitchcock" } ] },
19629 { "kind" : "drama", "films" : [
19630 { "title" : "Yojimbo",
19631 "director" : "Akira Kurosawa" } ] }
19632 ] }');
19633 </programlisting>
19634
19635 </para>
19636 <para>
19637 The following query shows how to use <function>JSON_TABLE</function> to
19638 turn the JSON objects in the <structname>my_films</structname> table
19639 to a view containing columns for the keys <literal>kind</literal>,
19640 <literal>title</literal>, and <literal>director</literal> contained in
19641 the original JSON along with an ordinality column:
19642
19643 <programlisting>
19644 SELECT jt.* FROM
19645 my_films,
19646 JSON_TABLE (js, '$.favorites[*]' COLUMNS (
19647 id FOR ORDINALITY,
19648 kind text PATH '$.kind',
19649 title text PATH '$.films[*].title' WITH WRAPPER,
19650 director text PATH '$.films[*].director' WITH WRAPPER)) AS jt;
19651 </programlisting>
19652
19653 <screen>
19654 id | kind | title | director
19655 ----+----------+--------------------------------+----------------------------------
19656 1 | comedy | ["Bananas", "The Dinner Game"] | ["Woody Allen", "Francis Veber"]
19657 2 | horror | ["Psycho"] | ["Alfred Hitchcock"]
19658 3 | thriller | ["Vertigo"] | ["Alfred Hitchcock"]
19659 4 | drama | ["Yojimbo"] | ["Akira Kurosawa"]
19660 (4 rows)
19661 </screen>
19662
19663 </para>
19664 <para>
19665 The following is a modified version of the above query to show the
19666 usage of <literal>PASSING</literal> arguments in the filter specified in
19667 the top-level JSON path expression and the various options for the
19668 individual columns:
19669
19670 <programlisting>
19671 SELECT jt.* FROM
19672 my_films,
19673 JSON_TABLE (js, '$.favorites[*] ? (@.films[*].director == $filter)'
19674 PASSING 'Alfred Hitchcock' AS filter
19675 COLUMNS (
19676 id FOR ORDINALITY,
19677 kind text PATH '$.kind',
19678 title text FORMAT JSON PATH '$.films[*].title' OMIT QUOTES,
19679 director text PATH '$.films[*].director' KEEP QUOTES)) AS jt;
19680 </programlisting>
19681
19682 <screen>
19683 id | kind | title | director
19684 ----+----------+---------+--------------------
19685 1 | horror | Psycho | "Alfred Hitchcock"
19686 2 | thriller | Vertigo | "Alfred Hitchcock"
19687 (2 rows)
19688 </screen>
19689
19690 </para>
19691 <para>
19692 The following is a modified version of the above query to show the usage
19693 of <literal>NESTED PATH</literal> for populating title and director
19694 columns, illustrating how they are joined to the parent columns id and
19695 kind:
19696
19697 <programlisting>
19698 SELECT jt.* FROM
19699 my_films,
19700 JSON_TABLE ( js, '$.favorites[*] ? (@.films[*].director == $filter)'
19701 PASSING 'Alfred Hitchcock' AS filter
19702 COLUMNS (
19703 id FOR ORDINALITY,
19704 kind text PATH '$.kind',
19705 NESTED PATH '$.films[*]' COLUMNS (
19706 title text FORMAT JSON PATH '$.title' OMIT QUOTES,
19707 director text PATH '$.director' KEEP QUOTES))) AS jt;
19708 </programlisting>
19709
19710 <screen>
19711 id | kind | title | director
19712 ----+----------+---------+--------------------
19713 1 | horror | Psycho | "Alfred Hitchcock"
19714 2 | thriller | Vertigo | "Alfred Hitchcock"
19715 (2 rows)
19716 </screen>
19717
19718 </para>
19719
19720 <para>
19721 The following is the same query but without the filter in the root
19722 path:
19723
19724 <programlisting>
19725 SELECT jt.* FROM
19726 my_films,
19727 JSON_TABLE ( js, '$.favorites[*]'
19728 COLUMNS (
19729 id FOR ORDINALITY,
19730 kind text PATH '$.kind',
19731 NESTED PATH '$.films[*]' COLUMNS (
19732 title text FORMAT JSON PATH '$.title' OMIT QUOTES,
19733 director text PATH '$.director' KEEP QUOTES))) AS jt;
19734 </programlisting>
19735
19736 <screen>
19737 id | kind | title | director
19738 ----+----------+-----------------+--------------------
19739 1 | comedy | Bananas | "Woody Allen"
19740 1 | comedy | The Dinner Game | "Francis Veber"
19741 2 | horror | Psycho | "Alfred Hitchcock"
19742 3 | thriller | Vertigo | "Alfred Hitchcock"
19743 4 | drama | Yojimbo | "Akira Kurosawa"
19744 (5 rows)
19745 </screen>
19746
19747 </para>
19748
19749 <para>
19750 The following shows another query using a different <type>JSON</type>
19751 object as input. It shows the UNION "sibling join" between
19752 <literal>NESTED</literal> paths <literal>$.movies[*]</literal> and
19753 <literal>$.books[*]</literal> and also the usage of
19754 <literal>FOR ORDINALITY</literal> column at <literal>NESTED</literal>
19755 levels (columns <literal>movie_id</literal>, <literal>book_id</literal>,
19756 and <literal>author_id</literal>):
19757
19758 <programlisting>
19759 SELECT * FROM JSON_TABLE (
19760 '{"favorites":
19761 [{"movies":
19762 [{"name": "One", "director": "John Doe"},
19763 {"name": "Two", "director": "Don Joe"}],
19764 "books":
19765 [{"name": "Mystery", "authors": [{"name": "Brown Dan"}]},
19766 {"name": "Wonder", "authors": [{"name": "Jun Murakami"}, {"name":"Craig Doe"}]}]
19767 }]}'::json, '$.favorites[*]'
19768 COLUMNS (
19769 user_id FOR ORDINALITY,
19770 NESTED '$.movies[*]'
19771 COLUMNS (
19772 movie_id FOR ORDINALITY,
19773 mname text PATH '$.name',
19774 director text),
19775 NESTED '$.books[*]'
19776 COLUMNS (
19777 book_id FOR ORDINALITY,
19778 bname text PATH '$.name',
19779 NESTED '$.authors[*]'
19780 COLUMNS (
19781 author_id FOR ORDINALITY,
19782 author_name text PATH '$.name'))));
19783 </programlisting>
19784
19785 <screen>
19786 user_id | movie_id | mname | director | book_id | bname | author_id | author_name
19787 ---------+----------+-------+----------+---------+---------+-----------+--------------
19788 1 | 1 | One | John Doe | | | |
19789 1 | 2 | Two | Don Joe | | | |
19790 1 | | | | 1 | Mystery | 1 | Brown Dan
19791 1 | | | | 2 | Wonder | 1 | Jun Murakami
19792 1 | | | | 2 | Wonder | 2 | Craig Doe
19793 (5 rows)
19794 </screen>
19795
19796 </para>
19797 </sect2>
19798 </sect1>
19799
19800 <sect1 id="functions-sequence">
19801 <title>Sequence Manipulation Functions</title>
19802
19803 <indexterm>
19804 <primary>sequence</primary>
19805 </indexterm>
19806
19807 <para>
19808 This section describes functions for operating on <firstterm>sequence
19809 objects</firstterm>, also called sequence generators or just sequences.
19810 Sequence objects are special single-row tables created with <xref
19811 linkend="sql-createsequence"/>.
19812 Sequence objects are commonly used to generate unique identifiers
19813 for rows of a table. The sequence functions, listed in <xref
19814 linkend="functions-sequence-table"/>, provide simple, multiuser-safe
19815 methods for obtaining successive sequence values from sequence
19816 objects.
19817 </para>
19818
19819 <table id="functions-sequence-table">
19820 <title>Sequence Functions</title>
19821 <tgroup cols="1">
19822 <thead>
19823 <row>
19824 <entry role="func_table_entry"><para role="func_signature">
19825 Function
19826 </para>
19827 <para>
19828 Description
19829 </para></entry>
19830 </row>
19831 </thead>
19832
19833 <tbody>
19834 <row>
19835 <entry role="func_table_entry"><para role="func_signature">
19836 <indexterm>
19837 <primary>nextval</primary>
19838 </indexterm>
19839 <function>nextval</function> ( <type>regclass</type> )
19840 <returnvalue>bigint</returnvalue>
19841 </para>
19842 <para>
19843 Advances the sequence object to its next value and returns that value.
19844 This is done atomically: even if multiple sessions
19845 execute <function>nextval</function> concurrently, each will safely
19846 receive a distinct sequence value.
19847 If the sequence object has been created with default parameters,
19848 successive <function>nextval</function> calls will return successive
19849 values beginning with 1. Other behaviors can be obtained by using
19850 appropriate parameters in the <xref linkend="sql-createsequence"/>
19851 command.
19852 </para>
19853 <para>
19854 This function requires <literal>USAGE</literal>
19855 or <literal>UPDATE</literal> privilege on the sequence.
19856 </para></entry>
19857 </row>
19858
19859 <row>
19860 <entry role="func_table_entry"><para role="func_signature">
19861 <indexterm>
19862 <primary>setval</primary>
19863 </indexterm>
19864 <function>setval</function> ( <type>regclass</type>, <type>bigint</type> <optional>, <type>boolean</type> </optional> )
19865 <returnvalue>bigint</returnvalue>
19866 </para>
19867 <para>
19868 Sets the sequence object's current value, and optionally
19869 its <literal>is_called</literal> flag. The two-parameter
19870 form sets the sequence's <literal>last_value</literal> field to the
19871 specified value and sets its <literal>is_called</literal> field to
19872 <literal>true</literal>, meaning that the next
19873 <function>nextval</function> will advance the sequence before
19874 returning a value. The value that will be reported
19875 by <function>currval</function> is also set to the specified value.
19876 In the three-parameter form, <literal>is_called</literal> can be set
19877 to either <literal>true</literal>
19878 or <literal>false</literal>. <literal>true</literal> has the same
19879 effect as the two-parameter form. If it is set
19880 to <literal>false</literal>, the next <function>nextval</function>
19881 will return exactly the specified value, and sequence advancement
19882 commences with the following <function>nextval</function>.
19883 Furthermore, the value reported by <function>currval</function> is not
19884 changed in this case. For example,
19885 <programlisting>
19886 SELECT setval('myseq', 42); <lineannotation>Next <function>nextval</function> will return 43</lineannotation>
19887 SELECT setval('myseq', 42, true); <lineannotation>Same as above</lineannotation>
19888 SELECT setval('myseq', 42, false); <lineannotation>Next <function>nextval</function> will return 42</lineannotation>
19889 </programlisting>
19890 The result returned by <function>setval</function> is just the value of its
19891 second argument.
19892 </para>
19893 <para>
19894 This function requires <literal>UPDATE</literal> privilege on the
19895 sequence.
19896 </para></entry>
19897 </row>
19898
19899 <row>
19900 <entry role="func_table_entry"><para role="func_signature">
19901 <indexterm>
19902 <primary>currval</primary>
19903 </indexterm>
19904 <function>currval</function> ( <type>regclass</type> )
19905 <returnvalue>bigint</returnvalue>
19906 </para>
19907 <para>
19908 Returns the value most recently obtained
19909 by <function>nextval</function> for this sequence in the current
19910 session. (An error is reported if <function>nextval</function> has
19911 never been called for this sequence in this session.) Because this is
19912 returning a session-local value, it gives a predictable answer whether
19913 or not other sessions have executed <function>nextval</function> since
19914 the current session did.
19915 </para>
19916 <para>
19917 This function requires <literal>USAGE</literal>
19918 or <literal>SELECT</literal> privilege on the sequence.
19919 </para></entry>
19920 </row>
19921
19922 <row>
19923 <entry role="func_table_entry"><para role="func_signature">
19924 <indexterm>
19925 <primary>lastval</primary>
19926 </indexterm>
19927 <function>lastval</function> ()
19928 <returnvalue>bigint</returnvalue>
19929 </para>
19930 <para>
19931 Returns the value most recently returned by
19932 <function>nextval</function> in the current session. This function is
19933 identical to <function>currval</function>, except that instead
19934 of taking the sequence name as an argument it refers to whichever
19935 sequence <function>nextval</function> was most recently applied to
19936 in the current session. It is an error to call
19937 <function>lastval</function> if <function>nextval</function>
19938 has not yet been called in the current session.
19939 </para>
19940 <para>
19941 This function requires <literal>USAGE</literal>
19942 or <literal>SELECT</literal> privilege on the last used sequence.
19943 </para></entry>
19944 </row>
19945 </tbody>
19946 </tgroup>
19947 </table>
19948
19949 <caution>
19950 <para>
19951 To avoid blocking concurrent transactions that obtain numbers from
19952 the same sequence, the value obtained by <function>nextval</function>
19953 is not reclaimed for re-use if the calling transaction later aborts.
19954 This means that transaction aborts or database crashes can result in
19955 gaps in the sequence of assigned values. That can happen without a
19956 transaction abort, too. For example an <command>INSERT</command> with
19957 an <literal>ON CONFLICT</literal> clause will compute the to-be-inserted
19958 tuple, including doing any required <function>nextval</function>
19959 calls, before detecting any conflict that would cause it to follow
19960 the <literal>ON CONFLICT</literal> rule instead.
19961 Thus, <productname>PostgreSQL</productname> sequence
19962 objects <emphasis>cannot be used to obtain <quote>gapless</quote>
19963 sequences</emphasis>.
19964 </para>
19965
19966 <para>
19967 Likewise, sequence state changes made by <function>setval</function>
19968 are immediately visible to other transactions, and are not undone if
19969 the calling transaction rolls back.
19970 </para>
19971
19972 <para>
19973 If the database cluster crashes before committing a transaction
19974 containing a <function>nextval</function>
19975 or <function>setval</function> call, the sequence state change might
19976 not have made its way to persistent storage, so that it is uncertain
19977 whether the sequence will have its original or updated state after the
19978 cluster restarts. This is harmless for usage of the sequence within
19979 the database, since other effects of uncommitted transactions will not
19980 be visible either. However, if you wish to use a sequence value for
19981 persistent outside-the-database purposes, make sure that the
19982 <function>nextval</function> call has been committed before doing so.
19983 </para>
19984 </caution>
19985
19986 <para>
19987 The sequence to be operated on by a sequence function is specified by
19988 a <type>regclass</type> argument, which is simply the OID of the sequence in the
19989 <structname>pg_class</structname> system catalog. You do not have to look up the
19990 OID by hand, however, since the <type>regclass</type> data type's input
19991 converter will do the work for you. See <xref linkend="datatype-oid"/>
19992 for details.
19993 </para>
19994 </sect1>
19995
19996
19997 <sect1 id="functions-conditional">
19998 <title>Conditional Expressions</title>
19999
20000 <indexterm>
20001 <primary>CASE</primary>
20002 </indexterm>
20003
20004 <indexterm>
20005 <primary>conditional expression</primary>
20006 </indexterm>
20007
20008 <para>
20009 This section describes the <acronym>SQL</acronym>-compliant conditional expressions
20010 available in <productname>PostgreSQL</productname>.
20011 </para>
20012
20013 <tip>
20014 <para>
20015 If your needs go beyond the capabilities of these conditional
20016 expressions, you might want to consider writing a server-side function
20017 in a more expressive programming language.
20018 </para>
20019 </tip>
20020
20021 <note>
20022 <para>
20023 Although <token>COALESCE</token>, <token>GREATEST</token>, and
20024 <token>LEAST</token> are syntactically similar to functions, they are
20025 not ordinary functions, and thus cannot be used with explicit
20026 <token>VARIADIC</token> array arguments.
20027 </para>
20028 </note>
20029
20030 <sect2 id="functions-case">
20031 <title><literal>CASE</literal></title>
20032
20033 <para>
20034 The <acronym>SQL</acronym> <token>CASE</token> expression is a
20035 generic conditional expression, similar to if/else statements in
20036 other programming languages:
20037
20038 <synopsis>
20039 CASE WHEN <replaceable>condition</replaceable> THEN <replaceable>result</replaceable>
20040 <optional>WHEN ...</optional>
20041 <optional>ELSE <replaceable>result</replaceable></optional>
20042 END
20043 </synopsis>
20044
20045 <token>CASE</token> clauses can be used wherever
20046 an expression is valid. Each <replaceable>condition</replaceable> is an
20047 expression that returns a <type>boolean</type> result. If the condition's
20048 result is true, the value of the <token>CASE</token> expression is the
20049 <replaceable>result</replaceable> that follows the condition, and the
20050 remainder of the <token>CASE</token> expression is not processed. If the
20051 condition's result is not true, any subsequent <token>WHEN</token> clauses
20052 are examined in the same manner. If no <token>WHEN</token>
20053 <replaceable>condition</replaceable> yields true, the value of the
20054 <token>CASE</token> expression is the <replaceable>result</replaceable> of the
20055 <token>ELSE</token> clause. If the <token>ELSE</token> clause is
20056 omitted and no condition is true, the result is null.
20057 </para>
20058
20059 <para>
20060 An example:
20061 <screen>
20062 SELECT * FROM test;
20063
20064 a
20065 ---
20066 1
20067 2
20068 3
20069
20070
20071 SELECT a,
20072 CASE WHEN a=1 THEN 'one'
20073 WHEN a=2 THEN 'two'
20074 ELSE 'other'
20075 END
20076 FROM test;
20077
20078 a | case
20079 ---+-------
20080 1 | one
20081 2 | two
20082 3 | other
20083 </screen>
20084 </para>
20085
20086 <para>
20087 The data types of all the <replaceable>result</replaceable>
20088 expressions must be convertible to a single output type.
20089 See <xref linkend="typeconv-union-case"/> for more details.
20090 </para>
20091
20092 <para>
20093 There is a <quote>simple</quote> form of <token>CASE</token> expression
20094 that is a variant of the general form above:
20095
20096 <synopsis>
20097 CASE <replaceable>expression</replaceable>
20098 WHEN <replaceable>value</replaceable> THEN <replaceable>result</replaceable>
20099 <optional>WHEN ...</optional>
20100 <optional>ELSE <replaceable>result</replaceable></optional>
20101 END
20102 </synopsis>
20103
20104 The first
20105 <replaceable>expression</replaceable> is computed, then compared to
20106 each of the <replaceable>value</replaceable> expressions in the
20107 <token>WHEN</token> clauses until one is found that is equal to it. If
20108 no match is found, the <replaceable>result</replaceable> of the
20109 <token>ELSE</token> clause (or a null value) is returned. This is similar
20110 to the <function>switch</function> statement in C.
20111 </para>
20112
20113 <para>
20114 The example above can be written using the simple
20115 <token>CASE</token> syntax:
20116 <screen>
20117 SELECT a,
20118 CASE a WHEN 1 THEN 'one'
20119 WHEN 2 THEN 'two'
20120 ELSE 'other'
20121 END
20122 FROM test;
20123
20124 a | case
20125 ---+-------
20126 1 | one
20127 2 | two
20128 3 | other
20129 </screen>
20130 </para>
20131
20132 <para>
20133 A <token>CASE</token> expression does not evaluate any subexpressions
20134 that are not needed to determine the result. For example, this is a
20135 possible way of avoiding a division-by-zero failure:
20136 <programlisting>
20137 SELECT ... WHERE CASE WHEN x &lt;&gt; 0 THEN y/x &gt; 1.5 ELSE false END;
20138 </programlisting>
20139 </para>
20140
20141 <note>
20142 <para>
20143 As described in <xref linkend="syntax-express-eval"/>, there are various
20144 situations in which subexpressions of an expression are evaluated at
20145 different times, so that the principle that <quote><token>CASE</token>
20146 evaluates only necessary subexpressions</quote> is not ironclad. For
20147 example a constant <literal>1/0</literal> subexpression will usually result in
20148 a division-by-zero failure at planning time, even if it's within
20149 a <token>CASE</token> arm that would never be entered at run time.
20150 </para>
20151 </note>
20152 </sect2>
20153
20154 <sect2 id="functions-coalesce-nvl-ifnull">
20155 <title><literal>COALESCE</literal></title>
20156
20157 <indexterm>
20158 <primary>COALESCE</primary>
20159 </indexterm>
20160
20161 <indexterm>
20162 <primary>NVL</primary>
20163 </indexterm>
20164
20165 <indexterm>
20166 <primary>IFNULL</primary>
20167 </indexterm>
20168
20169 <synopsis>
20170 <function>COALESCE</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
20171 </synopsis>
20172
20173 <para>
20174 The <function>COALESCE</function> function returns the first of its
20175 arguments that is not null. Null is returned only if all arguments
20176 are null. It is often used to substitute a default value for
20177 null values when data is retrieved for display, for example:
20178 <programlisting>
20179 SELECT COALESCE(description, short_description, '(none)') ...
20180 </programlisting>
20181 This returns <varname>description</varname> if it is not null, otherwise
20182 <varname>short_description</varname> if it is not null, otherwise <literal>(none)</literal>.
20183 </para>
20184
20185 <para>
20186 The arguments must all be convertible to a common data type, which
20187 will be the type of the result (see
20188 <xref linkend="typeconv-union-case"/> for details).
20189 </para>
20190
20191 <para>
20192 Like a <token>CASE</token> expression, <function>COALESCE</function> only
20193 evaluates the arguments that are needed to determine the result;
20194 that is, arguments to the right of the first non-null argument are
20195 not evaluated. This SQL-standard function provides capabilities similar
20196 to <function>NVL</function> and <function>IFNULL</function>, which are used in some other
20197 database systems.
20198 </para>
20199 </sect2>
20200
20201 <sect2 id="functions-nullif">
20202 <title><literal>NULLIF</literal></title>
20203
20204 <indexterm>
20205 <primary>NULLIF</primary>
20206 </indexterm>
20207
20208 <synopsis>
20209 <function>NULLIF</function>(<replaceable>value1</replaceable>, <replaceable>value2</replaceable>)
20210 </synopsis>
20211
20212 <para>
20213 The <function>NULLIF</function> function returns a null value if
20214 <replaceable>value1</replaceable> equals <replaceable>value2</replaceable>;
20215 otherwise it returns <replaceable>value1</replaceable>.
20216 This can be used to perform the inverse operation of the
20217 <function>COALESCE</function> example given above:
20218 <programlisting>
20219 SELECT NULLIF(value, '(none)') ...
20220 </programlisting>
20221 In this example, if <literal>value</literal> is <literal>(none)</literal>,
20222 null is returned, otherwise the value of <literal>value</literal>
20223 is returned.
20224 </para>
20225
20226 <para>
20227 The two arguments must be of comparable types.
20228 To be specific, they are compared exactly as if you had
20229 written <literal><replaceable>value1</replaceable>
20230 = <replaceable>value2</replaceable></literal>, so there must be a
20231 suitable <literal>=</literal> operator available.
20232 </para>
20233
20234 <para>
20235 The result has the same type as the first argument &mdash; but there is
20236 a subtlety. What is actually returned is the first argument of the
20237 implied <literal>=</literal> operator, and in some cases that will have
20238 been promoted to match the second argument's type. For
20239 example, <literal>NULLIF(1, 2.2)</literal> yields <type>numeric</type>,
20240 because there is no <type>integer</type> <literal>=</literal>
20241 <type>numeric</type> operator,
20242 only <type>numeric</type> <literal>=</literal> <type>numeric</type>.
20243 </para>
20244
20245 </sect2>
20246
20247 <sect2 id="functions-greatest-least">
20248 <title><literal>GREATEST</literal> and <literal>LEAST</literal></title>
20249
20250 <indexterm>
20251 <primary>GREATEST</primary>
20252 </indexterm>
20253 <indexterm>
20254 <primary>LEAST</primary>
20255 </indexterm>
20256
20257 <synopsis>
20258 <function>GREATEST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
20259 </synopsis>
20260 <synopsis>
20261 <function>LEAST</function>(<replaceable>value</replaceable> <optional>, ...</optional>)
20262 </synopsis>
20263
20264 <para>
20265 The <function>GREATEST</function> and <function>LEAST</function> functions select the
20266 largest or smallest value from a list of any number of expressions.
20267 The expressions must all be convertible to a common data type, which
20268 will be the type of the result
20269 (see <xref linkend="typeconv-union-case"/> for details).
20270 </para>
20271
20272 <para>
20273 NULL values in the argument list are ignored. The result will be NULL
20274 only if all the expressions evaluate to NULL. (This is a deviation from
20275 the SQL standard. According to the standard, the return value is NULL if
20276 any argument is NULL. Some other databases behave this way.)
20277 </para>
20278 </sect2>
20279 </sect1>
20280
20281 <sect1 id="functions-array">
20282 <title>Array Functions and Operators</title>
20283
20284 <para>
20285 <xref linkend="array-operators-table"/> shows the specialized operators
20286 available for array types.
20287 In addition to those, the usual comparison operators shown in <xref
20288 linkend="functions-comparison-op-table"/> are available for
20289 arrays. The comparison operators compare the array contents
20290 element-by-element, using the default B-tree comparison function for
20291 the element data type, and sort based on the first difference.
20292 In multidimensional arrays the elements are visited in row-major order
20293 (last subscript varies most rapidly).
20294 If the contents of two arrays are equal but the dimensionality is
20295 different, the first difference in the dimensionality information
20296 determines the sort order.
20297 </para>
20298
20299 <table id="array-operators-table">
20300 <title>Array Operators</title>
20301 <tgroup cols="1">
20302 <thead>
20303 <row>
20304 <entry role="func_table_entry"><para role="func_signature">
20305 Operator
20306 </para>
20307 <para>
20308 Description
20309 </para>
20310 <para>
20311 Example(s)
20312 </para></entry>
20313 </row>
20314 </thead>
20315
20316 <tbody>
20317 <row>
20318 <entry role="func_table_entry"><para role="func_signature">
20319 <type>anyarray</type> <literal>@&gt;</literal> <type>anyarray</type>
20320 <returnvalue>boolean</returnvalue>
20321 </para>
20322 <para>
20323 Does the first array contain the second, that is, does each element
20324 appearing in the second array equal some element of the first array?
20325 (Duplicates are not treated specially,
20326 thus <literal>ARRAY[1]</literal> and <literal>ARRAY[1,1]</literal> are
20327 each considered to contain the other.)
20328 </para>
20329 <para>
20330 <literal>ARRAY[1,4,3] @&gt; ARRAY[3,1,3]</literal>
20331 <returnvalue>t</returnvalue>
20332 </para></entry>
20333 </row>
20334
20335 <row>
20336 <entry role="func_table_entry"><para role="func_signature">
20337 <type>anyarray</type> <literal>&lt;@</literal> <type>anyarray</type>
20338 <returnvalue>boolean</returnvalue>
20339 </para>
20340 <para>
20341 Is the first array contained by the second?
20342 </para>
20343 <para>
20344 <literal>ARRAY[2,2,7] &lt;@ ARRAY[1,7,4,2,6]</literal>
20345 <returnvalue>t</returnvalue>
20346 </para></entry>
20347 </row>
20348
20349 <row>
20350 <entry role="func_table_entry"><para role="func_signature">
20351 <type>anyarray</type> <literal>&amp;&amp;</literal> <type>anyarray</type>
20352 <returnvalue>boolean</returnvalue>
20353 </para>
20354 <para>
20355 Do the arrays overlap, that is, have any elements in common?
20356 </para>
20357 <para>
20358 <literal>ARRAY[1,4,3] &amp;&amp; ARRAY[2,1]</literal>
20359 <returnvalue>t</returnvalue>
20360 </para></entry>
20361 </row>
20362
20363 <row>
20364 <entry role="func_table_entry"><para role="func_signature">
20365 <type>anycompatiblearray</type> <literal>||</literal> <type>anycompatiblearray</type>
20366 <returnvalue>anycompatiblearray</returnvalue>
20367 </para>
20368 <para>
20369 Concatenates the two arrays. Concatenating a null or empty array is a
20370 no-op; otherwise the arrays must have the same number of dimensions
20371 (as illustrated by the first example) or differ in number of
20372 dimensions by one (as illustrated by the second).
20373 If the arrays are not of identical element types, they will be coerced
20374 to a common type (see <xref linkend="typeconv-union-case"/>).
20375 </para>
20376 <para>
20377 <literal>ARRAY[1,2,3] || ARRAY[4,5,6,7]</literal>
20378 <returnvalue>{1,2,3,4,5,6,7}</returnvalue>
20379 </para>
20380 <para>
20381 <literal>ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9.9]]</literal>
20382 <returnvalue>{{1,2,3},{4,5,6},{7,8,9.9}}</returnvalue>
20383 </para></entry>
20384 </row>
20385
20386 <row>
20387 <entry role="func_table_entry"><para role="func_signature">
20388 <type>anycompatible</type> <literal>||</literal> <type>anycompatiblearray</type>
20389 <returnvalue>anycompatiblearray</returnvalue>
20390 </para>
20391 <para>
20392 Concatenates an element onto the front of an array (which must be
20393 empty or one-dimensional).
20394 </para>
20395 <para>
20396 <literal>3 || ARRAY[4,5,6]</literal>
20397 <returnvalue>{3,4,5,6}</returnvalue>
20398 </para></entry>
20399 </row>
20400
20401 <row>
20402 <entry role="func_table_entry"><para role="func_signature">
20403 <type>anycompatiblearray</type> <literal>||</literal> <type>anycompatible</type>
20404 <returnvalue>anycompatiblearray</returnvalue>
20405 </para>
20406 <para>
20407 Concatenates an element onto the end of an array (which must be
20408 empty or one-dimensional).
20409 </para>
20410 <para>
20411 <literal>ARRAY[4,5,6] || 7</literal>
20412 <returnvalue>{4,5,6,7}</returnvalue>
20413 </para></entry>
20414 </row>
20415 </tbody>
20416 </tgroup>
20417 </table>
20418
20419 <para>
20420 See <xref linkend="arrays"/> for more details about array operator
20421 behavior. See <xref linkend="indexes-types"/> for more details about
20422 which operators support indexed operations.
20423 </para>
20424
20425 <para>
20426 <xref linkend="array-functions-table"/> shows the functions
20427 available for use with array types. See <xref linkend="arrays"/>
20428 for more information and examples of the use of these functions.
20429 </para>
20430
20431 <table id="array-functions-table">
20432 <title>Array Functions</title>
20433 <tgroup cols="1">
20434 <thead>
20435 <row>
20436 <entry role="func_table_entry"><para role="func_signature">
20437 Function
20438 </para>
20439 <para>
20440 Description
20441 </para>
20442 <para>
20443 Example(s)
20444 </para></entry>
20445 </row>
20446 </thead>
20447
20448 <tbody>
20449 <row>
20450 <entry role="func_table_entry"><para role="func_signature">
20451 <indexterm>
20452 <primary>array_append</primary>
20453 </indexterm>
20454 <function>array_append</function> ( <type>anycompatiblearray</type>, <type>anycompatible</type> )
20455 <returnvalue>anycompatiblearray</returnvalue>
20456 </para>
20457 <para>
20458 Appends an element to the end of an array (same as
20459 the <type>anycompatiblearray</type> <literal>||</literal> <type>anycompatible</type>
20460 operator).
20461 </para>
20462 <para>
20463 <literal>array_append(ARRAY[1,2], 3)</literal>
20464 <returnvalue>{1,2,3}</returnvalue>
20465 </para></entry>
20466 </row>
20467
20468 <row>
20469 <entry role="func_table_entry"><para role="func_signature">
20470 <indexterm>
20471 <primary>array_cat</primary>
20472 </indexterm>
20473 <function>array_cat</function> ( <type>anycompatiblearray</type>, <type>anycompatiblearray</type> )
20474 <returnvalue>anycompatiblearray</returnvalue>
20475 </para>
20476 <para>
20477 Concatenates two arrays (same as
20478 the <type>anycompatiblearray</type> <literal>||</literal> <type>anycompatiblearray</type>
20479 operator).
20480 </para>
20481 <para>
20482 <literal>array_cat(ARRAY[1,2,3], ARRAY[4,5])</literal>
20483 <returnvalue>{1,2,3,4,5}</returnvalue>
20484 </para></entry>
20485 </row>
20486
20487 <row>
20488 <entry role="func_table_entry"><para role="func_signature">
20489 <indexterm>
20490 <primary>array_dims</primary>
20491 </indexterm>
20492 <function>array_dims</function> ( <type>anyarray</type> )
20493 <returnvalue>text</returnvalue>
20494 </para>
20495 <para>
20496 Returns a text representation of the array's dimensions.
20497 </para>
20498 <para>
20499 <literal>array_dims(ARRAY[[1,2,3], [4,5,6]])</literal>
20500 <returnvalue>[1:2][1:3]</returnvalue>
20501 </para></entry>
20502 </row>
20503
20504 <row>
20505 <entry role="func_table_entry"><para role="func_signature">
20506 <indexterm>
20507 <primary>array_fill</primary>
20508 </indexterm>
20509 <function>array_fill</function> ( <type>anyelement</type>, <type>integer[]</type>
20510 <optional>, <type>integer[]</type> </optional> )
20511 <returnvalue>anyarray</returnvalue>
20512 </para>
20513 <para>
20514 Returns an array filled with copies of the given value, having
20515 dimensions of the lengths specified by the second argument.
20516 The optional third argument supplies lower-bound values for each
20517 dimension (which default to all <literal>1</literal>).
20518 </para>
20519 <para>
20520 <literal>array_fill(11, ARRAY[2,3])</literal>
20521 <returnvalue>{{11,11,11},{11,11,11}}</returnvalue>
20522 </para>
20523 <para>
20524 <literal>array_fill(7, ARRAY[3], ARRAY[2])</literal>
20525 <returnvalue>[2:4]={7,7,7}</returnvalue>
20526 </para></entry>
20527 </row>
20528
20529 <row>
20530 <entry role="func_table_entry"><para role="func_signature">
20531 <indexterm>
20532 <primary>array_length</primary>
20533 </indexterm>
20534 <function>array_length</function> ( <type>anyarray</type>, <type>integer</type> )
20535 <returnvalue>integer</returnvalue>
20536 </para>
20537 <para>
20538 Returns the length of the requested array dimension.
20539 (Produces NULL instead of 0 for empty or missing array dimensions.)
20540 </para>
20541 <para>
20542 <literal>array_length(array[1,2,3], 1)</literal>
20543 <returnvalue>3</returnvalue>
20544 </para>
20545 <para>
20546 <literal>array_length(array[]::int[], 1)</literal>
20547 <returnvalue>NULL</returnvalue>
20548 </para>
20549 <para>
20550 <literal>array_length(array['text'], 2)</literal>
20551 <returnvalue>NULL</returnvalue>
20552 </para></entry>
20553 </row>
20554
20555 <row>
20556 <entry role="func_table_entry"><para role="func_signature">
20557 <indexterm>
20558 <primary>array_lower</primary>
20559 </indexterm>
20560 <function>array_lower</function> ( <type>anyarray</type>, <type>integer</type> )
20561 <returnvalue>integer</returnvalue>
20562 </para>
20563 <para>
20564 Returns the lower bound of the requested array dimension.
20565 </para>
20566 <para>
20567 <literal>array_lower('[0:2]={1,2,3}'::integer[], 1)</literal>
20568 <returnvalue>0</returnvalue>
20569 </para></entry>
20570 </row>
20571
20572 <row>
20573 <entry role="func_table_entry"><para role="func_signature">
20574 <indexterm>
20575 <primary>array_ndims</primary>
20576 </indexterm>
20577 <function>array_ndims</function> ( <type>anyarray</type> )
20578 <returnvalue>integer</returnvalue>
20579 </para>
20580 <para>
20581 Returns the number of dimensions of the array.
20582 </para>
20583 <para>
20584 <literal>array_ndims(ARRAY[[1,2,3], [4,5,6]])</literal>
20585 <returnvalue>2</returnvalue>
20586 </para></entry>
20587 </row>
20588
20589 <row>
20590 <entry role="func_table_entry"><para role="func_signature">
20591 <indexterm>
20592 <primary>array_position</primary>
20593 </indexterm>
20594 <function>array_position</function> ( <type>anycompatiblearray</type>, <type>anycompatible</type> <optional>, <type>integer</type> </optional> )
20595 <returnvalue>integer</returnvalue>
20596 </para>
20597 <para>
20598 Returns the subscript of the first occurrence of the second argument
20599 in the array, or <literal>NULL</literal> if it's not present.
20600 If the third argument is given, the search begins at that subscript.
20601 The array must be one-dimensional.
20602 Comparisons are done using <literal>IS NOT DISTINCT FROM</literal>
20603 semantics, so it is possible to search for <literal>NULL</literal>.
20604 </para>
20605 <para>
20606 <literal>array_position(ARRAY['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'], 'mon')</literal>
20607 <returnvalue>2</returnvalue>
20608 </para></entry>
20609 </row>
20610
20611 <row>
20612 <entry role="func_table_entry"><para role="func_signature">
20613 <indexterm>
20614 <primary>array_positions</primary>
20615 </indexterm>
20616 <function>array_positions</function> ( <type>anycompatiblearray</type>, <type>anycompatible</type> )
20617 <returnvalue>integer[]</returnvalue>
20618 </para>
20619 <para>
20620 Returns an array of the subscripts of all occurrences of the second
20621 argument in the array given as first argument.
20622 The array must be one-dimensional.
20623 Comparisons are done using <literal>IS NOT DISTINCT FROM</literal>
20624 semantics, so it is possible to search for <literal>NULL</literal>.
20625 <literal>NULL</literal> is returned only if the array
20626 is <literal>NULL</literal>; if the value is not found in the array, an
20627 empty array is returned.
20628 </para>
20629 <para>
20630 <literal>array_positions(ARRAY['A','A','B','A'], 'A')</literal>
20631 <returnvalue>{1,2,4}</returnvalue>
20632 </para></entry>
20633 </row>
20634
20635 <row>
20636 <entry role="func_table_entry"><para role="func_signature">
20637 <indexterm>
20638 <primary>array_prepend</primary>
20639 </indexterm>
20640 <function>array_prepend</function> ( <type>anycompatible</type>, <type>anycompatiblearray</type> )
20641 <returnvalue>anycompatiblearray</returnvalue>
20642 </para>
20643 <para>
20644 Prepends an element to the beginning of an array (same as
20645 the <type>anycompatible</type> <literal>||</literal> <type>anycompatiblearray</type>
20646 operator).
20647 </para>
20648 <para>
20649 <literal>array_prepend(1, ARRAY[2,3])</literal>
20650 <returnvalue>{1,2,3}</returnvalue>
20651 </para></entry>
20652 </row>
20653
20654 <row>
20655 <entry role="func_table_entry"><para role="func_signature">
20656 <indexterm>
20657 <primary>array_remove</primary>
20658 </indexterm>
20659 <function>array_remove</function> ( <type>anycompatiblearray</type>, <type>anycompatible</type> )
20660 <returnvalue>anycompatiblearray</returnvalue>
20661 </para>
20662 <para>
20663 Removes all elements equal to the given value from the array.
20664 The array must be one-dimensional.
20665 Comparisons are done using <literal>IS NOT DISTINCT FROM</literal>
20666 semantics, so it is possible to remove <literal>NULL</literal>s.
20667 </para>
20668 <para>
20669 <literal>array_remove(ARRAY[1,2,3,2], 2)</literal>
20670 <returnvalue>{1,3}</returnvalue>
20671 </para></entry>
20672 </row>
20673
20674 <row>
20675 <entry role="func_table_entry"><para role="func_signature">
20676 <indexterm>
20677 <primary>array_replace</primary>
20678 </indexterm>
20679 <function>array_replace</function> ( <type>anycompatiblearray</type>, <type>anycompatible</type>, <type>anycompatible</type> )
20680 <returnvalue>anycompatiblearray</returnvalue>
20681 </para>
20682 <para>
20683 Replaces each array element equal to the second argument with the
20684 third argument.
20685 </para>
20686 <para>
20687 <literal>array_replace(ARRAY[1,2,5,4], 5, 3)</literal>
20688 <returnvalue>{1,2,3,4}</returnvalue>
20689 </para></entry>
20690 </row>
20691
20692 <row>
20693 <entry role="func_table_entry"><para role="func_signature">
20694 <indexterm>
20695 <primary>array_reverse</primary>
20696 </indexterm>
20697 <function>array_reverse</function> ( <type>anyarray</type> )
20698 <returnvalue>anyarray</returnvalue>
20699 </para>
20700 <para>
20701 Reverses the first dimension of the array.
20702 </para>
20703 <para>
20704 <literal>array_reverse(ARRAY[[1,2],[3,4],[5,6]])</literal>
20705 <returnvalue>{{5,6},{3,4},{1,2}}</returnvalue>
20706 </para></entry>
20707 </row>
20708
20709 <row>
20710 <entry role="func_table_entry"><para role="func_signature">
20711 <indexterm>
20712 <primary>array_sample</primary>
20713 </indexterm>
20714 <function>array_sample</function> ( <parameter>array</parameter> <type>anyarray</type>, <parameter>n</parameter> <type>integer</type> )
20715 <returnvalue>anyarray</returnvalue>
20716 </para>
20717 <para>
20718 Returns an array of <parameter>n</parameter> items randomly selected
20719 from <parameter>array</parameter>. <parameter>n</parameter> may not
20720 exceed the length of <parameter>array</parameter>'s first dimension.
20721 If <parameter>array</parameter> is multi-dimensional,
20722 an <quote>item</quote> is a slice having a given first subscript.
20723 </para>
20724 <para>
20725 <literal>array_sample(ARRAY[1,2,3,4,5,6], 3)</literal>
20726 <returnvalue>{2,6,1}</returnvalue>
20727 </para>
20728 <para>
20729 <literal>array_sample(ARRAY[[1,2],[3,4],[5,6]], 2)</literal>
20730 <returnvalue>{{5,6},{1,2}}</returnvalue>
20731 </para></entry>
20732 </row>
20733
20734 <row>
20735 <entry role="func_table_entry"><para role="func_signature">
20736 <indexterm>
20737 <primary>array_shuffle</primary>
20738 </indexterm>
20739 <function>array_shuffle</function> ( <type>anyarray</type> )
20740 <returnvalue>anyarray</returnvalue>
20741 </para>
20742 <para>
20743 Randomly shuffles the first dimension of the array.
20744 </para>
20745 <para>
20746 <literal>array_shuffle(ARRAY[[1,2],[3,4],[5,6]])</literal>
20747 <returnvalue>{{5,6},{1,2},{3,4}}</returnvalue>
20748 </para></entry>
20749 </row>
20750
20751 <row>
20752 <entry role="func_table_entry"><para role="func_signature">
20753 <indexterm>
20754 <primary>array_sort</primary>
20755 </indexterm>
20756 <function>array_sort</function> (
20757 <parameter>array</parameter> <type>anyarray</type>
20758 <optional>, <parameter>descending</parameter> <type>boolean</type>
20759 <optional>, <parameter>nulls_first</parameter> <type>boolean</type>
20760 </optional></optional> )
20761 <returnvalue>anyarray</returnvalue>
20762 </para>
20763 <para>
20764 Sorts the first dimension of the array.
20765 The sort order is determined by the default sort ordering of the
20766 array's element type; however, if the element type is collatable,
20767 the collation to use can be specified by adding
20768 a <literal>COLLATE</literal> clause to
20769 the <parameter>array</parameter> argument.
20770 </para>
20771 <para>
20772 If <parameter>descending</parameter> is true then sort in
20773 descending order, otherwise ascending order. If omitted, the
20774 default is ascending order.
20775 If <parameter>nulls_first</parameter> is true then nulls appear
20776 before non-null values, otherwise nulls appear after non-null
20777 values.
20778 If omitted, <parameter>nulls_first</parameter> is taken to have
20779 the same value as <parameter>descending</parameter>.
20780 </para>
20781 <para>
20782 <literal>array_sort(ARRAY[[2,4],[2,1],[6,5]])</literal>
20783 <returnvalue>{{2,1},{2,4},{6,5}}</returnvalue>
20784 </para></entry>
20785 </row>
20786
20787 <row>
20788 <entry role="func_table_entry"><para role="func_signature">
20789 <indexterm id="function-array-to-string">
20790 <primary>array_to_string</primary>
20791 </indexterm>
20792 <function>array_to_string</function> ( <parameter>array</parameter> <type>anyarray</type>, <parameter>delimiter</parameter> <type>text</type> <optional>, <parameter>null_string</parameter> <type>text</type> </optional> )
20793 <returnvalue>text</returnvalue>
20794 </para>
20795 <para>
20796 Converts each array element to its text representation, and
20797 concatenates those separated by
20798 the <parameter>delimiter</parameter> string.
20799 If <parameter>null_string</parameter> is given and is
20800 not <literal>NULL</literal>, then <literal>NULL</literal> array
20801 entries are represented by that string; otherwise, they are omitted.
20802 See also <link linkend="function-string-to-array"><function>string_to_array</function></link>.
20803 </para>
20804 <para>
20805 <literal>array_to_string(ARRAY[1, 2, 3, NULL, 5], ',', '*')</literal>
20806 <returnvalue>1,2,3,*,5</returnvalue>
20807 </para></entry>
20808 </row>
20809
20810 <row>
20811 <entry role="func_table_entry"><para role="func_signature">
20812 <indexterm>
20813 <primary>array_upper</primary>
20814 </indexterm>
20815 <function>array_upper</function> ( <type>anyarray</type>, <type>integer</type> )
20816 <returnvalue>integer</returnvalue>
20817 </para>
20818 <para>
20819 Returns the upper bound of the requested array dimension.
20820 </para>
20821 <para>
20822 <literal>array_upper(ARRAY[1,8,3,7], 1)</literal>
20823 <returnvalue>4</returnvalue>
20824 </para></entry>
20825 </row>
20826
20827 <row>
20828 <entry role="func_table_entry"><para role="func_signature">
20829 <indexterm>
20830 <primary>cardinality</primary>
20831 </indexterm>
20832 <function>cardinality</function> ( <type>anyarray</type> )
20833 <returnvalue>integer</returnvalue>
20834 </para>
20835 <para>
20836 Returns the total number of elements in the array, or 0 if the array
20837 is empty.
20838 </para>
20839 <para>
20840 <literal>cardinality(ARRAY[[1,2],[3,4]])</literal>
20841 <returnvalue>4</returnvalue>
20842 </para></entry>
20843 </row>
20844
20845 <row>
20846 <entry role="func_table_entry"><para role="func_signature">
20847 <indexterm>
20848 <primary>trim_array</primary>
20849 </indexterm>
20850 <function>trim_array</function> ( <parameter>array</parameter> <type>anyarray</type>, <parameter>n</parameter> <type>integer</type> )
20851 <returnvalue>anyarray</returnvalue>
20852 </para>
20853 <para>
20854 Trims an array by removing the last <parameter>n</parameter> elements.
20855 If the array is multidimensional, only the first dimension is trimmed.
20856 </para>
20857 <para>
20858 <literal>trim_array(ARRAY[1,2,3,4,5,6], 2)</literal>
20859 <returnvalue>{1,2,3,4}</returnvalue>
20860 </para></entry>
20861 </row>
20862
20863 <row>
20864 <entry role="func_table_entry"><para role="func_signature">
20865 <indexterm>
20866 <primary>unnest</primary>
20867 </indexterm>
20868 <function>unnest</function> ( <type>anyarray</type> )
20869 <returnvalue>setof anyelement</returnvalue>
20870 </para>
20871 <para>
20872 Expands an array into a set of rows.
20873 The array's elements are read out in storage order.
20874 </para>
20875 <para>
20876 <literal>unnest(ARRAY[1,2])</literal>
20877 <returnvalue></returnvalue>
20878 <programlisting>
20879 1
20880 2
20881 </programlisting>
20882 </para>
20883 <para>
20884 <literal>unnest(ARRAY[['foo','bar'],['baz','quux']])</literal>
20885 <returnvalue></returnvalue>
20886 <programlisting>
20887 foo
20888 bar
20889 baz
20890 quux
20891 </programlisting>
20892 </para></entry>
20893 </row>
20894
20895 <row>
20896 <entry role="func_table_entry"><para role="func_signature">
20897 <function>unnest</function> ( <type>anyarray</type>, <type>anyarray</type> <optional>, ... </optional> )
20898 <returnvalue>setof anyelement, anyelement [, ... ]</returnvalue>
20899 </para>
20900 <para>
20901 Expands multiple arrays (possibly of different data types) into a set of
20902 rows. If the arrays are not all the same length then the shorter ones
20903 are padded with <literal>NULL</literal>s. This form is only allowed
20904 in a query's FROM clause; see <xref linkend="queries-tablefunctions"/>.
20905 </para>
20906 <para>
20907 <literal>select * from unnest(ARRAY[1,2], ARRAY['foo','bar','baz']) as x(a,b)</literal>
20908 <returnvalue></returnvalue>
20909 <programlisting>
20910 a | b
20911 ---+-----
20912 1 | foo
20913 2 | bar
20914 | baz
20915 </programlisting>
20916 </para></entry>
20917 </row>
20918 </tbody>
20919 </tgroup>
20920 </table>
20921
20922 <para>
20923 See also <xref linkend="functions-aggregate"/> about the aggregate
20924 function <function>array_agg</function> for use with arrays.
20925 </para>
20926 </sect1>
20927
20928 <sect1 id="functions-range">
20929 <title>Range/Multirange Functions and Operators</title>
20930
20931 <para>
20932 See <xref linkend="rangetypes"/> for an overview of range types.
20933 </para>
20934
20935 <para>
20936 <xref linkend="range-operators-table"/> shows the specialized operators
20937 available for range types.
20938 <xref linkend="multirange-operators-table"/> shows the specialized operators
20939 available for multirange types.
20940 In addition to those, the usual comparison operators shown in
20941 <xref linkend="functions-comparison-op-table"/> are available for range
20942 and multirange types. The comparison operators order first by the range lower
20943 bounds, and only if those are equal do they compare the upper bounds. The
20944 multirange operators compare each range until one is unequal. This
20945 does not usually result in a useful overall ordering, but the operators are
20946 provided to allow unique indexes to be constructed on ranges.
20947 </para>
20948
20949 <table id="range-operators-table">
20950 <title>Range Operators</title>
20951 <tgroup cols="1">
20952 <thead>
20953 <row>
20954 <entry role="func_table_entry"><para role="func_signature">
20955 Operator
20956 </para>
20957 <para>
20958 Description
20959 </para>
20960 <para>
20961 Example(s)
20962 </para></entry>
20963 </row>
20964 </thead>
20965
20966 <tbody>
20967 <row>
20968 <entry role="func_table_entry"><para role="func_signature">
20969 <type>anyrange</type> <literal>@&gt;</literal> <type>anyrange</type>
20970 <returnvalue>boolean</returnvalue>
20971 </para>
20972 <para>
20973 Does the first range contain the second?
20974 </para>
20975 <para>
20976 <literal>int4range(2,4) @&gt; int4range(2,3)</literal>
20977 <returnvalue>t</returnvalue>
20978 </para></entry>
20979 </row>
20980
20981 <row>
20982 <entry role="func_table_entry"><para role="func_signature">
20983 <type>anyrange</type> <literal>@&gt;</literal> <type>anyelement</type>
20984 <returnvalue>boolean</returnvalue>
20985 </para>
20986 <para>
20987 Does the range contain the element?
20988 </para>
20989 <para>
20990 <literal>'[2011-01-01,2011-03-01)'::tsrange @&gt; '2011-01-10'::timestamp</literal>
20991 <returnvalue>t</returnvalue>
20992 </para></entry>
20993 </row>
20994
20995 <row>
20996 <entry role="func_table_entry"><para role="func_signature">
20997 <type>anyrange</type> <literal>&lt;@</literal> <type>anyrange</type>
20998 <returnvalue>boolean</returnvalue>
20999 </para>
21000 <para>
21001 Is the first range contained by the second?
21002 </para>
21003 <para>
21004 <literal>int4range(2,4) &lt;@ int4range(1,7)</literal>
21005 <returnvalue>t</returnvalue>
21006 </para></entry>
21007 </row>
21008
21009 <row>
21010 <entry role="func_table_entry"><para role="func_signature">
21011 <type>anyelement</type> <literal>&lt;@</literal> <type>anyrange</type>
21012 <returnvalue>boolean</returnvalue>
21013 </para>
21014 <para>
21015 Is the element contained in the range?
21016 </para>
21017 <para>
21018 <literal>42 &lt;@ int4range(1,7)</literal>
21019 <returnvalue>f</returnvalue>
21020 </para></entry>
21021 </row>
21022
21023 <row>
21024 <entry role="func_table_entry"><para role="func_signature">
21025 <type>anyrange</type> <literal>&amp;&amp;</literal> <type>anyrange</type>
21026 <returnvalue>boolean</returnvalue>
21027 </para>
21028 <para>
21029 Do the ranges overlap, that is, have any elements in common?
21030 </para>
21031 <para>
21032 <literal>int8range(3,7) &amp;&amp; int8range(4,12)</literal>
21033 <returnvalue>t</returnvalue>
21034 </para></entry>
21035 </row>
21036
21037 <row>
21038 <entry role="func_table_entry"><para role="func_signature">
21039 <type>anyrange</type> <literal>&lt;&lt;</literal> <type>anyrange</type>
21040 <returnvalue>boolean</returnvalue>
21041 </para>
21042 <para>
21043 Is the first range strictly left of the second?
21044 </para>
21045 <para>
21046 <literal>int8range(1,10) &lt;&lt; int8range(100,110)</literal>
21047 <returnvalue>t</returnvalue>
21048 </para></entry>
21049 </row>
21050
21051 <row>
21052 <entry role="func_table_entry"><para role="func_signature">
21053 <type>anyrange</type> <literal>&gt;&gt;</literal> <type>anyrange</type>
21054 <returnvalue>boolean</returnvalue>
21055 </para>
21056 <para>
21057 Is the first range strictly right of the second?
21058 </para>
21059 <para>
21060 <literal>int8range(50,60) &gt;&gt; int8range(20,30)</literal>
21061 <returnvalue>t</returnvalue>
21062 </para></entry>
21063 </row>
21064
21065 <row>
21066 <entry role="func_table_entry"><para role="func_signature">
21067 <type>anyrange</type> <literal>&amp;&lt;</literal> <type>anyrange</type>
21068 <returnvalue>boolean</returnvalue>
21069 </para>
21070 <para>
21071 Does the first range not extend to the right of the second?
21072 </para>
21073 <para>
21074 <literal>int8range(1,20) &amp;&lt; int8range(18,20)</literal>
21075 <returnvalue>t</returnvalue>
21076 </para></entry>
21077 </row>
21078
21079 <row>
21080 <entry role="func_table_entry"><para role="func_signature">
21081 <type>anyrange</type> <literal>&amp;&gt;</literal> <type>anyrange</type>
21082 <returnvalue>boolean</returnvalue>
21083 </para>
21084 <para>
21085 Does the first range not extend to the left of the second?
21086 </para>
21087 <para>
21088 <literal>int8range(7,20) &amp;&gt; int8range(5,10)</literal>
21089 <returnvalue>t</returnvalue>
21090 </para></entry>
21091 </row>
21092
21093 <row>
21094 <entry role="func_table_entry"><para role="func_signature">
21095 <type>anyrange</type> <literal>-|-</literal> <type>anyrange</type>
21096 <returnvalue>boolean</returnvalue>
21097 </para>
21098 <para>
21099 Are the ranges adjacent?
21100 </para>
21101 <para>
21102 <literal>numrange(1.1,2.2) -|- numrange(2.2,3.3)</literal>
21103 <returnvalue>t</returnvalue>
21104 </para></entry>
21105 </row>
21106
21107 <row>
21108 <entry role="func_table_entry"><para role="func_signature">
21109 <type>anyrange</type> <literal>+</literal> <type>anyrange</type>
21110 <returnvalue>anyrange</returnvalue>
21111 </para>
21112 <para>
21113 Computes the union of the ranges. The ranges must overlap or be
21114 adjacent, so that the union is a single range (but
21115 see <function>range_merge()</function>).
21116 </para>
21117 <para>
21118 <literal>numrange(5,15) + numrange(10,20)</literal>
21119 <returnvalue>[5,20)</returnvalue>
21120 </para></entry>
21121 </row>
21122
21123 <row>
21124 <entry role="func_table_entry"><para role="func_signature">
21125 <type>anyrange</type> <literal>*</literal> <type>anyrange</type>
21126 <returnvalue>anyrange</returnvalue>
21127 </para>
21128 <para>
21129 Computes the intersection of the ranges.
21130 </para>
21131 <para>
21132 <literal>int8range(5,15) * int8range(10,20)</literal>
21133 <returnvalue>[10,15)</returnvalue>
21134 </para></entry>
21135 </row>
21136
21137 <row>
21138 <entry role="func_table_entry"><para role="func_signature">
21139 <type>anyrange</type> <literal>-</literal> <type>anyrange</type>
21140 <returnvalue>anyrange</returnvalue>
21141 </para>
21142 <para>
21143 Computes the difference of the ranges. The second range must not be
21144 contained in the first in such a way that the difference would not be
21145 a single range.
21146 </para>
21147 <para>
21148 <literal>int8range(5,15) - int8range(10,20)</literal>
21149 <returnvalue>[5,10)</returnvalue>
21150 </para></entry>
21151 </row>
21152 </tbody>
21153 </tgroup>
21154 </table>
21155
21156 <table id="multirange-operators-table">
21157 <title>Multirange Operators</title>
21158 <tgroup cols="1">
21159 <thead>
21160 <row>
21161 <entry role="func_table_entry"><para role="func_signature">
21162 Operator
21163 </para>
21164 <para>
21165 Description
21166 </para>
21167 <para>
21168 Example(s)
21169 </para></entry>
21170 </row>
21171 </thead>
21172
21173 <tbody>
21174 <row>
21175 <entry role="func_table_entry"><para role="func_signature">
21176 <type>anymultirange</type> <literal>@&gt;</literal> <type>anymultirange</type>
21177 <returnvalue>boolean</returnvalue>
21178 </para>
21179 <para>
21180 Does the first multirange contain the second?
21181 </para>
21182 <para>
21183 <literal>'{[2,4)}'::int4multirange @&gt; '{[2,3)}'::int4multirange</literal>
21184 <returnvalue>t</returnvalue>
21185 </para></entry>
21186 </row>
21187
21188 <row>
21189 <entry role="func_table_entry"><para role="func_signature">
21190 <type>anymultirange</type> <literal>@&gt;</literal> <type>anyrange</type>
21191 <returnvalue>boolean</returnvalue>
21192 </para>
21193 <para>
21194 Does the multirange contain the range?
21195 </para>
21196 <para>
21197 <literal>'{[2,4)}'::int4multirange @&gt; int4range(2,3)</literal>
21198 <returnvalue>t</returnvalue>
21199 </para></entry>
21200 </row>
21201
21202 <row>
21203 <entry role="func_table_entry"><para role="func_signature">
21204 <type>anymultirange</type> <literal>@&gt;</literal> <type>anyelement</type>
21205 <returnvalue>boolean</returnvalue>
21206 </para>
21207 <para>
21208 Does the multirange contain the element?
21209 </para>
21210 <para>
21211 <literal>'{[2011-01-01,2011-03-01)}'::tsmultirange @&gt; '2011-01-10'::timestamp</literal>
21212 <returnvalue>t</returnvalue>
21213 </para></entry>
21214 </row>
21215
21216 <row>
21217 <entry role="func_table_entry"><para role="func_signature">
21218 <type>anyrange</type> <literal>@&gt;</literal> <type>anymultirange</type>
21219 <returnvalue>boolean</returnvalue>
21220 </para>
21221 <para>
21222 Does the range contain the multirange?
21223 </para>
21224 <para>
21225 <literal>'[2,4)'::int4range @&gt; '{[2,3)}'::int4multirange</literal>
21226 <returnvalue>t</returnvalue>
21227 </para></entry>
21228 </row>
21229
21230 <row>
21231 <entry role="func_table_entry"><para role="func_signature">
21232 <type>anymultirange</type> <literal>&lt;@</literal> <type>anymultirange</type>
21233 <returnvalue>boolean</returnvalue>
21234 </para>
21235 <para>
21236 Is the first multirange contained by the second?
21237 </para>
21238 <para>
21239 <literal>'{[2,4)}'::int4multirange &lt;@ '{[1,7)}'::int4multirange</literal>
21240 <returnvalue>t</returnvalue>
21241 </para></entry>
21242 </row>
21243
21244 <row>
21245 <entry role="func_table_entry"><para role="func_signature">
21246 <type>anymultirange</type> <literal>&lt;@</literal> <type>anyrange</type>
21247 <returnvalue>boolean</returnvalue>
21248 </para>
21249 <para>
21250 Is the multirange contained by the range?
21251 </para>
21252 <para>
21253 <literal>'{[2,4)}'::int4multirange &lt;@ int4range(1,7)</literal>
21254 <returnvalue>t</returnvalue>
21255 </para></entry>
21256 </row>
21257
21258 <row>
21259 <entry role="func_table_entry"><para role="func_signature">
21260 <type>anyrange</type> <literal>&lt;@</literal> <type>anymultirange</type>
21261 <returnvalue>boolean</returnvalue>
21262 </para>
21263 <para>
21264 Is the range contained by the multirange?
21265 </para>
21266 <para>
21267 <literal>int4range(2,4) &lt;@ '{[1,7)}'::int4multirange</literal>
21268 <returnvalue>t</returnvalue>
21269 </para></entry>
21270 </row>
21271
21272 <row>
21273 <entry role="func_table_entry"><para role="func_signature">
21274 <type>anyelement</type> <literal>&lt;@</literal> <type>anymultirange</type>
21275 <returnvalue>boolean</returnvalue>
21276 </para>
21277 <para>
21278 Is the element contained by the multirange?
21279 </para>
21280 <para>
21281 <literal>4 &lt;@ '{[1,7)}'::int4multirange</literal>
21282 <returnvalue>t</returnvalue>
21283 </para></entry>
21284 </row>
21285
21286 <row>
21287 <entry role="func_table_entry"><para role="func_signature">
21288 <type>anymultirange</type> <literal>&amp;&amp;</literal> <type>anymultirange</type>
21289 <returnvalue>boolean</returnvalue>
21290 </para>
21291 <para>
21292 Do the multiranges overlap, that is, have any elements in common?
21293 </para>
21294 <para>
21295 <literal>'{[3,7)}'::int8multirange &amp;&amp; '{[4,12)}'::int8multirange</literal>
21296 <returnvalue>t</returnvalue>
21297 </para></entry>
21298 </row>
21299
21300 <row>
21301 <entry role="func_table_entry"><para role="func_signature">
21302 <type>anymultirange</type> <literal>&amp;&amp;</literal> <type>anyrange</type>
21303 <returnvalue>boolean</returnvalue>
21304 </para>
21305 <para>
21306 Does the multirange overlap the range?
21307 </para>
21308 <para>
21309 <literal>'{[3,7)}'::int8multirange &amp;&amp; int8range(4,12)</literal>
21310 <returnvalue>t</returnvalue>
21311 </para></entry>
21312 </row>
21313
21314 <row>
21315 <entry role="func_table_entry"><para role="func_signature">
21316 <type>anyrange</type> <literal>&amp;&amp;</literal> <type>anymultirange</type>
21317 <returnvalue>boolean</returnvalue>
21318 </para>
21319 <para>
21320 Does the range overlap the multirange?
21321 </para>
21322 <para>
21323 <literal>int8range(3,7) &amp;&amp; '{[4,12)}'::int8multirange</literal>
21324 <returnvalue>t</returnvalue>
21325 </para></entry>
21326 </row>
21327
21328 <row>
21329 <entry role="func_table_entry"><para role="func_signature">
21330 <type>anymultirange</type> <literal>&lt;&lt;</literal> <type>anymultirange</type>
21331 <returnvalue>boolean</returnvalue>
21332 </para>
21333 <para>
21334 Is the first multirange strictly left of the second?
21335 </para>
21336 <para>
21337 <literal>'{[1,10)}'::int8multirange &lt;&lt; '{[100,110)}'::int8multirange</literal>
21338 <returnvalue>t</returnvalue>
21339 </para></entry>
21340 </row>
21341
21342 <row>
21343 <entry role="func_table_entry"><para role="func_signature">
21344 <type>anymultirange</type> <literal>&lt;&lt;</literal> <type>anyrange</type>
21345 <returnvalue>boolean</returnvalue>
21346 </para>
21347 <para>
21348 Is the multirange strictly left of the range?
21349 </para>
21350 <para>
21351 <literal>'{[1,10)}'::int8multirange &lt;&lt; int8range(100,110)</literal>
21352 <returnvalue>t</returnvalue>
21353 </para></entry>
21354 </row>
21355
21356 <row>
21357 <entry role="func_table_entry"><para role="func_signature">
21358 <type>anyrange</type> <literal>&lt;&lt;</literal> <type>anymultirange</type>
21359 <returnvalue>boolean</returnvalue>
21360 </para>
21361 <para>
21362 Is the range strictly left of the multirange?
21363 </para>
21364 <para>
21365 <literal>int8range(1,10) &lt;&lt; '{[100,110)}'::int8multirange</literal>
21366 <returnvalue>t</returnvalue>
21367 </para></entry>
21368 </row>
21369
21370 <row>
21371 <entry role="func_table_entry"><para role="func_signature">
21372 <type>anymultirange</type> <literal>&gt;&gt;</literal> <type>anymultirange</type>
21373 <returnvalue>boolean</returnvalue>
21374 </para>
21375 <para>
21376 Is the first multirange strictly right of the second?
21377 </para>
21378 <para>
21379 <literal>'{[50,60)}'::int8multirange &gt;&gt; '{[20,30)}'::int8multirange</literal>
21380 <returnvalue>t</returnvalue>
21381 </para></entry>
21382 </row>
21383
21384 <row>
21385 <entry role="func_table_entry"><para role="func_signature">
21386 <type>anymultirange</type> <literal>&gt;&gt;</literal> <type>anyrange</type>
21387 <returnvalue>boolean</returnvalue>
21388 </para>
21389 <para>
21390 Is the multirange strictly right of the range?
21391 </para>
21392 <para>
21393 <literal>'{[50,60)}'::int8multirange &gt;&gt; int8range(20,30)</literal>
21394 <returnvalue>t</returnvalue>
21395 </para></entry>
21396 </row>
21397
21398 <row>
21399 <entry role="func_table_entry"><para role="func_signature">
21400 <type>anyrange</type> <literal>&gt;&gt;</literal> <type>anymultirange</type>
21401 <returnvalue>boolean</returnvalue>
21402 </para>
21403 <para>
21404 Is the range strictly right of the multirange?
21405 </para>
21406 <para>
21407 <literal>int8range(50,60) &gt;&gt; '{[20,30)}'::int8multirange</literal>
21408 <returnvalue>t</returnvalue>
21409 </para></entry>
21410 </row>
21411
21412 <row>
21413 <entry role="func_table_entry"><para role="func_signature">
21414 <type>anymultirange</type> <literal>&amp;&lt;</literal> <type>anymultirange</type>
21415 <returnvalue>boolean</returnvalue>
21416 </para>
21417 <para>
21418 Does the first multirange not extend to the right of the second?
21419 </para>
21420 <para>
21421 <literal>'{[1,20)}'::int8multirange &amp;&lt; '{[18,20)}'::int8multirange</literal>
21422 <returnvalue>t</returnvalue>
21423 </para></entry>
21424 </row>
21425
21426 <row>
21427 <entry role="func_table_entry"><para role="func_signature">
21428 <type>anymultirange</type> <literal>&amp;&lt;</literal> <type>anyrange</type>
21429 <returnvalue>boolean</returnvalue>
21430 </para>
21431 <para>
21432 Does the multirange not extend to the right of the range?
21433 </para>
21434 <para>
21435 <literal>'{[1,20)}'::int8multirange &amp;&lt; int8range(18,20)</literal>
21436 <returnvalue>t</returnvalue>
21437 </para></entry>
21438 </row>
21439
21440 <row>
21441 <entry role="func_table_entry"><para role="func_signature">
21442 <type>anyrange</type> <literal>&amp;&lt;</literal> <type>anymultirange</type>
21443 <returnvalue>boolean</returnvalue>
21444 </para>
21445 <para>
21446 Does the range not extend to the right of the multirange?
21447 </para>
21448 <para>
21449 <literal>int8range(1,20) &amp;&lt; '{[18,20)}'::int8multirange</literal>
21450 <returnvalue>t</returnvalue>
21451 </para></entry>
21452 </row>
21453
21454 <row>
21455 <entry role="func_table_entry"><para role="func_signature">
21456 <type>anymultirange</type> <literal>&amp;&gt;</literal> <type>anymultirange</type>
21457 <returnvalue>boolean</returnvalue>
21458 </para>
21459 <para>
21460 Does the first multirange not extend to the left of the second?
21461 </para>
21462 <para>
21463 <literal>'{[7,20)}'::int8multirange &amp;&gt; '{[5,10)}'::int8multirange</literal>
21464 <returnvalue>t</returnvalue>
21465 </para></entry>
21466 </row>
21467
21468 <row>
21469 <entry role="func_table_entry"><para role="func_signature">
21470 <type>anymultirange</type> <literal>&amp;&gt;</literal> <type>anyrange</type>
21471 <returnvalue>boolean</returnvalue>
21472 </para>
21473 <para>
21474 Does the multirange not extend to the left of the range?
21475 </para>
21476 <para>
21477 <literal>'{[7,20)}'::int8multirange &amp;&gt; int8range(5,10)</literal>
21478 <returnvalue>t</returnvalue>
21479 </para></entry>
21480 </row>
21481
21482 <row>
21483 <entry role="func_table_entry"><para role="func_signature">
21484 <type>anyrange</type> <literal>&amp;&gt;</literal> <type>anymultirange</type>
21485 <returnvalue>boolean</returnvalue>
21486 </para>
21487 <para>
21488 Does the range not extend to the left of the multirange?
21489 </para>
21490 <para>
21491 <literal>int8range(7,20) &amp;&gt; '{[5,10)}'::int8multirange</literal>
21492 <returnvalue>t</returnvalue>
21493 </para></entry>
21494 </row>
21495
21496 <row>
21497 <entry role="func_table_entry"><para role="func_signature">
21498 <type>anymultirange</type> <literal>-|-</literal> <type>anymultirange</type>
21499 <returnvalue>boolean</returnvalue>
21500 </para>
21501 <para>
21502 Are the multiranges adjacent?
21503 </para>
21504 <para>
21505 <literal>'{[1.1,2.2)}'::nummultirange -|- '{[2.2,3.3)}'::nummultirange</literal>
21506 <returnvalue>t</returnvalue>
21507 </para></entry>
21508 </row>
21509
21510 <row>
21511 <entry role="func_table_entry"><para role="func_signature">
21512 <type>anymultirange</type> <literal>-|-</literal> <type>anyrange</type>
21513 <returnvalue>boolean</returnvalue>
21514 </para>
21515 <para>
21516 Is the multirange adjacent to the range?
21517 </para>
21518 <para>
21519 <literal>'{[1.1,2.2)}'::nummultirange -|- numrange(2.2,3.3)</literal>
21520 <returnvalue>t</returnvalue>
21521 </para></entry>
21522 </row>
21523
21524 <row>
21525 <entry role="func_table_entry"><para role="func_signature">
21526 <type>anyrange</type> <literal>-|-</literal> <type>anymultirange</type>
21527 <returnvalue>boolean</returnvalue>
21528 </para>
21529 <para>
21530 Is the range adjacent to the multirange?
21531 </para>
21532 <para>
21533 <literal>numrange(1.1,2.2) -|- '{[2.2,3.3)}'::nummultirange</literal>
21534 <returnvalue>t</returnvalue>
21535 </para></entry>
21536 </row>
21537
21538 <row>
21539 <entry role="func_table_entry"><para role="func_signature">
21540 <type>anymultirange</type> <literal>+</literal> <type>anymultirange</type>
21541 <returnvalue>anymultirange</returnvalue>
21542 </para>
21543 <para>
21544 Computes the union of the multiranges. The multiranges need not overlap
21545 or be adjacent.
21546 </para>
21547 <para>
21548 <literal>'{[5,10)}'::nummultirange + '{[15,20)}'::nummultirange</literal>
21549 <returnvalue>{[5,10), [15,20)}</returnvalue>
21550 </para></entry>
21551 </row>
21552
21553 <row>
21554 <entry role="func_table_entry"><para role="func_signature">
21555 <type>anymultirange</type> <literal>*</literal> <type>anymultirange</type>
21556 <returnvalue>anymultirange</returnvalue>
21557 </para>
21558 <para>
21559 Computes the intersection of the multiranges.
21560 </para>
21561 <para>
21562 <literal>'{[5,15)}'::int8multirange * '{[10,20)}'::int8multirange</literal>
21563 <returnvalue>{[10,15)}</returnvalue>
21564 </para></entry>
21565 </row>
21566
21567 <row>
21568 <entry role="func_table_entry"><para role="func_signature">
21569 <type>anymultirange</type> <literal>-</literal> <type>anymultirange</type>
21570 <returnvalue>anymultirange</returnvalue>
21571 </para>
21572 <para>
21573 Computes the difference of the multiranges.
21574 </para>
21575 <para>
21576 <literal>'{[5,20)}'::int8multirange - '{[10,15)}'::int8multirange</literal>
21577 <returnvalue>{[5,10), [15,20)}</returnvalue>
21578 </para></entry>
21579 </row>
21580 </tbody>
21581 </tgroup>
21582 </table>
21583
21584 <para>
21585 The left-of/right-of/adjacent operators always return false when an empty
21586 range or multirange is involved; that is, an empty range is not considered to
21587 be either before or after any other range.
21588 </para>
21589
21590 <para>
21591 Elsewhere empty ranges and multiranges are treated as the additive identity:
21592 anything unioned with an empty value is itself. Anything minus an empty
21593 value is itself. An empty multirange has exactly the same points as an empty
21594 range. Every range contains the empty range. Every multirange contains as many
21595 empty ranges as you like.
21596 </para>
21597
21598 <para>
21599 The range union and difference operators will fail if the resulting range would
21600 need to contain two disjoint sub-ranges, as such a range cannot be
21601 represented. There are separate operators for union and difference that take
21602 multirange parameters and return a multirange, and they do not fail even if
21603 their arguments are disjoint. So if you need a union or difference operation
21604 for ranges that may be disjoint, you can avoid errors by first casting your
21605 ranges to multiranges.
21606 </para>
21607
21608 <para>
21609 <xref linkend="range-functions-table"/> shows the functions
21610 available for use with range types.
21611 <xref linkend="multirange-functions-table"/> shows the functions
21612 available for use with multirange types.
21613 </para>
21614
21615 <table id="range-functions-table">
21616 <title>Range Functions</title>
21617 <tgroup cols="1">
21618 <thead>
21619 <row>
21620 <entry role="func_table_entry"><para role="func_signature">
21621 Function
21622 </para>
21623 <para>
21624 Description
21625 </para>
21626 <para>
21627 Example(s)
21628 </para></entry>
21629 </row>
21630 </thead>
21631
21632 <tbody>
21633 <row>
21634 <entry role="func_table_entry"><para role="func_signature">
21635 <indexterm>
21636 <primary>lower</primary>
21637 </indexterm>
21638 <function>lower</function> ( <type>anyrange</type> )
21639 <returnvalue>anyelement</returnvalue>
21640 </para>
21641 <para>
21642 Extracts the lower bound of the range (<literal>NULL</literal> if the
21643 range is empty or has no lower bound).
21644 </para>
21645 <para>
21646 <literal>lower(numrange(1.1,2.2))</literal>
21647 <returnvalue>1.1</returnvalue>
21648 </para></entry>
21649 </row>
21650
21651 <row>
21652 <entry role="func_table_entry"><para role="func_signature">
21653 <indexterm>
21654 <primary>upper</primary>
21655 </indexterm>
21656 <function>upper</function> ( <type>anyrange</type> )
21657 <returnvalue>anyelement</returnvalue>
21658 </para>
21659 <para>
21660 Extracts the upper bound of the range (<literal>NULL</literal> if the
21661 range is empty or has no upper bound).
21662 </para>
21663 <para>
21664 <literal>upper(numrange(1.1,2.2))</literal>
21665 <returnvalue>2.2</returnvalue>
21666 </para></entry>
21667 </row>
21668
21669 <row>
21670 <entry role="func_table_entry"><para role="func_signature">
21671 <indexterm>
21672 <primary>isempty</primary>
21673 </indexterm>
21674 <function>isempty</function> ( <type>anyrange</type> )
21675 <returnvalue>boolean</returnvalue>
21676 </para>
21677 <para>
21678 Is the range empty?
21679 </para>
21680 <para>
21681 <literal>isempty(numrange(1.1,2.2))</literal>
21682 <returnvalue>f</returnvalue>
21683 </para></entry>
21684 </row>
21685
21686 <row>
21687 <entry role="func_table_entry"><para role="func_signature">
21688 <indexterm>
21689 <primary>lower_inc</primary>
21690 </indexterm>
21691 <function>lower_inc</function> ( <type>anyrange</type> )
21692 <returnvalue>boolean</returnvalue>
21693 </para>
21694 <para>
21695 Is the range's lower bound inclusive?
21696 </para>
21697 <para>
21698 <literal>lower_inc(numrange(1.1,2.2))</literal>
21699 <returnvalue>t</returnvalue>
21700 </para></entry>
21701 </row>
21702
21703 <row>
21704 <entry role="func_table_entry"><para role="func_signature">
21705 <indexterm>
21706 <primary>upper_inc</primary>
21707 </indexterm>
21708 <function>upper_inc</function> ( <type>anyrange</type> )
21709 <returnvalue>boolean</returnvalue>
21710 </para>
21711 <para>
21712 Is the range's upper bound inclusive?
21713 </para>
21714 <para>
21715 <literal>upper_inc(numrange(1.1,2.2))</literal>
21716 <returnvalue>f</returnvalue>
21717 </para></entry>
21718 </row>
21719
21720 <row>
21721 <entry role="func_table_entry"><para role="func_signature">
21722 <indexterm>
21723 <primary>lower_inf</primary>
21724 </indexterm>
21725 <function>lower_inf</function> ( <type>anyrange</type> )
21726 <returnvalue>boolean</returnvalue>
21727 </para>
21728 <para>
21729 Does the range have no lower bound? (A lower bound of
21730 <literal>-Infinity</literal> returns false.)
21731 </para>
21732 <para>
21733 <literal>lower_inf('(,)'::daterange)</literal>
21734 <returnvalue>t</returnvalue>
21735 </para></entry>
21736 </row>
21737
21738 <row>
21739 <entry role="func_table_entry"><para role="func_signature">
21740 <indexterm>
21741 <primary>upper_inf</primary>
21742 </indexterm>
21743 <function>upper_inf</function> ( <type>anyrange</type> )
21744 <returnvalue>boolean</returnvalue>
21745 </para>
21746 <para>
21747 Does the range have no upper bound? (An upper bound of
21748 <literal>Infinity</literal> returns false.)
21749 </para>
21750 <para>
21751 <literal>upper_inf('(,)'::daterange)</literal>
21752 <returnvalue>t</returnvalue>
21753 </para></entry>
21754 </row>
21755
21756 <row>
21757 <entry role="func_table_entry"><para role="func_signature">
21758 <indexterm>
21759 <primary>range_merge</primary>
21760 </indexterm>
21761 <function>range_merge</function> ( <type>anyrange</type>, <type>anyrange</type> )
21762 <returnvalue>anyrange</returnvalue>
21763 </para>
21764 <para>
21765 Computes the smallest range that includes both of the given ranges.
21766 </para>
21767 <para>
21768 <literal>range_merge('[1,2)'::int4range, '[3,4)'::int4range)</literal>
21769 <returnvalue>[1,4)</returnvalue>
21770 </para></entry>
21771 </row>
21772 </tbody>
21773 </tgroup>
21774 </table>
21775
21776 <table id="multirange-functions-table">
21777 <title>Multirange Functions</title>
21778 <tgroup cols="1">
21779 <thead>
21780 <row>
21781 <entry role="func_table_entry"><para role="func_signature">
21782 Function
21783 </para>
21784 <para>
21785 Description
21786 </para>
21787 <para>
21788 Example(s)
21789 </para></entry>
21790 </row>
21791 </thead>
21792 <tbody>
21793 <row>
21794 <entry role="func_table_entry"><para role="func_signature">
21795 <indexterm>
21796 <primary>lower</primary>
21797 </indexterm>
21798 <function>lower</function> ( <type>anymultirange</type> )
21799 <returnvalue>anyelement</returnvalue>
21800 </para>
21801 <para>
21802 Extracts the lower bound of the multirange (<literal>NULL</literal> if the
21803 multirange is empty or has no lower bound).
21804 </para>
21805 <para>
21806 <literal>lower('{[1.1,2.2)}'::nummultirange)</literal>
21807 <returnvalue>1.1</returnvalue>
21808 </para></entry>
21809 </row>
21810
21811 <row>
21812 <entry role="func_table_entry"><para role="func_signature">
21813 <indexterm>
21814 <primary>upper</primary>
21815 </indexterm>
21816 <function>upper</function> ( <type>anymultirange</type> )
21817 <returnvalue>anyelement</returnvalue>
21818 </para>
21819 <para>
21820 Extracts the upper bound of the multirange (<literal>NULL</literal> if the
21821 multirange is empty or has no upper bound).
21822 </para>
21823 <para>
21824 <literal>upper('{[1.1,2.2)}'::nummultirange)</literal>
21825 <returnvalue>2.2</returnvalue>
21826 </para></entry>
21827 </row>
21828
21829 <row>
21830 <entry role="func_table_entry"><para role="func_signature">
21831 <indexterm>
21832 <primary>isempty</primary>
21833 </indexterm>
21834 <function>isempty</function> ( <type>anymultirange</type> )
21835 <returnvalue>boolean</returnvalue>
21836 </para>
21837 <para>
21838 Is the multirange empty?
21839 </para>
21840 <para>
21841 <literal>isempty('{[1.1,2.2)}'::nummultirange)</literal>
21842 <returnvalue>f</returnvalue>
21843 </para></entry>
21844 </row>
21845
21846 <row>
21847 <entry role="func_table_entry"><para role="func_signature">
21848 <indexterm>
21849 <primary>lower_inc</primary>
21850 </indexterm>
21851 <function>lower_inc</function> ( <type>anymultirange</type> )
21852 <returnvalue>boolean</returnvalue>
21853 </para>
21854 <para>
21855 Is the multirange's lower bound inclusive?
21856 </para>
21857 <para>
21858 <literal>lower_inc('{[1.1,2.2)}'::nummultirange)</literal>
21859 <returnvalue>t</returnvalue>
21860 </para></entry>
21861 </row>
21862
21863 <row>
21864 <entry role="func_table_entry"><para role="func_signature">
21865 <indexterm>
21866 <primary>upper_inc</primary>
21867 </indexterm>
21868 <function>upper_inc</function> ( <type>anymultirange</type> )
21869 <returnvalue>boolean</returnvalue>
21870 </para>
21871 <para>
21872 Is the multirange's upper bound inclusive?
21873 </para>
21874 <para>
21875 <literal>upper_inc('{[1.1,2.2)}'::nummultirange)</literal>
21876 <returnvalue>f</returnvalue>
21877 </para></entry>
21878 </row>
21879
21880 <row>
21881 <entry role="func_table_entry"><para role="func_signature">
21882 <indexterm>
21883 <primary>lower_inf</primary>
21884 </indexterm>
21885 <function>lower_inf</function> ( <type>anymultirange</type> )
21886 <returnvalue>boolean</returnvalue>
21887 </para>
21888 <para>
21889 Does the multirange have no lower bound? (A lower bound of
21890 <literal>-Infinity</literal> returns false.)
21891 </para>
21892 <para>
21893 <literal>lower_inf('{(,)}'::datemultirange)</literal>
21894 <returnvalue>t</returnvalue>
21895 </para></entry>
21896 </row>
21897
21898 <row>
21899 <entry role="func_table_entry"><para role="func_signature">
21900 <indexterm>
21901 <primary>upper_inf</primary>
21902 </indexterm>
21903 <function>upper_inf</function> ( <type>anymultirange</type> )
21904 <returnvalue>boolean</returnvalue>
21905 </para>
21906 <para>
21907 Does the multirange have no upper bound? (An upper bound of
21908 <literal>Infinity</literal> returns false.)
21909 </para>
21910 <para>
21911 <literal>upper_inf('{(,)}'::datemultirange)</literal>
21912 <returnvalue>t</returnvalue>
21913 </para></entry>
21914 </row>
21915
21916 <row>
21917 <entry role="func_table_entry"><para role="func_signature">
21918 <indexterm>
21919 <primary>range_merge</primary>
21920 </indexterm>
21921 <function>range_merge</function> ( <type>anymultirange</type> )
21922 <returnvalue>anyrange</returnvalue>
21923 </para>
21924 <para>
21925 Computes the smallest range that includes the entire multirange.
21926 </para>
21927 <para>
21928 <literal>range_merge('{[1,2), [3,4)}'::int4multirange)</literal>
21929 <returnvalue>[1,4)</returnvalue>
21930 </para></entry>
21931 </row>
21932
21933 <row>
21934 <entry role="func_table_entry"><para role="func_signature">
21935 <indexterm>
21936 <primary>multirange (function)</primary>
21937 </indexterm>
21938 <function>multirange</function> ( <type>anyrange</type> )
21939 <returnvalue>anymultirange</returnvalue>
21940 </para>
21941 <para>
21942 Returns a multirange containing just the given range.
21943 </para>
21944 <para>
21945 <literal>multirange('[1,2)'::int4range)</literal>
21946 <returnvalue>{[1,2)}</returnvalue>
21947 </para></entry>
21948 </row>
21949
21950 <row>
21951 <entry role="func_table_entry"><para role="func_signature">
21952 <indexterm>
21953 <primary>unnest</primary>
21954 <secondary>for multirange</secondary>
21955 </indexterm>
21956 <function>unnest</function> ( <type>anymultirange</type> )
21957 <returnvalue>setof anyrange</returnvalue>
21958 </para>
21959 <para>
21960 Expands a multirange into a set of ranges in ascending order.
21961 </para>
21962 <para>
21963 <literal>unnest('{[1,2), [3,4)}'::int4multirange)</literal>
21964 <returnvalue></returnvalue>
21965 <programlisting>
21966 [1,2)
21967 [3,4)
21968 </programlisting>
21969 </para></entry>
21970 </row>
21971 </tbody>
21972 </tgroup>
21973 </table>
21974
21975 <para>
21976 The <function>lower_inc</function>, <function>upper_inc</function>,
21977 <function>lower_inf</function>, and <function>upper_inf</function>
21978 functions all return false for an empty range or multirange.
21979 </para>
21980 </sect1>
21981
21982 <sect1 id="functions-aggregate">
21983 <title>Aggregate Functions</title>
21984
21985 <indexterm zone="functions-aggregate">
21986 <primary>aggregate function</primary>
21987 <secondary>built-in</secondary>
21988 </indexterm>
21989
21990 <para>
21991 <firstterm>Aggregate functions</firstterm> compute a single result
21992 from a set of input values. The built-in general-purpose aggregate
21993 functions are listed in <xref linkend="functions-aggregate-table"/>
21994 while statistical aggregates are in <xref
21995 linkend="functions-aggregate-statistics-table"/>.
21996 The built-in within-group ordered-set aggregate functions
21997 are listed in <xref linkend="functions-orderedset-table"/>
21998 while the built-in within-group hypothetical-set ones are in <xref
21999 linkend="functions-hypothetical-table"/>. Grouping operations,
22000 which are closely related to aggregate functions, are listed in
22001 <xref linkend="functions-grouping-table"/>.
22002 The special syntax considerations for aggregate
22003 functions are explained in <xref linkend="syntax-aggregates"/>.
22004 Consult <xref linkend="tutorial-agg"/> for additional introductory
22005 information.
22006 </para>
22007
22008 <para>
22009 Aggregate functions that support <firstterm>Partial Mode</firstterm>
22010 are eligible to participate in various optimizations, such as parallel
22011 aggregation.
22012 </para>
22013
22014 <para>
22015 While all aggregates below accept an optional
22016 <literal>ORDER BY</literal> clause (as outlined in <xref
22017 linkend="syntax-aggregates"/>), the clause has only been added to
22018 aggregates whose output is affected by ordering.
22019 </para>
22020
22021 <table id="functions-aggregate-table">
22022 <title>General-Purpose Aggregate Functions</title>
22023 <tgroup cols="2">
22024 <colspec colname="col1" colwidth="10*"/>
22025 <colspec colname="col2" colwidth="1*"/>
22026 <thead>
22027 <row>
22028 <entry role="func_table_entry"><para role="func_signature">
22029 Function
22030 </para>
22031 <para>
22032 Description
22033 </para></entry>
22034 <entry>Partial Mode</entry>
22035 </row>
22036 </thead>
22037
22038 <tbody>
22039 <row>
22040 <entry role="func_table_entry"><para role="func_signature">
22041 <indexterm>
22042 <primary>any_value</primary>
22043 </indexterm>
22044 <function>any_value</function> ( <type>anyelement</type> )
22045 <returnvalue><replaceable>same as input type</replaceable></returnvalue>
22046 </para>
22047 <para>
22048 Returns an arbitrary value from the non-null input values.
22049 </para></entry>
22050 <entry>Yes</entry>
22051 </row>
22052
22053 <row>
22054 <entry role="func_table_entry"><para role="func_signature">
22055 <indexterm>
22056 <primary>array_agg</primary>
22057 </indexterm>
22058 <function>array_agg</function> ( <type>anynonarray</type> <literal>ORDER BY</literal> <literal>input_sort_columns</literal> )
22059 <returnvalue>anyarray</returnvalue>
22060 </para>
22061 <para>
22062 Collects all the input values, including nulls, into an array.
22063 </para></entry>
22064 <entry>Yes</entry>
22065 </row>
22066
22067 <row>
22068 <entry role="func_table_entry"><para role="func_signature">
22069 <function>array_agg</function> ( <type>anyarray</type> <literal>ORDER BY</literal> <literal>input_sort_columns</literal> )
22070 <returnvalue>anyarray</returnvalue>
22071 </para>
22072 <para>
22073 Concatenates all the input arrays into an array of one higher
22074 dimension. (The inputs must all have the same dimensionality, and
22075 cannot be empty or null.)
22076 </para></entry>
22077 <entry>Yes</entry>
22078 </row>
22079
22080 <row>
22081 <entry role="func_table_entry"><para role="func_signature">
22082 <indexterm>
22083 <primary>average</primary>
22084 </indexterm>
22085 <indexterm>
22086 <primary>avg</primary>
22087 </indexterm>
22088 <function>avg</function> ( <type>smallint</type> )
22089 <returnvalue>numeric</returnvalue>
22090 </para>
22091 <para role="func_signature">
22092 <function>avg</function> ( <type>integer</type> )
22093 <returnvalue>numeric</returnvalue>
22094 </para>
22095 <para role="func_signature">
22096 <function>avg</function> ( <type>bigint</type> )
22097 <returnvalue>numeric</returnvalue>
22098 </para>
22099 <para role="func_signature">
22100 <function>avg</function> ( <type>numeric</type> )
22101 <returnvalue>numeric</returnvalue>
22102 </para>
22103 <para role="func_signature">
22104 <function>avg</function> ( <type>real</type> )
22105 <returnvalue>double precision</returnvalue>
22106 </para>
22107 <para role="func_signature">
22108 <function>avg</function> ( <type>double precision</type> )
22109 <returnvalue>double precision</returnvalue>
22110 </para>
22111 <para role="func_signature">
22112 <function>avg</function> ( <type>interval</type> )
22113 <returnvalue>interval</returnvalue>
22114 </para>
22115 <para>
22116 Computes the average (arithmetic mean) of all the non-null input
22117 values.
22118 </para></entry>
22119 <entry>Yes</entry>
22120 </row>
22121
22122 <row>
22123 <entry role="func_table_entry"><para role="func_signature">
22124 <indexterm>
22125 <primary>bit_and</primary>
22126 </indexterm>
22127 <function>bit_and</function> ( <type>smallint</type> )
22128 <returnvalue>smallint</returnvalue>
22129 </para>
22130 <para role="func_signature">
22131 <function>bit_and</function> ( <type>integer</type> )
22132 <returnvalue>integer</returnvalue>
22133 </para>
22134 <para role="func_signature">
22135 <function>bit_and</function> ( <type>bigint</type> )
22136 <returnvalue>bigint</returnvalue>
22137 </para>
22138 <para role="func_signature">
22139 <function>bit_and</function> ( <type>bit</type> )
22140 <returnvalue>bit</returnvalue>
22141 </para>
22142 <para>
22143 Computes the bitwise AND of all non-null input values.
22144 </para></entry>
22145 <entry>Yes</entry>
22146 </row>
22147
22148 <row>
22149 <entry role="func_table_entry"><para role="func_signature">
22150 <indexterm>
22151 <primary>bit_or</primary>
22152 </indexterm>
22153 <function>bit_or</function> ( <type>smallint</type> )
22154 <returnvalue>smallint</returnvalue>
22155 </para>
22156 <para role="func_signature">
22157 <function>bit_or</function> ( <type>integer</type> )
22158 <returnvalue>integer</returnvalue>
22159 </para>
22160 <para role="func_signature">
22161 <function>bit_or</function> ( <type>bigint</type> )
22162 <returnvalue>bigint</returnvalue>
22163 </para>
22164 <para role="func_signature">
22165 <function>bit_or</function> ( <type>bit</type> )
22166 <returnvalue>bit</returnvalue>
22167 </para>
22168 <para>
22169 Computes the bitwise OR of all non-null input values.
22170 </para></entry>
22171 <entry>Yes</entry>
22172 </row>
22173
22174 <row>
22175 <entry role="func_table_entry"><para role="func_signature">
22176 <indexterm>
22177 <primary>bit_xor</primary>
22178 </indexterm>
22179 <function>bit_xor</function> ( <type>smallint</type> )
22180 <returnvalue>smallint</returnvalue>
22181 </para>
22182 <para role="func_signature">
22183 <function>bit_xor</function> ( <type>integer</type> )
22184 <returnvalue>integer</returnvalue>
22185 </para>
22186 <para role="func_signature">
22187 <function>bit_xor</function> ( <type>bigint</type> )
22188 <returnvalue>bigint</returnvalue>
22189 </para>
22190 <para role="func_signature">
22191 <function>bit_xor</function> ( <type>bit</type> )
22192 <returnvalue>bit</returnvalue>
22193 </para>
22194 <para>
22195 Computes the bitwise exclusive OR of all non-null input values.
22196 Can be useful as a checksum for an unordered set of values.
22197 </para></entry>
22198 <entry>Yes</entry>
22199 </row>
22200
22201 <row>
22202 <entry role="func_table_entry"><para role="func_signature">
22203 <indexterm>
22204 <primary>bool_and</primary>
22205 </indexterm>
22206 <function>bool_and</function> ( <type>boolean</type> )
22207 <returnvalue>boolean</returnvalue>
22208 </para>
22209 <para>
22210 Returns true if all non-null input values are true, otherwise false.
22211 </para></entry>
22212 <entry>Yes</entry>
22213 </row>
22214
22215 <row>
22216 <entry role="func_table_entry"><para role="func_signature">
22217 <indexterm>
22218 <primary>bool_or</primary>
22219 </indexterm>
22220 <function>bool_or</function> ( <type>boolean</type> )
22221 <returnvalue>boolean</returnvalue>
22222 </para>
22223 <para>
22224 Returns true if any non-null input value is true, otherwise false.
22225 </para></entry>
22226 <entry>Yes</entry>
22227 </row>
22228
22229 <row>
22230 <entry role="func_table_entry"><para role="func_signature">
22231 <indexterm>
22232 <primary>count</primary>
22233 </indexterm>
22234 <function>count</function> ( <literal>*</literal> )
22235 <returnvalue>bigint</returnvalue>
22236 </para>
22237 <para>
22238 Computes the number of input rows.
22239 </para></entry>
22240 <entry>Yes</entry>
22241 </row>
22242
22243 <row>
22244 <entry role="func_table_entry"><para role="func_signature">
22245 <function>count</function> ( <type>"any"</type> )
22246 <returnvalue>bigint</returnvalue>
22247 </para>
22248 <para>
22249 Computes the number of input rows in which the input value is not
22250 null.
22251 </para></entry>
22252 <entry>Yes</entry>
22253 </row>
22254
22255 <row>
22256 <entry role="func_table_entry"><para role="func_signature">
22257 <indexterm>
22258 <primary>every</primary>
22259 </indexterm>
22260 <function>every</function> ( <type>boolean</type> )
22261 <returnvalue>boolean</returnvalue>
22262 </para>
22263 <para>
22264 This is the SQL standard's equivalent to <function>bool_and</function>.
22265 </para></entry>
22266 <entry>Yes</entry>
22267 </row>
22268
22269 <row>
22270 <entry role="func_table_entry"><para role="func_signature">
22271 <indexterm>
22272 <primary>json_agg</primary>
22273 </indexterm>
22274 <function>json_agg</function> ( <type>anyelement</type> <literal>ORDER BY</literal> <literal>input_sort_columns</literal> )
22275 <returnvalue>json</returnvalue>
22276 </para>
22277 <para role="func_signature">
22278 <indexterm>
22279 <primary>jsonb_agg</primary>
22280 </indexterm>
22281 <function>jsonb_agg</function> ( <type>anyelement</type> <literal>ORDER BY</literal> <literal>input_sort_columns</literal> )
22282 <returnvalue>jsonb</returnvalue>
22283 </para>
22284 <para>
22285 Collects all the input values, including nulls, into a JSON array.
22286 Values are converted to JSON as per <function>to_json</function>
22287 or <function>to_jsonb</function>.
22288 </para></entry>
22289 <entry>No</entry>
22290 </row>
22291
22292 <row>
22293 <entry role="func_table_entry"><para role="func_signature">
22294 <indexterm>
22295 <primary>json_agg_strict</primary>
22296 </indexterm>
22297 <function>json_agg_strict</function> ( <type>anyelement</type> )
22298 <returnvalue>json</returnvalue>
22299 </para>
22300 <para role="func_signature">
22301 <indexterm>
22302 <primary>jsonb_agg_strict</primary>
22303 </indexterm>
22304 <function>jsonb_agg_strict</function> ( <type>anyelement</type> )
22305 <returnvalue>jsonb</returnvalue>
22306 </para>
22307 <para>
22308 Collects all the input values, skipping nulls, into a JSON array.
22309 Values are converted to JSON as per <function>to_json</function>
22310 or <function>to_jsonb</function>.
22311 </para></entry>
22312 <entry>No</entry>
22313 </row>
22314
22315 <row>
22316 <entry role="func_table_entry"><para role="func_signature">
22317 <indexterm><primary>json_arrayagg</primary></indexterm>
22318 <function>json_arrayagg</function> (
22319 <optional> <replaceable>value_expression</replaceable> </optional>
22320 <optional> <literal>ORDER BY</literal> <replaceable>sort_expression</replaceable> </optional>
22321 <optional> { <literal>NULL</literal> | <literal>ABSENT</literal> } <literal>ON NULL</literal> </optional>
22322 <optional> <literal>RETURNING</literal> <replaceable>data_type</replaceable> <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional> </optional> </optional>)
22323 </para>
22324 <para>
22325 Behaves in the same way as <function>json_array</function>
22326 but as an aggregate function so it only takes one
22327 <replaceable>value_expression</replaceable> parameter.
22328 If <literal>ABSENT ON NULL</literal> is specified, any NULL
22329 values are omitted.
22330 If <literal>ORDER BY</literal> is specified, the elements will
22331 appear in the array in that order rather than in the input order.
22332 </para>
22333 <para>
22334 <literal>SELECT json_arrayagg(v) FROM (VALUES(2),(1)) t(v)</literal>
22335 <returnvalue>[2, 1]</returnvalue>
22336 </para></entry>
22337 <entry>No</entry>
22338 </row>
22339
22340 <row>
22341 <entry role="func_table_entry"><para role="func_signature">
22342 <indexterm><primary>json_objectagg</primary></indexterm>
22343 <function>json_objectagg</function> (
22344 <optional> { <replaceable>key_expression</replaceable> { <literal>VALUE</literal> | ':' } <replaceable>value_expression</replaceable> } </optional>
22345 <optional> { <literal>NULL</literal> | <literal>ABSENT</literal> } <literal>ON NULL</literal> </optional>
22346 <optional> { <literal>WITH</literal> | <literal>WITHOUT</literal> } <literal>UNIQUE</literal> <optional> <literal>KEYS</literal> </optional> </optional>
22347 <optional> <literal>RETURNING</literal> <replaceable>data_type</replaceable> <optional> <literal>FORMAT JSON</literal> <optional> <literal>ENCODING UTF8</literal> </optional> </optional> </optional>)
22348 </para>
22349 <para>
22350 Behaves like <function>json_object</function><!-- xref -->, but as an
22351 aggregate function, so it only takes one
22352 <replaceable>key_expression</replaceable> and one
22353 <replaceable>value_expression</replaceable> parameter.
22354 </para>
22355 <para>
22356 <literal>SELECT json_objectagg(k:v) FROM (VALUES ('a'::text,current_date),('b',current_date + 1)) AS t(k,v)</literal>
22357 <returnvalue>{ "a" : "2022-05-10", "b" : "2022-05-11" }</returnvalue>
22358 </para></entry>
22359 <entry>No</entry>
22360 </row>
22361
22362 <row>
22363 <entry role="func_table_entry"><para role="func_signature">
22364 <indexterm>
22365 <primary>json_object_agg</primary>
22366 </indexterm>
22367 <function>json_object_agg</function> ( <parameter>key</parameter>
22368 <type>"any"</type>, <parameter>value</parameter>
22369 <type>"any"</type>
22370 <literal>ORDER BY</literal> <literal>input_sort_columns</literal> )
22371 <returnvalue>json</returnvalue>
22372 </para>
22373 <para role="func_signature">
22374 <indexterm>
22375 <primary>jsonb_object_agg</primary>
22376 </indexterm>
22377 <function>jsonb_object_agg</function> ( <parameter>key</parameter>
22378 <type>"any"</type>, <parameter>value</parameter>
22379 <type>"any"</type>
22380 <literal>ORDER BY</literal> <literal>input_sort_columns</literal> )
22381 <returnvalue>jsonb</returnvalue>
22382 </para>
22383 <para>
22384 Collects all the key/value pairs into a JSON object. Key arguments
22385 are coerced to text; value arguments are converted as per
22386 <function>to_json</function> or <function>to_jsonb</function>.
22387 Values can be null, but keys cannot.
22388 </para></entry>
22389 <entry>No</entry>
22390 </row>
22391
22392 <row>
22393 <entry role="func_table_entry"><para role="func_signature">
22394 <indexterm>
22395 <primary>json_object_agg_strict</primary>
22396 </indexterm>
22397 <function>json_object_agg_strict</function> (
22398 <parameter>key</parameter> <type>"any"</type>,
22399 <parameter>value</parameter> <type>"any"</type> )
22400 <returnvalue>json</returnvalue>
22401 </para>
22402 <para role="func_signature">
22403 <indexterm>
22404 <primary>jsonb_object_agg_strict</primary>
22405 </indexterm>
22406 <function>jsonb_object_agg_strict</function> (
22407 <parameter>key</parameter> <type>"any"</type>,
22408 <parameter>value</parameter> <type>"any"</type> )
22409 <returnvalue>jsonb</returnvalue>
22410 </para>
22411 <para>
22412 Collects all the key/value pairs into a JSON object. Key arguments
22413 are coerced to text; value arguments are converted as per
22414 <function>to_json</function> or <function>to_jsonb</function>.
22415 The <parameter>key</parameter> can not be null. If the
22416 <parameter>value</parameter> is null then the entry is skipped,
22417 </para></entry>
22418 <entry>No</entry>
22419 </row>
22420
22421 <row>
22422 <entry role="func_table_entry"><para role="func_signature">
22423 <indexterm>
22424 <primary>json_object_agg_unique</primary>
22425 </indexterm>
22426 <function>json_object_agg_unique</function> (
22427 <parameter>key</parameter> <type>"any"</type>,
22428 <parameter>value</parameter> <type>"any"</type> )
22429 <returnvalue>json</returnvalue>
22430 </para>
22431 <para role="func_signature">
22432 <indexterm>
22433 <primary>jsonb_object_agg_unique</primary>
22434 </indexterm>
22435 <function>jsonb_object_agg_unique</function> (
22436 <parameter>key</parameter> <type>"any"</type>,
22437 <parameter>value</parameter> <type>"any"</type> )
22438 <returnvalue>jsonb</returnvalue>
22439 </para>
22440 <para>
22441 Collects all the key/value pairs into a JSON object. Key arguments
22442 are coerced to text; value arguments are converted as per
22443 <function>to_json</function> or <function>to_jsonb</function>.
22444 Values can be null, but keys cannot.
22445 If there is a duplicate key an error is thrown.
22446 </para></entry>
22447 <entry>No</entry>
22448 </row>
22449
22450 <row>
22451 <entry role="func_table_entry"><para role="func_signature">
22452 <indexterm>
22453 <primary>json_object_agg_unique_strict</primary>
22454 </indexterm>
22455 <function>json_object_agg_unique_strict</function> (
22456 <parameter>key</parameter> <type>"any"</type>,
22457 <parameter>value</parameter> <type>"any"</type> )
22458 <returnvalue>json</returnvalue>
22459 </para>
22460 <para role="func_signature">
22461 <indexterm>
22462 <primary>jsonb_object_agg_unique_strict</primary>
22463 </indexterm>
22464 <function>jsonb_object_agg_unique_strict</function> (
22465 <parameter>key</parameter> <type>"any"</type>,
22466 <parameter>value</parameter> <type>"any"</type> )
22467 <returnvalue>jsonb</returnvalue>
22468 </para>
22469 <para>
22470 Collects all the key/value pairs into a JSON object. Key arguments
22471 are coerced to text; value arguments are converted as per
22472 <function>to_json</function> or <function>to_jsonb</function>.
22473 The <parameter>key</parameter> can not be null. If the
22474 <parameter>value</parameter> is null then the entry is skipped.
22475 If there is a duplicate key an error is thrown.
22476 </para></entry>
22477 <entry>No</entry>
22478 </row>
22479
22480 <row>
22481 <entry role="func_table_entry"><para role="func_signature">
22482 <indexterm>
22483 <primary>max</primary>
22484 </indexterm>
22485 <function>max</function> ( <replaceable>see text</replaceable> )
22486 <returnvalue><replaceable>same as input type</replaceable></returnvalue>
22487 </para>
22488 <para>
22489 Computes the maximum of the non-null input
22490 values. Available for any numeric, string, date/time, or enum type,
22491 as well as <type>bytea</type>, <type>inet</type>, <type>interval</type>,
22492 <type>money</type>, <type>oid</type>, <type>pg_lsn</type>,
22493 <type>tid</type>, <type>xid8</type>,
22494 and also arrays and composite types containing sortable data types.
22495 </para></entry>
22496 <entry>Yes</entry>
22497 </row>
22498
22499 <row>
22500 <entry role="func_table_entry"><para role="func_signature">
22501 <indexterm>
22502 <primary>min</primary>
22503 </indexterm>
22504 <function>min</function> ( <replaceable>see text</replaceable> )
22505 <returnvalue><replaceable>same as input type</replaceable></returnvalue>
22506 </para>
22507 <para>
22508 Computes the minimum of the non-null input
22509 values. Available for any numeric, string, date/time, or enum type,
22510 as well as <type>bytea</type>, <type>inet</type>, <type>interval</type>,
22511 <type>money</type>, <type>oid</type>, <type>pg_lsn</type>,
22512 <type>tid</type>, <type>xid8</type>,
22513 and also arrays and composite types containing sortable data types.
22514 </para></entry>
22515 <entry>Yes</entry>
22516 </row>
22517
22518 <row>
22519 <entry role="func_table_entry"><para role="func_signature">
22520 <indexterm>
22521 <primary>range_agg</primary>
22522 </indexterm>
22523 <function>range_agg</function> ( <parameter>value</parameter>
22524 <type>anyrange</type> )
22525 <returnvalue>anymultirange</returnvalue>
22526 </para>
22527 <para role="func_signature">
22528 <function>range_agg</function> ( <parameter>value</parameter>
22529 <type>anymultirange</type> )
22530 <returnvalue>anymultirange</returnvalue>
22531 </para>
22532 <para>
22533 Computes the union of the non-null input values.
22534 </para></entry>
22535 <entry>No</entry>
22536 </row>
22537
22538 <row>
22539 <entry role="func_table_entry"><para role="func_signature">
22540 <indexterm>
22541 <primary>range_intersect_agg</primary>
22542 </indexterm>
22543 <function>range_intersect_agg</function> ( <parameter>value</parameter>
22544 <type>anyrange</type> )
22545 <returnvalue>anyrange</returnvalue>
22546 </para>
22547 <para role="func_signature">
22548 <function>range_intersect_agg</function> ( <parameter>value</parameter>
22549 <type>anymultirange</type> )
22550 <returnvalue>anymultirange</returnvalue>
22551 </para>
22552 <para>
22553 Computes the intersection of the non-null input values.
22554 </para></entry>
22555 <entry>No</entry>
22556 </row>
22557
22558 <row>
22559 <entry role="func_table_entry"><para role="func_signature">
22560 <indexterm>
22561 <primary>string_agg</primary>
22562 </indexterm>
22563 <function>string_agg</function> ( <parameter>value</parameter>
22564 <type>text</type>, <parameter>delimiter</parameter> <type>text</type> )
22565 <returnvalue>text</returnvalue>
22566 </para>
22567 <para role="func_signature">
22568 <function>string_agg</function> ( <parameter>value</parameter>
22569 <type>bytea</type>, <parameter>delimiter</parameter> <type>bytea</type>
22570 <literal>ORDER BY</literal> <literal>input_sort_columns</literal> )
22571 <returnvalue>bytea</returnvalue>
22572 </para>
22573 <para>
22574 Concatenates the non-null input values into a string. Each value
22575 after the first is preceded by the
22576 corresponding <parameter>delimiter</parameter> (if it's not null).
22577 </para></entry>
22578 <entry>Yes</entry>
22579 </row>
22580
22581 <row>
22582 <entry role="func_table_entry"><para role="func_signature">
22583 <indexterm>
22584 <primary>sum</primary>
22585 </indexterm>
22586 <function>sum</function> ( <type>smallint</type> )
22587 <returnvalue>bigint</returnvalue>
22588 </para>
22589 <para role="func_signature">
22590 <function>sum</function> ( <type>integer</type> )
22591 <returnvalue>bigint</returnvalue>
22592 </para>
22593 <para role="func_signature">
22594 <function>sum</function> ( <type>bigint</type> )
22595 <returnvalue>numeric</returnvalue>
22596 </para>
22597 <para role="func_signature">
22598 <function>sum</function> ( <type>numeric</type> )
22599 <returnvalue>numeric</returnvalue>
22600 </para>
22601 <para role="func_signature">
22602 <function>sum</function> ( <type>real</type> )
22603 <returnvalue>real</returnvalue>
22604 </para>
22605 <para role="func_signature">
22606 <function>sum</function> ( <type>double precision</type> )
22607 <returnvalue>double precision</returnvalue>
22608 </para>
22609 <para role="func_signature">
22610 <function>sum</function> ( <type>interval</type> )
22611 <returnvalue>interval</returnvalue>
22612 </para>
22613 <para role="func_signature">
22614 <function>sum</function> ( <type>money</type> )
22615 <returnvalue>money</returnvalue>
22616 </para>
22617 <para>
22618 Computes the sum of the non-null input values.
22619 </para></entry>
22620 <entry>Yes</entry>
22621 </row>
22622
22623 <row>
22624 <entry role="func_table_entry"><para role="func_signature">
22625 <indexterm>
22626 <primary>xmlagg</primary>
22627 </indexterm>
22628 <function>xmlagg</function> ( <type>xml</type> <literal>ORDER BY</literal> <literal>input_sort_columns</literal> )
22629 <returnvalue>xml</returnvalue>
22630 </para>
22631 <para>
22632 Concatenates the non-null XML input values (see
22633 <xref linkend="functions-xml-xmlagg"/>).
22634 </para></entry>
22635 <entry>No</entry>
22636 </row>
22637 </tbody>
22638 </tgroup>
22639 </table>
22640
22641 <para>
22642 It should be noted that except for <function>count</function>,
22643 these functions return a null value when no rows are selected. In
22644 particular, <function>sum</function> of no rows returns null, not
22645 zero as one might expect, and <function>array_agg</function>
22646 returns null rather than an empty array when there are no input
22647 rows. The <function>coalesce</function> function can be used to
22648 substitute zero or an empty array for null when necessary.
22649 </para>
22650
22651 <para>
22652 The aggregate functions <function>array_agg</function>,
22653 <function>json_agg</function>, <function>jsonb_agg</function>,
22654 <function>json_agg_strict</function>, <function>jsonb_agg_strict</function>,
22655 <function>json_object_agg</function>, <function>jsonb_object_agg</function>,
22656 <function>json_object_agg_strict</function>, <function>jsonb_object_agg_strict</function>,
22657 <function>json_object_agg_unique</function>, <function>jsonb_object_agg_unique</function>,
22658 <function>json_object_agg_unique_strict</function>,
22659 <function>jsonb_object_agg_unique_strict</function>,
22660 <function>string_agg</function>,
22661 and <function>xmlagg</function>, as well as similar user-defined
22662 aggregate functions, produce meaningfully different result values
22663 depending on the order of the input values. This ordering is
22664 unspecified by default, but can be controlled by writing an
22665 <literal>ORDER BY</literal> clause within the aggregate call, as shown in
22666 <xref linkend="syntax-aggregates"/>.
22667 Alternatively, supplying the input values from a sorted subquery
22668 will usually work. For example:
22669
22670 <screen><![CDATA[
22671 SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;
22672 ]]></screen>
22673
22674 Beware that this approach can fail if the outer query level contains
22675 additional processing, such as a join, because that might cause the
22676 subquery's output to be reordered before the aggregate is computed.
22677 </para>
22678
22679 <note>
22680 <indexterm>
22681 <primary>ANY</primary>
22682 </indexterm>
22683 <indexterm>
22684 <primary>SOME</primary>
22685 </indexterm>
22686 <para>
22687 The boolean aggregates <function>bool_and</function> and
22688 <function>bool_or</function> correspond to the standard SQL aggregates
22689 <function>every</function> and <function>any</function> or
22690 <function>some</function>.
22691 <productname>PostgreSQL</productname>
22692 supports <function>every</function>, but not <function>any</function>
22693 or <function>some</function>, because there is an ambiguity built into
22694 the standard syntax:
22695 <programlisting>
22696 SELECT b1 = ANY((SELECT b2 FROM t2 ...)) FROM t1 ...;
22697 </programlisting>
22698 Here <function>ANY</function> can be considered either as introducing
22699 a subquery, or as being an aggregate function, if the subquery
22700 returns one row with a Boolean value.
22701 Thus the standard name cannot be given to these aggregates.
22702 </para>
22703 </note>
22704
22705 <note>
22706 <para>
22707 Users accustomed to working with other SQL database management
22708 systems might be disappointed by the performance of the
22709 <function>count</function> aggregate when it is applied to the
22710 entire table. A query like:
22711 <programlisting>
22712 SELECT count(*) FROM sometable;
22713 </programlisting>
22714 will require effort proportional to the size of the table:
22715 <productname>PostgreSQL</productname> will need to scan either the
22716 entire table or the entirety of an index that includes all rows in
22717 the table.
22718 </para>
22719 </note>
22720
22721 <para>
22722 <xref linkend="functions-aggregate-statistics-table"/> shows
22723 aggregate functions typically used in statistical analysis.
22724 (These are separated out merely to avoid cluttering the listing
22725 of more-commonly-used aggregates.) Functions shown as
22726 accepting <replaceable>numeric_type</replaceable> are available for all
22727 the types <type>smallint</type>, <type>integer</type>,
22728 <type>bigint</type>, <type>numeric</type>, <type>real</type>,
22729 and <type>double precision</type>.
22730 Where the description mentions
22731 <parameter>N</parameter>, it means the
22732 number of input rows for which all the input expressions are non-null.
22733 In all cases, null is returned if the computation is meaningless,
22734 for example when <parameter>N</parameter> is zero.
22735 </para>
22736
22737 <indexterm>
22738 <primary>statistics</primary>
22739 </indexterm>
22740 <indexterm>
22741 <primary>linear regression</primary>
22742 </indexterm>
22743
22744 <table id="functions-aggregate-statistics-table">
22745 <title>Aggregate Functions for Statistics</title>
22746 <tgroup cols="2">
22747 <colspec colname="col1" colwidth="10*"/>
22748 <colspec colname="col2" colwidth="1*"/>
22749 <thead>
22750 <row>
22751 <entry role="func_table_entry"><para role="func_signature">
22752 Function
22753 </para>
22754 <para>
22755 Description
22756 </para></entry>
22757 <entry>Partial Mode</entry>
22758 </row>
22759 </thead>
22760
22761 <tbody>
22762 <row>
22763 <entry role="func_table_entry"><para role="func_signature">
22764 <indexterm>
22765 <primary>correlation</primary>
22766 </indexterm>
22767 <indexterm>
22768 <primary>corr</primary>
22769 </indexterm>
22770 <function>corr</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22771 <returnvalue>double precision</returnvalue>
22772 </para>
22773 <para>
22774 Computes the correlation coefficient.
22775 </para></entry>
22776 <entry>Yes</entry>
22777 </row>
22778
22779 <row>
22780 <entry role="func_table_entry"><para role="func_signature">
22781 <indexterm>
22782 <primary>covariance</primary>
22783 <secondary>population</secondary>
22784 </indexterm>
22785 <indexterm>
22786 <primary>covar_pop</primary>
22787 </indexterm>
22788 <function>covar_pop</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22789 <returnvalue>double precision</returnvalue>
22790 </para>
22791 <para>
22792 Computes the population covariance.
22793 </para></entry>
22794 <entry>Yes</entry>
22795 </row>
22796
22797 <row>
22798 <entry role="func_table_entry"><para role="func_signature">
22799 <indexterm>
22800 <primary>covariance</primary>
22801 <secondary>sample</secondary>
22802 </indexterm>
22803 <indexterm>
22804 <primary>covar_samp</primary>
22805 </indexterm>
22806 <function>covar_samp</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22807 <returnvalue>double precision</returnvalue>
22808 </para>
22809 <para>
22810 Computes the sample covariance.
22811 </para></entry>
22812 <entry>Yes</entry>
22813 </row>
22814
22815 <row>
22816 <entry role="func_table_entry"><para role="func_signature">
22817 <indexterm>
22818 <primary>regr_avgx</primary>
22819 </indexterm>
22820 <function>regr_avgx</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22821 <returnvalue>double precision</returnvalue>
22822 </para>
22823 <para>
22824 Computes the average of the independent variable,
22825 <literal>sum(<parameter>X</parameter>)/<parameter>N</parameter></literal>.
22826 </para></entry>
22827 <entry>Yes</entry>
22828 </row>
22829
22830 <row>
22831 <entry role="func_table_entry"><para role="func_signature">
22832 <indexterm>
22833 <primary>regr_avgy</primary>
22834 </indexterm>
22835 <function>regr_avgy</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22836 <returnvalue>double precision</returnvalue>
22837 </para>
22838 <para>
22839 Computes the average of the dependent variable,
22840 <literal>sum(<parameter>Y</parameter>)/<parameter>N</parameter></literal>.
22841 </para></entry>
22842 <entry>Yes</entry>
22843 </row>
22844
22845 <row>
22846 <entry role="func_table_entry"><para role="func_signature">
22847 <indexterm>
22848 <primary>regr_count</primary>
22849 </indexterm>
22850 <function>regr_count</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22851 <returnvalue>bigint</returnvalue>
22852 </para>
22853 <para>
22854 Computes the number of rows in which both inputs are non-null.
22855 </para></entry>
22856 <entry>Yes</entry>
22857 </row>
22858
22859 <row>
22860 <entry role="func_table_entry"><para role="func_signature">
22861 <indexterm>
22862 <primary>regression intercept</primary>
22863 </indexterm>
22864 <indexterm>
22865 <primary>regr_intercept</primary>
22866 </indexterm>
22867 <function>regr_intercept</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22868 <returnvalue>double precision</returnvalue>
22869 </para>
22870 <para>
22871 Computes the y-intercept of the least-squares-fit linear equation
22872 determined by the
22873 (<parameter>X</parameter>, <parameter>Y</parameter>) pairs.
22874 </para></entry>
22875 <entry>Yes</entry>
22876 </row>
22877
22878 <row>
22879 <entry role="func_table_entry"><para role="func_signature">
22880 <indexterm>
22881 <primary>regr_r2</primary>
22882 </indexterm>
22883 <function>regr_r2</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22884 <returnvalue>double precision</returnvalue>
22885 </para>
22886 <para>
22887 Computes the square of the correlation coefficient.
22888 </para></entry>
22889 <entry>Yes</entry>
22890 </row>
22891
22892 <row>
22893 <entry role="func_table_entry"><para role="func_signature">
22894 <indexterm>
22895 <primary>regression slope</primary>
22896 </indexterm>
22897 <indexterm>
22898 <primary>regr_slope</primary>
22899 </indexterm>
22900 <function>regr_slope</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22901 <returnvalue>double precision</returnvalue>
22902 </para>
22903 <para>
22904 Computes the slope of the least-squares-fit linear equation determined
22905 by the (<parameter>X</parameter>, <parameter>Y</parameter>)
22906 pairs.
22907 </para></entry>
22908 <entry>Yes</entry>
22909 </row>
22910
22911 <row>
22912 <entry role="func_table_entry"><para role="func_signature">
22913 <indexterm>
22914 <primary>regr_sxx</primary>
22915 </indexterm>
22916 <function>regr_sxx</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22917 <returnvalue>double precision</returnvalue>
22918 </para>
22919 <para>
22920 Computes the <quote>sum of squares</quote> of the independent
22921 variable,
22922 <literal>sum(<parameter>X</parameter>^2) - sum(<parameter>X</parameter>)^2/<parameter>N</parameter></literal>.
22923 </para></entry>
22924 <entry>Yes</entry>
22925 </row>
22926
22927 <row>
22928 <entry role="func_table_entry"><para role="func_signature">
22929 <indexterm>
22930 <primary>regr_sxy</primary>
22931 </indexterm>
22932 <function>regr_sxy</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22933 <returnvalue>double precision</returnvalue>
22934 </para>
22935 <para>
22936 Computes the <quote>sum of products</quote> of independent times
22937 dependent variables,
22938 <literal>sum(<parameter>X</parameter>*<parameter>Y</parameter>) - sum(<parameter>X</parameter>) * sum(<parameter>Y</parameter>)/<parameter>N</parameter></literal>.
22939 </para></entry>
22940 <entry>Yes</entry>
22941 </row>
22942
22943 <row>
22944 <entry role="func_table_entry"><para role="func_signature">
22945 <indexterm>
22946 <primary>regr_syy</primary>
22947 </indexterm>
22948 <function>regr_syy</function> ( <parameter>Y</parameter> <type>double precision</type>, <parameter>X</parameter> <type>double precision</type> )
22949 <returnvalue>double precision</returnvalue>
22950 </para>
22951 <para>
22952 Computes the <quote>sum of squares</quote> of the dependent
22953 variable,
22954 <literal>sum(<parameter>Y</parameter>^2) - sum(<parameter>Y</parameter>)^2/<parameter>N</parameter></literal>.
22955 </para></entry>
22956 <entry>Yes</entry>
22957 </row>
22958
22959 <row>
22960 <entry role="func_table_entry"><para role="func_signature">
22961 <indexterm>
22962 <primary>standard deviation</primary>
22963 </indexterm>
22964 <indexterm>
22965 <primary>stddev</primary>
22966 </indexterm>
22967 <function>stddev</function> ( <replaceable>numeric_type</replaceable> )
22968 <returnvalue></returnvalue> <type>double precision</type>
22969 for <type>real</type> or <type>double precision</type>,
22970 otherwise <type>numeric</type>
22971 </para>
22972 <para>
22973 This is a historical alias for <function>stddev_samp</function>.
22974 </para></entry>
22975 <entry>Yes</entry>
22976 </row>
22977
22978 <row>
22979 <entry role="func_table_entry"><para role="func_signature">
22980 <indexterm>
22981 <primary>standard deviation</primary>
22982 <secondary>population</secondary>
22983 </indexterm>
22984 <indexterm>
22985 <primary>stddev_pop</primary>
22986 </indexterm>
22987 <function>stddev_pop</function> ( <replaceable>numeric_type</replaceable> )
22988 <returnvalue></returnvalue> <type>double precision</type>
22989 for <type>real</type> or <type>double precision</type>,
22990 otherwise <type>numeric</type>
22991 </para>
22992 <para>
22993 Computes the population standard deviation of the input values.
22994 </para></entry>
22995 <entry>Yes</entry>
22996 </row>
22997
22998 <row>
22999 <entry role="func_table_entry"><para role="func_signature">
23000 <indexterm>
23001 <primary>standard deviation</primary>
23002 <secondary>sample</secondary>
23003 </indexterm>
23004 <indexterm>
23005 <primary>stddev_samp</primary>
23006 </indexterm>
23007 <function>stddev_samp</function> ( <replaceable>numeric_type</replaceable> )
23008 <returnvalue></returnvalue> <type>double precision</type>
23009 for <type>real</type> or <type>double precision</type>,
23010 otherwise <type>numeric</type>
23011 </para>
23012 <para>
23013 Computes the sample standard deviation of the input values.
23014 </para></entry>
23015 <entry>Yes</entry>
23016 </row>
23017
23018 <row>
23019 <entry role="func_table_entry"><para role="func_signature">
23020 <indexterm>
23021 <primary>variance</primary>
23022 </indexterm>
23023 <function>variance</function> ( <replaceable>numeric_type</replaceable> )
23024 <returnvalue></returnvalue> <type>double precision</type>
23025 for <type>real</type> or <type>double precision</type>,
23026 otherwise <type>numeric</type>
23027 </para>
23028 <para>
23029 This is a historical alias for <function>var_samp</function>.
23030 </para></entry>
23031 <entry>Yes</entry>
23032 </row>
23033
23034 <row>
23035 <entry role="func_table_entry"><para role="func_signature">
23036 <indexterm>
23037 <primary>variance</primary>
23038 <secondary>population</secondary>
23039 </indexterm>
23040 <indexterm>
23041 <primary>var_pop</primary>
23042 </indexterm>
23043 <function>var_pop</function> ( <replaceable>numeric_type</replaceable> )
23044 <returnvalue></returnvalue> <type>double precision</type>
23045 for <type>real</type> or <type>double precision</type>,
23046 otherwise <type>numeric</type>
23047 </para>
23048 <para>
23049 Computes the population variance of the input values (square of the
23050 population standard deviation).
23051 </para></entry>
23052 <entry>Yes</entry>
23053 </row>
23054
23055 <row>
23056 <entry role="func_table_entry"><para role="func_signature">
23057 <indexterm>
23058 <primary>variance</primary>
23059 <secondary>sample</secondary>
23060 </indexterm>
23061 <indexterm>
23062 <primary>var_samp</primary>
23063 </indexterm>
23064 <function>var_samp</function> ( <replaceable>numeric_type</replaceable> )
23065 <returnvalue></returnvalue> <type>double precision</type>
23066 for <type>real</type> or <type>double precision</type>,
23067 otherwise <type>numeric</type>
23068 </para>
23069 <para>
23070 Computes the sample variance of the input values (square of the sample
23071 standard deviation).
23072 </para></entry>
23073 <entry>Yes</entry>
23074 </row>
23075 </tbody>
23076 </tgroup>
23077 </table>
23078
23079 <para>
23080 <xref linkend="functions-orderedset-table"/> shows some
23081 aggregate functions that use the <firstterm>ordered-set aggregate</firstterm>
23082 syntax. These functions are sometimes referred to as <quote>inverse
23083 distribution</quote> functions. Their aggregated input is introduced by
23084 <literal>ORDER BY</literal>, and they may also take a <firstterm>direct
23085 argument</firstterm> that is not aggregated, but is computed only once.
23086 All these functions ignore null values in their aggregated input.
23087 For those that take a <parameter>fraction</parameter> parameter, the
23088 fraction value must be between 0 and 1; an error is thrown if not.
23089 However, a null <parameter>fraction</parameter> value simply produces a
23090 null result.
23091 </para>
23092
23093 <indexterm>
23094 <primary>ordered-set aggregate</primary>
23095 <secondary>built-in</secondary>
23096 </indexterm>
23097 <indexterm>
23098 <primary>inverse distribution</primary>
23099 </indexterm>
23100
23101 <table id="functions-orderedset-table">
23102 <title>Ordered-Set Aggregate Functions</title>
23103 <tgroup cols="2">
23104 <colspec colname="col1" colwidth="10*"/>
23105 <colspec colname="col2" colwidth="1*"/>
23106 <thead>
23107 <row>
23108 <entry role="func_table_entry"><para role="func_signature">
23109 Function
23110 </para>
23111 <para>
23112 Description
23113 </para></entry>
23114 <entry>Partial Mode</entry>
23115 </row>
23116 </thead>
23117
23118 <tbody>
23119 <row>
23120 <entry role="func_table_entry"><para role="func_signature">
23121 <indexterm>
23122 <primary>mode</primary>
23123 <secondary>statistical</secondary>
23124 </indexterm>
23125 <function>mode</function> () <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <type>anyelement</type> )
23126 <returnvalue>anyelement</returnvalue>
23127 </para>
23128 <para>
23129 Computes the <firstterm>mode</firstterm>, the most frequent
23130 value of the aggregated argument (arbitrarily choosing the first one
23131 if there are multiple equally-frequent values). The aggregated
23132 argument must be of a sortable type.
23133 </para></entry>
23134 <entry>No</entry>
23135 </row>
23136
23137 <row>
23138 <entry role="func_table_entry"><para role="func_signature">
23139 <indexterm>
23140 <primary>percentile</primary>
23141 <secondary>continuous</secondary>
23142 </indexterm>
23143 <function>percentile_cont</function> ( <parameter>fraction</parameter> <type>double precision</type> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <type>double precision</type> )
23144 <returnvalue>double precision</returnvalue>
23145 </para>
23146 <para role="func_signature">
23147 <function>percentile_cont</function> ( <parameter>fraction</parameter> <type>double precision</type> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <type>interval</type> )
23148 <returnvalue>interval</returnvalue>
23149 </para>
23150 <para>
23151 Computes the <firstterm>continuous percentile</firstterm>, a value
23152 corresponding to the specified <parameter>fraction</parameter>
23153 within the ordered set of aggregated argument values. This will
23154 interpolate between adjacent input items if needed.
23155 </para></entry>
23156 <entry>No</entry>
23157 </row>
23158
23159 <row>
23160 <entry role="func_table_entry"><para role="func_signature">
23161 <function>percentile_cont</function> ( <parameter>fractions</parameter> <type>double precision[]</type> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <type>double precision</type> )
23162 <returnvalue>double precision[]</returnvalue>
23163 </para>
23164 <para role="func_signature">
23165 <function>percentile_cont</function> ( <parameter>fractions</parameter> <type>double precision[]</type> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <type>interval</type> )
23166 <returnvalue>interval[]</returnvalue>
23167 </para>
23168 <para>
23169 Computes multiple continuous percentiles. The result is an array of
23170 the same dimensions as the <parameter>fractions</parameter>
23171 parameter, with each non-null element replaced by the (possibly
23172 interpolated) value corresponding to that percentile.
23173 </para></entry>
23174 <entry>No</entry>
23175 </row>
23176
23177 <row>
23178 <entry role="func_table_entry"><para role="func_signature">
23179 <indexterm>
23180 <primary>percentile</primary>
23181 <secondary>discrete</secondary>
23182 </indexterm>
23183 <function>percentile_disc</function> ( <parameter>fraction</parameter> <type>double precision</type> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <type>anyelement</type> )
23184 <returnvalue>anyelement</returnvalue>
23185 </para>
23186 <para>
23187 Computes the <firstterm>discrete percentile</firstterm>, the first
23188 value within the ordered set of aggregated argument values whose
23189 position in the ordering equals or exceeds the
23190 specified <parameter>fraction</parameter>. The aggregated
23191 argument must be of a sortable type.
23192 </para></entry>
23193 <entry>No</entry>
23194 </row>
23195
23196 <row>
23197 <entry role="func_table_entry"><para role="func_signature">
23198 <function>percentile_disc</function> ( <parameter>fractions</parameter> <type>double precision[]</type> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <type>anyelement</type> )
23199 <returnvalue>anyarray</returnvalue>
23200 </para>
23201 <para>
23202 Computes multiple discrete percentiles. The result is an array of the
23203 same dimensions as the <parameter>fractions</parameter> parameter,
23204 with each non-null element replaced by the input value corresponding
23205 to that percentile.
23206 The aggregated argument must be of a sortable type.
23207 </para></entry>
23208 <entry>No</entry>
23209 </row>
23210 </tbody>
23211 </tgroup>
23212 </table>
23213
23214 <indexterm>
23215 <primary>hypothetical-set aggregate</primary>
23216 <secondary>built-in</secondary>
23217 </indexterm>
23218
23219 <para>
23220 Each of the <quote>hypothetical-set</quote> aggregates listed in
23221 <xref linkend="functions-hypothetical-table"/> is associated with a
23222 window function of the same name defined in
23223 <xref linkend="functions-window"/>. In each case, the aggregate's result
23224 is the value that the associated window function would have
23225 returned for the <quote>hypothetical</quote> row constructed from
23226 <replaceable>args</replaceable>, if such a row had been added to the sorted
23227 group of rows represented by the <replaceable>sorted_args</replaceable>.
23228 For each of these functions, the list of direct arguments
23229 given in <replaceable>args</replaceable> must match the number and types of
23230 the aggregated arguments given in <replaceable>sorted_args</replaceable>.
23231 Unlike most built-in aggregates, these aggregates are not strict, that is
23232 they do not drop input rows containing nulls. Null values sort according
23233 to the rule specified in the <literal>ORDER BY</literal> clause.
23234 </para>
23235
23236 <table id="functions-hypothetical-table">
23237 <title>Hypothetical-Set Aggregate Functions</title>
23238 <tgroup cols="2">
23239 <colspec colname="col1" colwidth="10*"/>
23240 <colspec colname="col2" colwidth="1*"/>
23241 <thead>
23242 <row>
23243 <entry role="func_table_entry"><para role="func_signature">
23244 Function
23245 </para>
23246 <para>
23247 Description
23248 </para></entry>
23249 <entry>Partial Mode</entry>
23250 </row>
23251 </thead>
23252
23253 <tbody>
23254 <row>
23255 <entry role="func_table_entry"><para role="func_signature">
23256 <indexterm>
23257 <primary>rank</primary>
23258 <secondary>hypothetical</secondary>
23259 </indexterm>
23260 <function>rank</function> ( <replaceable>args</replaceable> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <replaceable>sorted_args</replaceable> )
23261 <returnvalue>bigint</returnvalue>
23262 </para>
23263 <para>
23264 Computes the rank of the hypothetical row, with gaps; that is, the row
23265 number of the first row in its peer group.
23266 </para></entry>
23267 <entry>No</entry>
23268 </row>
23269
23270 <row>
23271 <entry role="func_table_entry"><para role="func_signature">
23272 <indexterm>
23273 <primary>dense_rank</primary>
23274 <secondary>hypothetical</secondary>
23275 </indexterm>
23276 <function>dense_rank</function> ( <replaceable>args</replaceable> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <replaceable>sorted_args</replaceable> )
23277 <returnvalue>bigint</returnvalue>
23278 </para>
23279 <para>
23280 Computes the rank of the hypothetical row, without gaps; this function
23281 effectively counts peer groups.
23282 </para></entry>
23283 <entry>No</entry>
23284 </row>
23285
23286 <row>
23287 <entry role="func_table_entry"><para role="func_signature">
23288 <indexterm>
23289 <primary>percent_rank</primary>
23290 <secondary>hypothetical</secondary>
23291 </indexterm>
23292 <function>percent_rank</function> ( <replaceable>args</replaceable> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <replaceable>sorted_args</replaceable> )
23293 <returnvalue>double precision</returnvalue>
23294 </para>
23295 <para>
23296 Computes the relative rank of the hypothetical row, that is
23297 (<function>rank</function> - 1) / (total rows - 1).
23298 The value thus ranges from 0 to 1 inclusive.
23299 </para></entry>
23300 <entry>No</entry>
23301 </row>
23302
23303 <row>
23304 <entry role="func_table_entry"><para role="func_signature">
23305 <indexterm>
23306 <primary>cume_dist</primary>
23307 <secondary>hypothetical</secondary>
23308 </indexterm>
23309 <function>cume_dist</function> ( <replaceable>args</replaceable> ) <literal>WITHIN GROUP</literal> ( <literal>ORDER BY</literal> <replaceable>sorted_args</replaceable> )
23310 <returnvalue>double precision</returnvalue>
23311 </para>
23312 <para>
23313 Computes the cumulative distribution, that is (number of rows
23314 preceding or peers with hypothetical row) / (total rows). The value
23315 thus ranges from 1/<parameter>N</parameter> to 1.
23316 </para></entry>
23317 <entry>No</entry>
23318 </row>
23319 </tbody>
23320 </tgroup>
23321 </table>
23322
23323 <table id="functions-grouping-table">
23324 <title>Grouping Operations</title>
23325 <tgroup cols="1">
23326 <thead>
23327 <row>
23328 <entry role="func_table_entry"><para role="func_signature">
23329 Function
23330 </para>
23331 <para>
23332 Description
23333 </para></entry>
23334 </row>
23335 </thead>
23336
23337 <tbody>
23338 <row>
23339 <entry role="func_table_entry"><para role="func_signature">
23340 <indexterm>
23341 <primary>GROUPING</primary>
23342 </indexterm>
23343 <function>GROUPING</function> ( <replaceable>group_by_expression(s)</replaceable> )
23344 <returnvalue>integer</returnvalue>
23345 </para>
23346 <para>
23347 Returns a bit mask indicating which <literal>GROUP BY</literal>
23348 expressions are not included in the current grouping set.
23349 Bits are assigned with the rightmost argument corresponding to the
23350 least-significant bit; each bit is 0 if the corresponding expression
23351 is included in the grouping criteria of the grouping set generating
23352 the current result row, and 1 if it is not included.
23353 </para></entry>
23354 </row>
23355 </tbody>
23356 </tgroup>
23357 </table>
23358
23359 <para>
23360 The grouping operations shown in
23361 <xref linkend="functions-grouping-table"/> are used in conjunction with
23362 grouping sets (see <xref linkend="queries-grouping-sets"/>) to distinguish
23363 result rows. The arguments to the <literal>GROUPING</literal> function
23364 are not actually evaluated, but they must exactly match expressions given
23365 in the <literal>GROUP BY</literal> clause of the associated query level.
23366 For example:
23367 <screen>
23368 <prompt>=&gt;</prompt> <userinput>SELECT * FROM items_sold;</userinput>
23369 make | model | sales
23370 -------+-------+-------
23371 Foo | GT | 10
23372 Foo | Tour | 20
23373 Bar | City | 15
23374 Bar | Sport | 5
23375 (4 rows)
23376
23377 <prompt>=&gt;</prompt> <userinput>SELECT make, model, GROUPING(make,model), sum(sales) FROM items_sold GROUP BY ROLLUP(make,model);</userinput>
23378 make | model | grouping | sum
23379 -------+-------+----------+-----
23380 Foo | GT | 0 | 10
23381 Foo | Tour | 0 | 20
23382 Bar | City | 0 | 15
23383 Bar | Sport | 0 | 5
23384 Foo | | 1 | 30
23385 Bar | | 1 | 20
23386 | | 3 | 50
23387 (7 rows)
23388 </screen>
23389 Here, the <literal>grouping</literal> value <literal>0</literal> in the
23390 first four rows shows that those have been grouped normally, over both the
23391 grouping columns. The value <literal>1</literal> indicates
23392 that <literal>model</literal> was not grouped by in the next-to-last two
23393 rows, and the value <literal>3</literal> indicates that
23394 neither <literal>make</literal> nor <literal>model</literal> was grouped
23395 by in the last row (which therefore is an aggregate over all the input
23396 rows).
23397 </para>
23398
23399 </sect1>
23400
23401 <sect1 id="functions-window">
23402 <title>Window Functions</title>
23403
23404 <indexterm zone="functions-window">
23405 <primary>window function</primary>
23406 <secondary>built-in</secondary>
23407 </indexterm>
23408
23409 <para>
23410 <firstterm>Window functions</firstterm> provide the ability to perform
23411 calculations across sets of rows that are related to the current query
23412 row. See <xref linkend="tutorial-window"/> for an introduction to this
23413 feature, and <xref linkend="syntax-window-functions"/> for syntax
23414 details.
23415 </para>
23416
23417 <para>
23418 The built-in window functions are listed in
23419 <xref linkend="functions-window-table"/>. Note that these functions
23420 <emphasis>must</emphasis> be invoked using window function syntax, i.e., an
23421 <literal>OVER</literal> clause is required.
23422 </para>
23423
23424 <para>
23425 In addition to these functions, any built-in or user-defined
23426 ordinary aggregate (i.e., not ordered-set or hypothetical-set aggregates)
23427 can be used as a window function; see
23428 <xref linkend="functions-aggregate"/> for a list of the built-in aggregates.
23429 Aggregate functions act as window functions only when an <literal>OVER</literal>
23430 clause follows the call; otherwise they act as plain aggregates
23431 and return a single row for the entire set.
23432 </para>
23433
23434 <table id="functions-window-table">
23435 <title>General-Purpose Window Functions</title>
23436 <tgroup cols="1">
23437 <thead>
23438 <row>
23439 <entry role="func_table_entry"><para role="func_signature">
23440 Function
23441 </para>
23442 <para>
23443 Description
23444 </para></entry>
23445 </row>
23446 </thead>
23447
23448 <tbody>
23449 <row>
23450 <entry role="func_table_entry"><para role="func_signature">
23451 <indexterm>
23452 <primary>row_number</primary>
23453 </indexterm>
23454 <function>row_number</function> ()
23455 <returnvalue>bigint</returnvalue>
23456 </para>
23457 <para>
23458 Returns the number of the current row within its partition, counting
23459 from 1.
23460 </para></entry>
23461 </row>
23462
23463 <row>
23464 <entry role="func_table_entry"><para role="func_signature">
23465 <indexterm>
23466 <primary>rank</primary>
23467 </indexterm>
23468 <function>rank</function> ()
23469 <returnvalue>bigint</returnvalue>
23470 </para>
23471 <para>
23472 Returns the rank of the current row, with gaps; that is,
23473 the <function>row_number</function> of the first row in its peer
23474 group.
23475 </para></entry>
23476 </row>
23477
23478 <row>
23479 <entry role="func_table_entry"><para role="func_signature">
23480 <indexterm>
23481 <primary>dense_rank</primary>
23482 </indexterm>
23483 <function>dense_rank</function> ()
23484 <returnvalue>bigint</returnvalue>
23485 </para>
23486 <para>
23487 Returns the rank of the current row, without gaps; this function
23488 effectively counts peer groups.
23489 </para></entry>
23490 </row>
23491
23492 <row>
23493 <entry role="func_table_entry"><para role="func_signature">
23494 <indexterm>
23495 <primary>percent_rank</primary>
23496 </indexterm>
23497 <function>percent_rank</function> ()
23498 <returnvalue>double precision</returnvalue>
23499 </para>
23500 <para>
23501 Returns the relative rank of the current row, that is
23502 (<function>rank</function> - 1) / (total partition rows - 1).
23503 The value thus ranges from 0 to 1 inclusive.
23504 </para></entry>
23505 </row>
23506
23507 <row>
23508 <entry role="func_table_entry"><para role="func_signature">
23509 <indexterm>
23510 <primary>cume_dist</primary>
23511 </indexterm>
23512 <function>cume_dist</function> ()
23513 <returnvalue>double precision</returnvalue>
23514 </para>
23515 <para>
23516 Returns the cumulative distribution, that is (number of partition rows
23517 preceding or peers with current row) / (total partition rows).
23518 The value thus ranges from 1/<parameter>N</parameter> to 1.
23519 </para></entry>
23520 </row>
23521
23522 <row>
23523 <entry role="func_table_entry"><para role="func_signature">
23524 <indexterm>
23525 <primary>ntile</primary>
23526 </indexterm>
23527 <function>ntile</function> ( <parameter>num_buckets</parameter> <type>integer</type> )
23528 <returnvalue>integer</returnvalue>
23529 </para>
23530 <para>
23531 Returns an integer ranging from 1 to the argument value, dividing the
23532 partition as equally as possible.
23533 </para></entry>
23534 </row>
23535
23536 <row>
23537 <entry role="func_table_entry"><para role="func_signature">
23538 <indexterm>
23539 <primary>lag</primary>
23540 </indexterm>
23541 <function>lag</function> ( <parameter>value</parameter> <type>anycompatible</type>
23542 <optional>, <parameter>offset</parameter> <type>integer</type>
23543 <optional>, <parameter>default</parameter> <type>anycompatible</type> </optional></optional> )
23544 <returnvalue>anycompatible</returnvalue>
23545 </para>
23546 <para>
23547 Returns <parameter>value</parameter> evaluated at
23548 the row that is <parameter>offset</parameter>
23549 rows before the current row within the partition; if there is no such
23550 row, instead returns <parameter>default</parameter>
23551 (which must be of a type compatible with
23552 <parameter>value</parameter>).
23553 Both <parameter>offset</parameter> and
23554 <parameter>default</parameter> are evaluated
23555 with respect to the current row. If omitted,
23556 <parameter>offset</parameter> defaults to 1 and
23557 <parameter>default</parameter> to <literal>NULL</literal>.
23558 </para></entry>
23559 </row>
23560
23561 <row>
23562 <entry role="func_table_entry"><para role="func_signature">
23563 <indexterm>
23564 <primary>lead</primary>
23565 </indexterm>
23566 <function>lead</function> ( <parameter>value</parameter> <type>anycompatible</type>
23567 <optional>, <parameter>offset</parameter> <type>integer</type>
23568 <optional>, <parameter>default</parameter> <type>anycompatible</type> </optional></optional> )
23569 <returnvalue>anycompatible</returnvalue>
23570 </para>
23571 <para>
23572 Returns <parameter>value</parameter> evaluated at
23573 the row that is <parameter>offset</parameter>
23574 rows after the current row within the partition; if there is no such
23575 row, instead returns <parameter>default</parameter>
23576 (which must be of a type compatible with
23577 <parameter>value</parameter>).
23578 Both <parameter>offset</parameter> and
23579 <parameter>default</parameter> are evaluated
23580 with respect to the current row. If omitted,
23581 <parameter>offset</parameter> defaults to 1 and
23582 <parameter>default</parameter> to <literal>NULL</literal>.
23583 </para></entry>
23584 </row>
23585
23586 <row>
23587 <entry role="func_table_entry"><para role="func_signature">
23588 <indexterm>
23589 <primary>first_value</primary>
23590 </indexterm>
23591 <function>first_value</function> ( <parameter>value</parameter> <type>anyelement</type> )
23592 <returnvalue>anyelement</returnvalue>
23593 </para>
23594 <para>
23595 Returns <parameter>value</parameter> evaluated
23596 at the row that is the first row of the window frame.
23597 </para></entry>
23598 </row>
23599
23600 <row>
23601 <entry role="func_table_entry"><para role="func_signature">
23602 <indexterm>
23603 <primary>last_value</primary>
23604 </indexterm>
23605 <function>last_value</function> ( <parameter>value</parameter> <type>anyelement</type> )
23606 <returnvalue>anyelement</returnvalue>
23607 </para>
23608 <para>
23609 Returns <parameter>value</parameter> evaluated
23610 at the row that is the last row of the window frame.
23611 </para></entry>
23612 </row>
23613
23614 <row>
23615 <entry role="func_table_entry"><para role="func_signature">
23616 <indexterm>
23617 <primary>nth_value</primary>
23618 </indexterm>
23619 <function>nth_value</function> ( <parameter>value</parameter> <type>anyelement</type>, <parameter>n</parameter> <type>integer</type> )
23620 <returnvalue>anyelement</returnvalue>
23621 </para>
23622 <para>
23623 Returns <parameter>value</parameter> evaluated
23624 at the row that is the <parameter>n</parameter>'th
23625 row of the window frame (counting from 1);
23626 returns <literal>NULL</literal> if there is no such row.
23627 </para></entry>
23628 </row>
23629 </tbody>
23630 </tgroup>
23631 </table>
23632
23633 <para>
23634 All of the functions listed in
23635 <xref linkend="functions-window-table"/> depend on the sort ordering
23636 specified by the <literal>ORDER BY</literal> clause of the associated window
23637 definition. Rows that are not distinct when considering only the
23638 <literal>ORDER BY</literal> columns are said to be <firstterm>peers</firstterm>.
23639 The four ranking functions (including <function>cume_dist</function>) are
23640 defined so that they give the same answer for all rows of a peer group.
23641 </para>
23642
23643 <para>
23644 Note that <function>first_value</function>, <function>last_value</function>, and
23645 <function>nth_value</function> consider only the rows within the <quote>window
23646 frame</quote>, which by default contains the rows from the start of the
23647 partition through the last peer of the current row. This is
23648 likely to give unhelpful results for <function>last_value</function> and
23649 sometimes also <function>nth_value</function>. You can redefine the frame by
23650 adding a suitable frame specification (<literal>RANGE</literal>,
23651 <literal>ROWS</literal> or <literal>GROUPS</literal>) to
23652 the <literal>OVER</literal> clause.
23653 See <xref linkend="syntax-window-functions"/> for more information
23654 about frame specifications.
23655 </para>
23656
23657 <para>
23658 When an aggregate function is used as a window function, it aggregates
23659 over the rows within the current row's window frame.
23660 An aggregate used with <literal>ORDER BY</literal> and the default window frame
23661 definition produces a <quote>running sum</quote> type of behavior, which may or
23662 may not be what's wanted. To obtain
23663 aggregation over the whole partition, omit <literal>ORDER BY</literal> or use
23664 <literal>ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING</literal>.
23665 Other frame specifications can be used to obtain other effects.
23666 </para>
23667
23668 <note>
23669 <para>
23670 The SQL standard defines a <literal>RESPECT NULLS</literal> or
23671 <literal>IGNORE NULLS</literal> option for <function>lead</function>, <function>lag</function>,
23672 <function>first_value</function>, <function>last_value</function>, and
23673 <function>nth_value</function>. This is not implemented in
23674 <productname>PostgreSQL</productname>: the behavior is always the
23675 same as the standard's default, namely <literal>RESPECT NULLS</literal>.
23676 Likewise, the standard's <literal>FROM FIRST</literal> or <literal>FROM LAST</literal>
23677 option for <function>nth_value</function> is not implemented: only the
23678 default <literal>FROM FIRST</literal> behavior is supported. (You can achieve
23679 the result of <literal>FROM LAST</literal> by reversing the <literal>ORDER BY</literal>
23680 ordering.)
23681 </para>
23682 </note>
23683
23684 </sect1>
23685
23686 <sect1 id="functions-merge-support">
23687 <title>Merge Support Functions</title>
23688
23689 <indexterm>
23690 <primary>MERGE</primary>
23691 <secondary>RETURNING</secondary>
23692 </indexterm>
23693
23694 <para>
23695 <productname>PostgreSQL</productname> includes one merge support function
23696 that may be used in the <literal>RETURNING</literal> list of a
23697 <xref linkend="sql-merge"/> command to identify the action taken for each
23698 row; see <xref linkend="functions-merge-support-table"/>.
23699 </para>
23700
23701 <table id="functions-merge-support-table">
23702 <title>Merge Support Functions</title>
23703
23704 <tgroup cols="1">
23705 <thead>
23706 <row>
23707 <entry role="func_table_entry"><para role="func_signature">
23708 Function
23709 </para>
23710 <para>
23711 Description
23712 </para></entry>
23713 </row>
23714 </thead>
23715
23716 <tbody>
23717 <row>
23718 <entry id="merge-action" role="func_table_entry"><para role="func_signature">
23719 <indexterm>
23720 <primary>merge_action</primary>
23721 </indexterm>
23722 <function>merge_action</function> ( )
23723 <returnvalue>text</returnvalue>
23724 </para>
23725 <para>
23726 Returns the merge action command executed for the current row. This
23727 will be <literal>'INSERT'</literal>, <literal>'UPDATE'</literal>, or
23728 <literal>'DELETE'</literal>.
23729 </para></entry>
23730 </row>
23731 </tbody>
23732 </tgroup>
23733 </table>
23734
23735 <para>
23736 Example:
23737 <screen><![CDATA[
23738 MERGE INTO products p
23739 USING stock s ON p.product_id = s.product_id
23740 WHEN MATCHED AND s.quantity > 0 THEN
23741 UPDATE SET in_stock = true, quantity = s.quantity
23742 WHEN MATCHED THEN
23743 UPDATE SET in_stock = false, quantity = 0
23744 WHEN NOT MATCHED THEN
23745 INSERT (product_id, in_stock, quantity)
23746 VALUES (s.product_id, true, s.quantity)
23747 RETURNING merge_action(), p.*;
23748
23749 merge_action | product_id | in_stock | quantity
23750 --------------+------------+----------+----------
23751 UPDATE | 1001 | t | 50
23752 UPDATE | 1002 | f | 0
23753 INSERT | 1003 | t | 10
23754 ]]></screen>
23755 </para>
23756
23757 <para>
23758 Note that this function can only be used in the <literal>RETURNING</literal>
23759 list of a <command>MERGE</command> command. It is an error to use it in any
23760 other part of a query.
23761 </para>
23762
23763 </sect1>
23764
23765 <sect1 id="functions-subquery">
23766 <title>Subquery Expressions</title>
23767
23768 <indexterm>
23769 <primary>EXISTS</primary>
23770 </indexterm>
23771
23772 <indexterm>
23773 <primary>IN</primary>
23774 </indexterm>
23775
23776 <indexterm>
23777 <primary>NOT IN</primary>
23778 </indexterm>
23779
23780 <indexterm>
23781 <primary>ANY</primary>
23782 </indexterm>
23783
23784 <indexterm>
23785 <primary>ALL</primary>
23786 </indexterm>
23787
23788 <indexterm>
23789 <primary>SOME</primary>
23790 </indexterm>
23791
23792 <indexterm>
23793 <primary>subquery</primary>
23794 </indexterm>
23795
23796 <para>
23797 This section describes the <acronym>SQL</acronym>-compliant subquery
23798 expressions available in <productname>PostgreSQL</productname>.
23799 All of the expression forms documented in this section return
23800 Boolean (true/false) results.
23801 </para>
23802
23803 <sect2 id="functions-subquery-exists">
23804 <title><literal>EXISTS</literal></title>
23805
23806 <synopsis>
23807 EXISTS (<replaceable>subquery</replaceable>)
23808 </synopsis>
23809
23810 <para>
23811 The argument of <token>EXISTS</token> is an arbitrary <command>SELECT</command> statement,
23812 or <firstterm>subquery</firstterm>. The
23813 subquery is evaluated to determine whether it returns any rows.
23814 If it returns at least one row, the result of <token>EXISTS</token> is
23815 <quote>true</quote>; if the subquery returns no rows, the result of <token>EXISTS</token>
23816 is <quote>false</quote>.
23817 </para>
23818
23819 <para>
23820 The subquery can refer to variables from the surrounding query,
23821 which will act as constants during any one evaluation of the subquery.
23822 </para>
23823
23824 <para>
23825 The subquery will generally only be executed long enough to determine
23826 whether at least one row is returned, not all the way to completion.
23827 It is unwise to write a subquery that has side effects (such as
23828 calling sequence functions); whether the side effects occur
23829 might be unpredictable.
23830 </para>
23831
23832 <para>
23833 Since the result depends only on whether any rows are returned,
23834 and not on the contents of those rows, the output list of the
23835 subquery is normally unimportant. A common coding convention is
23836 to write all <literal>EXISTS</literal> tests in the form
23837 <literal>EXISTS(SELECT 1 WHERE ...)</literal>. There are exceptions to
23838 this rule however, such as subqueries that use <token>INTERSECT</token>.
23839 </para>
23840
23841 <para>
23842 This simple example is like an inner join on <literal>col2</literal>, but
23843 it produces at most one output row for each <literal>tab1</literal> row,
23844 even if there are several matching <literal>tab2</literal> rows:
23845 <screen>
23846 SELECT col1
23847 FROM tab1
23848 WHERE EXISTS (SELECT 1 FROM tab2 WHERE col2 = tab1.col2);
23849 </screen>
23850 </para>
23851 </sect2>
23852
23853 <sect2 id="functions-subquery-in">
23854 <title><literal>IN</literal></title>
23855
23856 <synopsis>
23857 <replaceable>expression</replaceable> IN (<replaceable>subquery</replaceable>)
23858 </synopsis>
23859
23860 <para>
23861 The right-hand side is a parenthesized
23862 subquery, which must return exactly one column. The left-hand expression
23863 is evaluated and compared to each row of the subquery result.
23864 The result of <token>IN</token> is <quote>true</quote> if any equal subquery row is found.
23865 The result is <quote>false</quote> if no equal row is found (including the
23866 case where the subquery returns no rows).
23867 </para>
23868
23869 <para>
23870 Note that if the left-hand expression yields null, or if there are
23871 no equal right-hand values and at least one right-hand row yields
23872 null, the result of the <token>IN</token> construct will be null, not false.
23873 This is in accordance with SQL's normal rules for Boolean combinations
23874 of null values.
23875 </para>
23876
23877 <para>
23878 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
23879 be evaluated completely.
23880 </para>
23881
23882 <synopsis>
23883 <replaceable>row_constructor</replaceable> IN (<replaceable>subquery</replaceable>)
23884 </synopsis>
23885
23886 <para>
23887 The left-hand side of this form of <token>IN</token> is a row constructor,
23888 as described in <xref linkend="sql-syntax-row-constructors"/>.
23889 The right-hand side is a parenthesized
23890 subquery, which must return exactly as many columns as there are
23891 expressions in the left-hand row. The left-hand expressions are
23892 evaluated and compared row-wise to each row of the subquery result.
23893 The result of <token>IN</token> is <quote>true</quote> if any equal subquery row is found.
23894 The result is <quote>false</quote> if no equal row is found (including the
23895 case where the subquery returns no rows).
23896 </para>
23897
23898 <para>
23899 As usual, null values in the rows are combined per
23900 the normal rules of SQL Boolean expressions. Two rows are considered
23901 equal if all their corresponding members are non-null and equal; the rows
23902 are unequal if any corresponding members are non-null and unequal;
23903 otherwise the result of that row comparison is unknown (null).
23904 If all the per-row results are either unequal or null, with at least one
23905 null, then the result of <token>IN</token> is null.
23906 </para>
23907 </sect2>
23908
23909 <sect2 id="functions-subquery-notin">
23910 <title><literal>NOT IN</literal></title>
23911
23912 <synopsis>
23913 <replaceable>expression</replaceable> NOT IN (<replaceable>subquery</replaceable>)
23914 </synopsis>
23915
23916 <para>
23917 The right-hand side is a parenthesized
23918 subquery, which must return exactly one column. The left-hand expression
23919 is evaluated and compared to each row of the subquery result.
23920 The result of <token>NOT IN</token> is <quote>true</quote> if only unequal subquery rows
23921 are found (including the case where the subquery returns no rows).
23922 The result is <quote>false</quote> if any equal row is found.
23923 </para>
23924
23925 <para>
23926 Note that if the left-hand expression yields null, or if there are
23927 no equal right-hand values and at least one right-hand row yields
23928 null, the result of the <token>NOT IN</token> construct will be null, not true.
23929 This is in accordance with SQL's normal rules for Boolean combinations
23930 of null values.
23931 </para>
23932
23933 <para>
23934 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
23935 be evaluated completely.
23936 </para>
23937
23938 <synopsis>
23939 <replaceable>row_constructor</replaceable> NOT IN (<replaceable>subquery</replaceable>)
23940 </synopsis>
23941
23942 <para>
23943 The left-hand side of this form of <token>NOT IN</token> is a row constructor,
23944 as described in <xref linkend="sql-syntax-row-constructors"/>.
23945 The right-hand side is a parenthesized
23946 subquery, which must return exactly as many columns as there are
23947 expressions in the left-hand row. The left-hand expressions are
23948 evaluated and compared row-wise to each row of the subquery result.
23949 The result of <token>NOT IN</token> is <quote>true</quote> if only unequal subquery rows
23950 are found (including the case where the subquery returns no rows).
23951 The result is <quote>false</quote> if any equal row is found.
23952 </para>
23953
23954 <para>
23955 As usual, null values in the rows are combined per
23956 the normal rules of SQL Boolean expressions. Two rows are considered
23957 equal if all their corresponding members are non-null and equal; the rows
23958 are unequal if any corresponding members are non-null and unequal;
23959 otherwise the result of that row comparison is unknown (null).
23960 If all the per-row results are either unequal or null, with at least one
23961 null, then the result of <token>NOT IN</token> is null.
23962 </para>
23963 </sect2>
23964
23965 <sect2 id="functions-subquery-any-some">
23966 <title><literal>ANY</literal>/<literal>SOME</literal></title>
23967
23968 <synopsis>
23969 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>subquery</replaceable>)
23970 <replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>subquery</replaceable>)
23971 </synopsis>
23972
23973 <para>
23974 The right-hand side is a parenthesized
23975 subquery, which must return exactly one column. The left-hand expression
23976 is evaluated and compared to each row of the subquery result using the
23977 given <replaceable>operator</replaceable>, which must yield a Boolean
23978 result.
23979 The result of <token>ANY</token> is <quote>true</quote> if any true result is obtained.
23980 The result is <quote>false</quote> if no true result is found (including the
23981 case where the subquery returns no rows).
23982 </para>
23983
23984 <para>
23985 <token>SOME</token> is a synonym for <token>ANY</token>.
23986 <token>IN</token> is equivalent to <literal>= ANY</literal>.
23987 </para>
23988
23989 <para>
23990 Note that if there are no successes and at least one right-hand row yields
23991 null for the operator's result, the result of the <token>ANY</token> construct
23992 will be null, not false.
23993 This is in accordance with SQL's normal rules for Boolean combinations
23994 of null values.
23995 </para>
23996
23997 <para>
23998 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
23999 be evaluated completely.
24000 </para>
24001
24002 <synopsis>
24003 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>subquery</replaceable>)
24004 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>subquery</replaceable>)
24005 </synopsis>
24006
24007 <para>
24008 The left-hand side of this form of <token>ANY</token> is a row constructor,
24009 as described in <xref linkend="sql-syntax-row-constructors"/>.
24010 The right-hand side is a parenthesized
24011 subquery, which must return exactly as many columns as there are
24012 expressions in the left-hand row. The left-hand expressions are
24013 evaluated and compared row-wise to each row of the subquery result,
24014 using the given <replaceable>operator</replaceable>.
24015 The result of <token>ANY</token> is <quote>true</quote> if the comparison
24016 returns true for any subquery row.
24017 The result is <quote>false</quote> if the comparison returns false for every
24018 subquery row (including the case where the subquery returns no
24019 rows).
24020 The result is NULL if no comparison with a subquery row returns true,
24021 and at least one comparison returns NULL.
24022 </para>
24023
24024 <para>
24025 See <xref linkend="row-wise-comparison"/> for details about the meaning
24026 of a row constructor comparison.
24027 </para>
24028 </sect2>
24029
24030 <sect2 id="functions-subquery-all">
24031 <title><literal>ALL</literal></title>
24032
24033 <synopsis>
24034 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
24035 </synopsis>
24036
24037 <para>
24038 The right-hand side is a parenthesized
24039 subquery, which must return exactly one column. The left-hand expression
24040 is evaluated and compared to each row of the subquery result using the
24041 given <replaceable>operator</replaceable>, which must yield a Boolean
24042 result.
24043 The result of <token>ALL</token> is <quote>true</quote> if all rows yield true
24044 (including the case where the subquery returns no rows).
24045 The result is <quote>false</quote> if any false result is found.
24046 The result is NULL if no comparison with a subquery row returns false,
24047 and at least one comparison returns NULL.
24048 </para>
24049
24050 <para>
24051 <token>NOT IN</token> is equivalent to <literal>&lt;&gt; ALL</literal>.
24052 </para>
24053
24054 <para>
24055 As with <token>EXISTS</token>, it's unwise to assume that the subquery will
24056 be evaluated completely.
24057 </para>
24058
24059 <synopsis>
24060 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>subquery</replaceable>)
24061 </synopsis>
24062
24063 <para>
24064 The left-hand side of this form of <token>ALL</token> is a row constructor,
24065 as described in <xref linkend="sql-syntax-row-constructors"/>.
24066 The right-hand side is a parenthesized
24067 subquery, which must return exactly as many columns as there are
24068 expressions in the left-hand row. The left-hand expressions are
24069 evaluated and compared row-wise to each row of the subquery result,
24070 using the given <replaceable>operator</replaceable>.
24071 The result of <token>ALL</token> is <quote>true</quote> if the comparison
24072 returns true for all subquery rows (including the
24073 case where the subquery returns no rows).
24074 The result is <quote>false</quote> if the comparison returns false for any
24075 subquery row.
24076 The result is NULL if no comparison with a subquery row returns false,
24077 and at least one comparison returns NULL.
24078 </para>
24079
24080 <para>
24081 See <xref linkend="row-wise-comparison"/> for details about the meaning
24082 of a row constructor comparison.
24083 </para>
24084 </sect2>
24085
24086 <sect2 id="functions-subquery-single-row-comp">
24087 <title>Single-Row Comparison</title>
24088
24089 <indexterm zone="functions-subquery">
24090 <primary>comparison</primary>
24091 <secondary>subquery result row</secondary>
24092 </indexterm>
24093
24094 <synopsis>
24095 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> (<replaceable>subquery</replaceable>)
24096 </synopsis>
24097
24098 <para>
24099 The left-hand side is a row constructor,
24100 as described in <xref linkend="sql-syntax-row-constructors"/>.
24101 The right-hand side is a parenthesized subquery, which must return exactly
24102 as many columns as there are expressions in the left-hand row. Furthermore,
24103 the subquery cannot return more than one row. (If it returns zero rows,
24104 the result is taken to be null.) The left-hand side is evaluated and
24105 compared row-wise to the single subquery result row.
24106 </para>
24107
24108 <para>
24109 See <xref linkend="row-wise-comparison"/> for details about the meaning
24110 of a row constructor comparison.
24111 </para>
24112 </sect2>
24113 </sect1>
24114
24115
24116 <sect1 id="functions-comparisons">
24117 <title>Row and Array Comparisons</title>
24118
24119 <indexterm>
24120 <primary>IN</primary>
24121 </indexterm>
24122
24123 <indexterm>
24124 <primary>NOT IN</primary>
24125 </indexterm>
24126
24127 <indexterm>
24128 <primary>ANY</primary>
24129 </indexterm>
24130
24131 <indexterm>
24132 <primary>ALL</primary>
24133 </indexterm>
24134
24135 <indexterm>
24136 <primary>SOME</primary>
24137 </indexterm>
24138
24139 <indexterm>
24140 <primary>composite type</primary>
24141 <secondary>comparison</secondary>
24142 </indexterm>
24143
24144 <indexterm>
24145 <primary>row-wise comparison</primary>
24146 </indexterm>
24147
24148 <indexterm>
24149 <primary>comparison</primary>
24150 <secondary>composite type</secondary>
24151 </indexterm>
24152
24153 <indexterm>
24154 <primary>comparison</primary>
24155 <secondary>row constructor</secondary>
24156 </indexterm>
24157
24158 <indexterm>
24159 <primary>IS DISTINCT FROM</primary>
24160 </indexterm>
24161
24162 <indexterm>
24163 <primary>IS NOT DISTINCT FROM</primary>
24164 </indexterm>
24165
24166 <para>
24167 This section describes several specialized constructs for making
24168 multiple comparisons between groups of values. These forms are
24169 syntactically related to the subquery forms of the previous section,
24170 but do not involve subqueries.
24171 The forms involving array subexpressions are
24172 <productname>PostgreSQL</productname> extensions; the rest are
24173 <acronym>SQL</acronym>-compliant.
24174 All of the expression forms documented in this section return
24175 Boolean (true/false) results.
24176 </para>
24177
24178 <sect2 id="functions-comparisons-in-scalar">
24179 <title><literal>IN</literal></title>
24180
24181 <synopsis>
24182 <replaceable>expression</replaceable> IN (<replaceable>value</replaceable> <optional>, ...</optional>)
24183 </synopsis>
24184
24185 <para>
24186 The right-hand side is a parenthesized list
24187 of expressions. The result is <quote>true</quote> if the left-hand expression's
24188 result is equal to any of the right-hand expressions. This is a shorthand
24189 notation for
24190
24191 <synopsis>
24192 <replaceable>expression</replaceable> = <replaceable>value1</replaceable>
24193 OR
24194 <replaceable>expression</replaceable> = <replaceable>value2</replaceable>
24195 OR
24196 ...
24197 </synopsis>
24198 </para>
24199
24200 <para>
24201 Note that if the left-hand expression yields null, or if there are
24202 no equal right-hand values and at least one right-hand expression yields
24203 null, the result of the <token>IN</token> construct will be null, not false.
24204 This is in accordance with SQL's normal rules for Boolean combinations
24205 of null values.
24206 </para>
24207 </sect2>
24208
24209 <sect2 id="functions-comparisons-not-in">
24210 <title><literal>NOT IN</literal></title>
24211
24212 <synopsis>
24213 <replaceable>expression</replaceable> NOT IN (<replaceable>value</replaceable> <optional>, ...</optional>)
24214 </synopsis>
24215
24216 <para>
24217 The right-hand side is a parenthesized list
24218 of expressions. The result is <quote>true</quote> if the left-hand expression's
24219 result is unequal to all of the right-hand expressions. This is a shorthand
24220 notation for
24221
24222 <synopsis>
24223 <replaceable>expression</replaceable> &lt;&gt; <replaceable>value1</replaceable>
24224 AND
24225 <replaceable>expression</replaceable> &lt;&gt; <replaceable>value2</replaceable>
24226 AND
24227 ...
24228 </synopsis>
24229 </para>
24230
24231 <para>
24232 Note that if the left-hand expression yields null, or if there are
24233 no equal right-hand values and at least one right-hand expression yields
24234 null, the result of the <token>NOT IN</token> construct will be null, not true
24235 as one might naively expect.
24236 This is in accordance with SQL's normal rules for Boolean combinations
24237 of null values.
24238 </para>
24239
24240 <tip>
24241 <para>
24242 <literal>x NOT IN y</literal> is equivalent to <literal>NOT (x IN y)</literal> in all
24243 cases. However, null values are much more likely to trip up the novice when
24244 working with <token>NOT IN</token> than when working with <token>IN</token>.
24245 It is best to express your condition positively if possible.
24246 </para>
24247 </tip>
24248 </sect2>
24249
24250 <sect2 id="functions-comparisons-any-some">
24251 <title><literal>ANY</literal>/<literal>SOME</literal> (array)</title>
24252
24253 <synopsis>
24254 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>array expression</replaceable>)
24255 <replaceable>expression</replaceable> <replaceable>operator</replaceable> SOME (<replaceable>array expression</replaceable>)
24256 </synopsis>
24257
24258 <para>
24259 The right-hand side is a parenthesized expression, which must yield an
24260 array value.
24261 The left-hand expression
24262 is evaluated and compared to each element of the array using the
24263 given <replaceable>operator</replaceable>, which must yield a Boolean
24264 result.
24265 The result of <token>ANY</token> is <quote>true</quote> if any true result is obtained.
24266 The result is <quote>false</quote> if no true result is found (including the
24267 case where the array has zero elements).
24268 </para>
24269
24270 <para>
24271 If the array expression yields a null array, the result of
24272 <token>ANY</token> will be null. If the left-hand expression yields null,
24273 the result of <token>ANY</token> is ordinarily null (though a non-strict
24274 comparison operator could possibly yield a different result).
24275 Also, if the right-hand array contains any null elements and no true
24276 comparison result is obtained, the result of <token>ANY</token>
24277 will be null, not false (again, assuming a strict comparison operator).
24278 This is in accordance with SQL's normal rules for Boolean combinations
24279 of null values.
24280 </para>
24281
24282 <para>
24283 <token>SOME</token> is a synonym for <token>ANY</token>.
24284 </para>
24285 </sect2>
24286
24287 <sect2 id="functions-comparisons-all">
24288 <title><literal>ALL</literal> (array)</title>
24289
24290 <synopsis>
24291 <replaceable>expression</replaceable> <replaceable>operator</replaceable> ALL (<replaceable>array expression</replaceable>)
24292 </synopsis>
24293
24294 <para>
24295 The right-hand side is a parenthesized expression, which must yield an
24296 array value.
24297 The left-hand expression
24298 is evaluated and compared to each element of the array using the
24299 given <replaceable>operator</replaceable>, which must yield a Boolean
24300 result.
24301 The result of <token>ALL</token> is <quote>true</quote> if all comparisons yield true
24302 (including the case where the array has zero elements).
24303 The result is <quote>false</quote> if any false result is found.
24304 </para>
24305
24306 <para>
24307 If the array expression yields a null array, the result of
24308 <token>ALL</token> will be null. If the left-hand expression yields null,
24309 the result of <token>ALL</token> is ordinarily null (though a non-strict
24310 comparison operator could possibly yield a different result).
24311 Also, if the right-hand array contains any null elements and no false
24312 comparison result is obtained, the result of <token>ALL</token>
24313 will be null, not true (again, assuming a strict comparison operator).
24314 This is in accordance with SQL's normal rules for Boolean combinations
24315 of null values.
24316 </para>
24317 </sect2>
24318
24319 <sect2 id="row-wise-comparison">
24320 <title>Row Constructor Comparison</title>
24321
24322 <synopsis>
24323 <replaceable>row_constructor</replaceable> <replaceable>operator</replaceable> <replaceable>row_constructor</replaceable>
24324 </synopsis>
24325
24326 <para>
24327 Each side is a row constructor,
24328 as described in <xref linkend="sql-syntax-row-constructors"/>.
24329 The two row constructors must have the same number of fields.
24330 The given <replaceable>operator</replaceable> is applied to each pair
24331 of corresponding fields. (Since the fields could be of different
24332 types, this means that a different specific operator could be selected
24333 for each pair.)
24334 All the selected operators must be members of some B-tree operator
24335 class, or be the negator of an <literal>=</literal> member of a B-tree
24336 operator class, meaning that row constructor comparison is only
24337 possible when the <replaceable>operator</replaceable> is
24338 <literal>=</literal>,
24339 <literal>&lt;&gt;</literal>,
24340 <literal>&lt;</literal>,
24341 <literal>&lt;=</literal>,
24342 <literal>&gt;</literal>, or
24343 <literal>&gt;=</literal>,
24344 or has semantics similar to one of these.
24345 </para>
24346
24347 <para>
24348 The <literal>=</literal> and <literal>&lt;&gt;</literal> cases work slightly differently
24349 from the others. Two rows are considered
24350 equal if all their corresponding members are non-null and equal; the rows
24351 are unequal if any corresponding members are non-null and unequal;
24352 otherwise the result of the row comparison is unknown (null).
24353 </para>
24354
24355 <para>
24356 For the <literal>&lt;</literal>, <literal>&lt;=</literal>, <literal>&gt;</literal> and
24357 <literal>&gt;=</literal> cases, the row elements are compared left-to-right,
24358 stopping as soon as an unequal or null pair of elements is found.
24359 If either of this pair of elements is null, the result of the
24360 row comparison is unknown (null); otherwise comparison of this pair
24361 of elements determines the result. For example,
24362 <literal>ROW(1,2,NULL) &lt; ROW(1,3,0)</literal>
24363 yields true, not null, because the third pair of elements are not
24364 considered.
24365 </para>
24366
24367 <synopsis>
24368 <replaceable>row_constructor</replaceable> IS DISTINCT FROM <replaceable>row_constructor</replaceable>
24369 </synopsis>
24370
24371 <para>
24372 This construct is similar to a <literal>&lt;&gt;</literal> row comparison,
24373 but it does not yield null for null inputs. Instead, any null value is
24374 considered unequal to (distinct from) any non-null value, and any two
24375 nulls are considered equal (not distinct). Thus the result will
24376 either be true or false, never null.
24377 </para>
24378
24379 <synopsis>
24380 <replaceable>row_constructor</replaceable> IS NOT DISTINCT FROM <replaceable>row_constructor</replaceable>
24381 </synopsis>
24382
24383 <para>
24384 This construct is similar to a <literal>=</literal> row comparison,
24385 but it does not yield null for null inputs. Instead, any null value is
24386 considered unequal to (distinct from) any non-null value, and any two
24387 nulls are considered equal (not distinct). Thus the result will always
24388 be either true or false, never null.
24389 </para>
24390
24391 </sect2>
24392
24393 <sect2 id="composite-type-comparison">
24394 <title>Composite Type Comparison</title>
24395
24396 <synopsis>
24397 <replaceable>record</replaceable> <replaceable>operator</replaceable> <replaceable>record</replaceable>
24398 </synopsis>
24399
24400 <para>
24401 The SQL specification requires row-wise comparison to return NULL if the
24402 result depends on comparing two NULL values or a NULL and a non-NULL.
24403 <productname>PostgreSQL</productname> does this only when comparing the
24404 results of two row constructors (as in
24405 <xref linkend="row-wise-comparison"/>) or comparing a row constructor
24406 to the output of a subquery (as in <xref linkend="functions-subquery"/>).
24407 In other contexts where two composite-type values are compared, two
24408 NULL field values are considered equal, and a NULL is considered larger
24409 than a non-NULL. This is necessary in order to have consistent sorting
24410 and indexing behavior for composite types.
24411 </para>
24412
24413 <para>
24414 Each side is evaluated and they are compared row-wise. Composite type
24415 comparisons are allowed when the <replaceable>operator</replaceable> is
24416 <literal>=</literal>,
24417 <literal>&lt;&gt;</literal>,
24418 <literal>&lt;</literal>,
24419 <literal>&lt;=</literal>,
24420 <literal>&gt;</literal> or
24421 <literal>&gt;=</literal>,
24422 or has semantics similar to one of these. (To be specific, an operator
24423 can be a row comparison operator if it is a member of a B-tree operator
24424 class, or is the negator of the <literal>=</literal> member of a B-tree operator
24425 class.) The default behavior of the above operators is the same as for
24426 <literal>IS [ NOT ] DISTINCT FROM</literal> for row constructors (see
24427 <xref linkend="row-wise-comparison"/>).
24428 </para>
24429
24430 <para>
24431 To support matching of rows which include elements without a default
24432 B-tree operator class, the following operators are defined for composite
24433 type comparison:
24434 <literal>*=</literal>,
24435 <literal>*&lt;&gt;</literal>,
24436 <literal>*&lt;</literal>,
24437 <literal>*&lt;=</literal>,
24438 <literal>*&gt;</literal>, and
24439 <literal>*&gt;=</literal>.
24440 These operators compare the internal binary representation of the two
24441 rows. Two rows might have a different binary representation even
24442 though comparisons of the two rows with the equality operator is true.
24443 The ordering of rows under these comparison operators is deterministic
24444 but not otherwise meaningful. These operators are used internally
24445 for materialized views and might be useful for other specialized
24446 purposes such as replication and B-Tree deduplication (see <xref
24447 linkend="btree-deduplication"/>). They are not intended to be
24448 generally useful for writing queries, though.
24449 </para>
24450 </sect2>
24451 </sect1>
24452
24453 <sect1 id="functions-srf">
24454 <title>Set Returning Functions</title>
24455
24456 <indexterm zone="functions-srf">
24457 <primary>set returning functions</primary>
24458 <secondary>functions</secondary>
24459 </indexterm>
24460
24461 <para>
24462 This section describes functions that possibly return more than one row.
24463 The most widely used functions in this class are series generating
24464 functions, as detailed in <xref linkend="functions-srf-series"/> and
24465 <xref linkend="functions-srf-subscripts"/>. Other, more specialized
24466 set-returning functions are described elsewhere in this manual.
24467 See <xref linkend="queries-tablefunctions"/> for ways to combine multiple
24468 set-returning functions.
24469 </para>
24470
24471 <table id="functions-srf-series">
24472 <title>Series Generating Functions</title>
24473 <tgroup cols="1">
24474 <thead>
24475 <row>
24476 <entry role="func_table_entry"><para role="func_signature">
24477 Function
24478 </para>
24479 <para>
24480 Description
24481 </para></entry>
24482 </row>
24483 </thead>
24484
24485 <tbody>
24486 <row>
24487 <entry role="func_table_entry"><para role="func_signature">
24488 <indexterm>
24489 <primary>generate_series</primary>
24490 </indexterm>
24491 <function>generate_series</function> ( <parameter>start</parameter> <type>integer</type>, <parameter>stop</parameter> <type>integer</type> <optional>, <parameter>step</parameter> <type>integer</type> </optional> )
24492 <returnvalue>setof integer</returnvalue>
24493 </para>
24494 <para role="func_signature">
24495 <function>generate_series</function> ( <parameter>start</parameter> <type>bigint</type>, <parameter>stop</parameter> <type>bigint</type> <optional>, <parameter>step</parameter> <type>bigint</type> </optional> )
24496 <returnvalue>setof bigint</returnvalue>
24497 </para>
24498 <para role="func_signature">
24499 <function>generate_series</function> ( <parameter>start</parameter> <type>numeric</type>, <parameter>stop</parameter> <type>numeric</type> <optional>, <parameter>step</parameter> <type>numeric</type> </optional> )
24500 <returnvalue>setof numeric</returnvalue>
24501 </para>
24502 <para>
24503 Generates a series of values from <parameter>start</parameter>
24504 to <parameter>stop</parameter>, with a step size
24505 of <parameter>step</parameter>. <parameter>step</parameter>
24506 defaults to 1.
24507 </para></entry>
24508 </row>
24509
24510 <row>
24511 <entry role="func_table_entry"><para role="func_signature">
24512 <function>generate_series</function> ( <parameter>start</parameter> <type>timestamp</type>, <parameter>stop</parameter> <type>timestamp</type>, <parameter>step</parameter> <type>interval</type> )
24513 <returnvalue>setof timestamp</returnvalue>
24514 </para>
24515 <para role="func_signature">
24516 <function>generate_series</function> ( <parameter>start</parameter> <type>timestamp with time zone</type>, <parameter>stop</parameter> <type>timestamp with time zone</type>, <parameter>step</parameter> <type>interval</type> <optional>, <parameter>timezone</parameter> <type>text</type> </optional> )
24517 <returnvalue>setof timestamp with time zone</returnvalue>
24518 </para>
24519 <para>
24520 Generates a series of values from <parameter>start</parameter>
24521 to <parameter>stop</parameter>, with a step size
24522 of <parameter>step</parameter>.
24523 In the timezone-aware form, times of day and daylight-savings
24524 adjustments are computed according to the time zone named by
24525 the <parameter>timezone</parameter> argument, or the current
24526 <xref linkend="guc-timezone"/> setting if that is omitted.
24527 </para></entry>
24528 </row>
24529 </tbody>
24530 </tgroup>
24531 </table>
24532
24533 <para>
24534 When <parameter>step</parameter> is positive, zero rows are returned if
24535 <parameter>start</parameter> is greater than <parameter>stop</parameter>.
24536 Conversely, when <parameter>step</parameter> is negative, zero rows are
24537 returned if <parameter>start</parameter> is less than <parameter>stop</parameter>.
24538 Zero rows are also returned if any input is <literal>NULL</literal>.
24539 It is an error
24540 for <parameter>step</parameter> to be zero. Some examples follow:
24541 <programlisting>
24542 SELECT * FROM generate_series(2,4);
24543 generate_series
24544 -----------------
24545 2
24546 3
24547 4
24548 (3 rows)
24549
24550 SELECT * FROM generate_series(5,1,-2);
24551 generate_series
24552 -----------------
24553 5
24554 3
24555 1
24556 (3 rows)
24557
24558 SELECT * FROM generate_series(4,3);
24559 generate_series
24560 -----------------
24561 (0 rows)
24562
24563 SELECT generate_series(1.1, 4, 1.3);
24564 generate_series
24565 -----------------
24566 1.1
24567 2.4
24568 3.7
24569 (3 rows)
24570
24571 -- this example relies on the date-plus-integer operator:
24572 SELECT current_date + s.a AS dates FROM generate_series(0,14,7) AS s(a);
24573 dates
24574 ------------
24575 2004-02-05
24576 2004-02-12
24577 2004-02-19
24578 (3 rows)
24579
24580 SELECT * FROM generate_series('2008-03-01 00:00'::timestamp,
24581 '2008-03-04 12:00', '10 hours');
24582 generate_series
24583 ---------------------
24584 2008-03-01 00:00:00
24585 2008-03-01 10:00:00
24586 2008-03-01 20:00:00
24587 2008-03-02 06:00:00
24588 2008-03-02 16:00:00
24589 2008-03-03 02:00:00
24590 2008-03-03 12:00:00
24591 2008-03-03 22:00:00
24592 2008-03-04 08:00:00
24593 (9 rows)
24594
24595 -- this example assumes that TimeZone is set to UTC; note the DST transition:
24596 SELECT * FROM generate_series('2001-10-22 00:00 -04:00'::timestamptz,
24597 '2001-11-01 00:00 -05:00'::timestamptz,
24598 '1 day'::interval, 'America/New_York');
24599 generate_series
24600 ------------------------
24601 2001-10-22 04:00:00+00
24602 2001-10-23 04:00:00+00
24603 2001-10-24 04:00:00+00
24604 2001-10-25 04:00:00+00
24605 2001-10-26 04:00:00+00
24606 2001-10-27 04:00:00+00
24607 2001-10-28 04:00:00+00
24608 2001-10-29 05:00:00+00
24609 2001-10-30 05:00:00+00
24610 2001-10-31 05:00:00+00
24611 2001-11-01 05:00:00+00
24612 (11 rows)
24613 </programlisting>
24614 </para>
24615
24616 <table id="functions-srf-subscripts">
24617 <title>Subscript Generating Functions</title>
24618 <tgroup cols="1">
24619 <thead>
24620 <row>
24621 <entry role="func_table_entry"><para role="func_signature">
24622 Function
24623 </para>
24624 <para>
24625 Description
24626 </para></entry>
24627 </row>
24628 </thead>
24629
24630 <tbody>
24631 <row>
24632 <entry role="func_table_entry"><para role="func_signature">
24633 <indexterm>
24634 <primary>generate_subscripts</primary>
24635 </indexterm>
24636 <function>generate_subscripts</function> ( <parameter>array</parameter> <type>anyarray</type>, <parameter>dim</parameter> <type>integer</type> )
24637 <returnvalue>setof integer</returnvalue>
24638 </para>
24639 <para>
24640 Generates a series comprising the valid subscripts of
24641 the <parameter>dim</parameter>'th dimension of the given array.
24642 </para></entry>
24643 </row>
24644
24645 <row>
24646 <entry role="func_table_entry"><para role="func_signature">
24647 <function>generate_subscripts</function> ( <parameter>array</parameter> <type>anyarray</type>, <parameter>dim</parameter> <type>integer</type>, <parameter>reverse</parameter> <type>boolean</type> )
24648 <returnvalue>setof integer</returnvalue>
24649 </para>
24650 <para>
24651 Generates a series comprising the valid subscripts of
24652 the <parameter>dim</parameter>'th dimension of the given array.
24653 When <parameter>reverse</parameter> is true, returns the series in
24654 reverse order.
24655 </para></entry>
24656 </row>
24657 </tbody>
24658 </tgroup>
24659 </table>
24660
24661 <para>
24662 <function>generate_subscripts</function> is a convenience function that generates
24663 the set of valid subscripts for the specified dimension of the given
24664 array.
24665 Zero rows are returned for arrays that do not have the requested dimension,
24666 or if any input is <literal>NULL</literal>.
24667 Some examples follow:
24668 <programlisting>
24669 -- basic usage:
24670 SELECT generate_subscripts('{NULL,1,NULL,2}'::int[], 1) AS s;
24671 s
24672 ---
24673 1
24674 2
24675 3
24676 4
24677 (4 rows)
24678
24679 -- presenting an array, the subscript and the subscripted
24680 -- value requires a subquery:
24681 SELECT * FROM arrays;
24682 a
24683 --------------------
24684 {-1,-2}
24685 {100,200,300}
24686 (2 rows)
24687
24688 SELECT a AS array, s AS subscript, a[s] AS value
24689 FROM (SELECT generate_subscripts(a, 1) AS s, a FROM arrays) foo;
24690 array | subscript | value
24691 ---------------+-----------+-------
24692 {-1,-2} | 1 | -1
24693 {-1,-2} | 2 | -2
24694 {100,200,300} | 1 | 100
24695 {100,200,300} | 2 | 200
24696 {100,200,300} | 3 | 300
24697 (5 rows)
24698
24699 -- unnest a 2D array:
24700 CREATE OR REPLACE FUNCTION unnest2(anyarray)
24701 RETURNS SETOF anyelement AS $$
24702 select $1[i][j]
24703 from generate_subscripts($1,1) g1(i),
24704 generate_subscripts($1,2) g2(j);
24705 $$ LANGUAGE sql IMMUTABLE;
24706 CREATE FUNCTION
24707 SELECT * FROM unnest2(ARRAY[[1,2],[3,4]]);
24708 unnest2
24709 ---------
24710 1
24711 2
24712 3
24713 4
24714 (4 rows)
24715 </programlisting>
24716 </para>
24717
24718 <indexterm>
24719 <primary>ordinality</primary>
24720 </indexterm>
24721
24722 <para>
24723 When a function in the <literal>FROM</literal> clause is suffixed
24724 by <literal>WITH ORDINALITY</literal>, a <type>bigint</type> column is
24725 appended to the function's output column(s), which starts from 1 and
24726 increments by 1 for each row of the function's output.
24727 This is most useful in the case of set returning
24728 functions such as <function>unnest()</function>.
24729
24730 <programlisting>
24731 -- set returning function WITH ORDINALITY:
24732 SELECT * FROM pg_ls_dir('.') WITH ORDINALITY AS t(ls,n);
24733 ls | n
24734 -----------------+----
24735 pg_serial | 1
24736 pg_twophase | 2
24737 postmaster.opts | 3
24738 pg_notify | 4
24739 postgresql.conf | 5
24740 pg_tblspc | 6
24741 logfile | 7
24742 base | 8
24743 postmaster.pid | 9
24744 pg_ident.conf | 10
24745 global | 11
24746 pg_xact | 12
24747 pg_snapshots | 13
24748 pg_multixact | 14
24749 PG_VERSION | 15
24750 pg_wal | 16
24751 pg_hba.conf | 17
24752 pg_stat_tmp | 18
24753 pg_subtrans | 19
24754 (19 rows)
24755 </programlisting>
24756 </para>
24757
24758 </sect1>
24759
24760 <sect1 id="functions-info">
24761 <title>System Information Functions and Operators</title>
24762
24763 <para>
24764 The functions described in this section are used to obtain various
24765 information about a <productname>PostgreSQL</productname> installation.
24766 </para>
24767
24768 <sect2 id="functions-info-session">
24769 <title>Session Information Functions</title>
24770
24771 <para>
24772 <xref linkend="functions-info-session-table"/> shows several
24773 functions that extract session and system information.
24774 </para>
24775
24776 <para>
24777 In addition to the functions listed in this section, there are a number of
24778 functions related to the statistics system that also provide system
24779 information. See <xref linkend="monitoring-stats-functions"/> for more
24780 information.
24781 </para>
24782
24783 <table id="functions-info-session-table">
24784 <title>Session Information Functions</title>
24785 <tgroup cols="1">
24786 <thead>
24787 <row>
24788 <entry role="func_table_entry"><para role="func_signature">
24789 Function
24790 </para>
24791 <para>
24792 Description
24793 </para></entry>
24794 </row>
24795 </thead>
24796
24797 <tbody>
24798 <row>
24799 <entry role="func_table_entry"><para role="func_signature">
24800 <indexterm>
24801 <primary>current_catalog</primary>
24802 </indexterm>
24803 <function>current_catalog</function>
24804 <returnvalue>name</returnvalue>
24805 </para>
24806 <para role="func_signature">
24807 <indexterm>
24808 <primary>current_database</primary>
24809 </indexterm>
24810 <function>current_database</function> ()
24811 <returnvalue>name</returnvalue>
24812 </para>
24813 <para>
24814 Returns the name of the current database. (Databases are
24815 called <quote>catalogs</quote> in the SQL standard,
24816 so <function>current_catalog</function> is the standard's
24817 spelling.)
24818 </para></entry>
24819 </row>
24820
24821 <row>
24822 <entry role="func_table_entry"><para role="func_signature">
24823 <indexterm>
24824 <primary>current_query</primary>
24825 </indexterm>
24826 <function>current_query</function> ()
24827 <returnvalue>text</returnvalue>
24828 </para>
24829 <para>
24830 Returns the text of the currently executing query, as submitted
24831 by the client (which might contain more than one statement).
24832 </para></entry>
24833 </row>
24834
24835 <row>
24836 <entry role="func_table_entry"><para role="func_signature">
24837 <indexterm>
24838 <primary>current_role</primary>
24839 </indexterm>
24840 <function>current_role</function>
24841 <returnvalue>name</returnvalue>
24842 </para>
24843 <para>
24844 This is equivalent to <function>current_user</function>.
24845 </para></entry>
24846 </row>
24847
24848 <row>
24849 <entry role="func_table_entry"><para role="func_signature">
24850 <indexterm>
24851 <primary>current_schema</primary>
24852 </indexterm>
24853 <indexterm>
24854 <primary>schema</primary>
24855 <secondary>current</secondary>
24856 </indexterm>
24857 <function>current_schema</function>
24858 <returnvalue>name</returnvalue>
24859 </para>
24860 <para role="func_signature">
24861 <function>current_schema</function> ()
24862 <returnvalue>name</returnvalue>
24863 </para>
24864 <para>
24865 Returns the name of the schema that is first in the search path (or a
24866 null value if the search path is empty). This is the schema that will
24867 be used for any tables or other named objects that are created without
24868 specifying a target schema.
24869 </para></entry>
24870 </row>
24871
24872 <row>
24873 <entry role="func_table_entry"><para role="func_signature">
24874 <indexterm>
24875 <primary>current_schemas</primary>
24876 </indexterm>
24877 <indexterm>
24878 <primary>search path</primary>
24879 <secondary>current</secondary>
24880 </indexterm>
24881 <function>current_schemas</function> ( <parameter>include_implicit</parameter> <type>boolean</type> )
24882 <returnvalue>name[]</returnvalue>
24883 </para>
24884 <para>
24885 Returns an array of the names of all schemas presently in the
24886 effective search path, in their priority order. (Items in the current
24887 <xref linkend="guc-search-path"/> setting that do not correspond to
24888 existing, searchable schemas are omitted.) If the Boolean argument
24889 is <literal>true</literal>, then implicitly-searched system schemas
24890 such as <literal>pg_catalog</literal> are included in the result.
24891 </para></entry>
24892 </row>
24893
24894 <row>
24895 <entry role="func_table_entry"><para role="func_signature">
24896 <indexterm>
24897 <primary>current_user</primary>
24898 </indexterm>
24899 <indexterm>
24900 <primary>user</primary>
24901 <secondary>current</secondary>
24902 </indexterm>
24903 <function>current_user</function>
24904 <returnvalue>name</returnvalue>
24905 </para>
24906 <para>
24907 Returns the user name of the current execution context.
24908 </para></entry>
24909 </row>
24910
24911 <row>
24912 <entry role="func_table_entry"><para role="func_signature">
24913 <indexterm>
24914 <primary>inet_client_addr</primary>
24915 </indexterm>
24916 <function>inet_client_addr</function> ()
24917 <returnvalue>inet</returnvalue>
24918 </para>
24919 <para>
24920 Returns the IP address of the current client,
24921 or <literal>NULL</literal> if the current connection is via a
24922 Unix-domain socket.
24923 </para></entry>
24924 </row>
24925
24926 <row>
24927 <entry role="func_table_entry"><para role="func_signature">
24928 <indexterm>
24929 <primary>inet_client_port</primary>
24930 </indexterm>
24931 <function>inet_client_port</function> ()
24932 <returnvalue>integer</returnvalue>
24933 </para>
24934 <para>
24935 Returns the IP port number of the current client,
24936 or <literal>NULL</literal> if the current connection is via a
24937 Unix-domain socket.
24938 </para></entry>
24939 </row>
24940
24941 <row>
24942 <entry role="func_table_entry"><para role="func_signature">
24943 <indexterm>
24944 <primary>inet_server_addr</primary>
24945 </indexterm>
24946 <function>inet_server_addr</function> ()
24947 <returnvalue>inet</returnvalue>
24948 </para>
24949 <para>
24950 Returns the IP address on which the server accepted the current
24951 connection,
24952 or <literal>NULL</literal> if the current connection is via a
24953 Unix-domain socket.
24954 </para></entry>
24955 </row>
24956
24957 <row>
24958 <entry role="func_table_entry"><para role="func_signature">
24959 <indexterm>
24960 <primary>inet_server_port</primary>
24961 </indexterm>
24962 <function>inet_server_port</function> ()
24963 <returnvalue>integer</returnvalue>
24964 </para>
24965 <para>
24966 Returns the IP port number on which the server accepted the current
24967 connection,
24968 or <literal>NULL</literal> if the current connection is via a
24969 Unix-domain socket.
24970 </para></entry>
24971 </row>
24972
24973 <row>
24974 <entry role="func_table_entry"><para role="func_signature">
24975 <indexterm>
24976 <primary>pg_backend_pid</primary>
24977 </indexterm>
24978 <function>pg_backend_pid</function> ()
24979 <returnvalue>integer</returnvalue>
24980 </para>
24981 <para>
24982 Returns the process ID of the server process attached to the current
24983 session.
24984 </para></entry>
24985 </row>
24986
24987 <row>
24988 <entry role="func_table_entry"><para role="func_signature">
24989 <indexterm>
24990 <primary>pg_blocking_pids</primary>
24991 </indexterm>
24992 <function>pg_blocking_pids</function> ( <type>integer</type> )
24993 <returnvalue>integer[]</returnvalue>
24994 </para>
24995 <para>
24996 Returns an array of the process ID(s) of the sessions that are
24997 blocking the server process with the specified process ID from
24998 acquiring a lock, or an empty array if there is no such server process
24999 or it is not blocked.
25000 </para>
25001 <para>
25002 One server process blocks another if it either holds a lock that
25003 conflicts with the blocked process's lock request (hard block), or is
25004 waiting for a lock that would conflict with the blocked process's lock
25005 request and is ahead of it in the wait queue (soft block). When using
25006 parallel queries the result always lists client-visible process IDs
25007 (that is, <function>pg_backend_pid</function> results) even if the
25008 actual lock is held or awaited by a child worker process. As a result
25009 of that, there may be duplicated PIDs in the result. Also note that
25010 when a prepared transaction holds a conflicting lock, it will be
25011 represented by a zero process ID.
25012 </para>
25013 <para>
25014 Frequent calls to this function could have some impact on database
25015 performance, because it needs exclusive access to the lock manager's
25016 shared state for a short time.
25017 </para></entry>
25018 </row>
25019
25020 <row>
25021 <entry role="func_table_entry"><para role="func_signature">
25022 <indexterm>
25023 <primary>pg_conf_load_time</primary>
25024 </indexterm>
25025 <function>pg_conf_load_time</function> ()
25026 <returnvalue>timestamp with time zone</returnvalue>
25027 </para>
25028 <para>
25029 Returns the time when the server configuration files were last loaded.
25030 If the current session was alive at the time, this will be the time
25031 when the session itself re-read the configuration files (so the
25032 reading will vary a little in different sessions). Otherwise it is
25033 the time when the postmaster process re-read the configuration files.
25034 </para></entry>
25035 </row>
25036
25037 <row>
25038 <entry role="func_table_entry"><para role="func_signature">
25039 <indexterm>
25040 <primary>pg_current_logfile</primary>
25041 </indexterm>
25042 <indexterm>
25043 <primary>Logging</primary>
25044 <secondary>pg_current_logfile function</secondary>
25045 </indexterm>
25046 <indexterm>
25047 <primary>current_logfiles</primary>
25048 <secondary>and the pg_current_logfile function</secondary>
25049 </indexterm>
25050 <indexterm>
25051 <primary>Logging</primary>
25052 <secondary>current_logfiles file and the pg_current_logfile
25053 function</secondary>
25054 </indexterm>
25055 <function>pg_current_logfile</function> ( <optional> <type>text</type> </optional> )
25056 <returnvalue>text</returnvalue>
25057 </para>
25058 <para>
25059 Returns the path name of the log file currently in use by the logging
25060 collector. The path includes the <xref linkend="guc-log-directory"/>
25061 directory and the individual log file name. The result
25062 is <literal>NULL</literal> if the logging collector is disabled.
25063 When multiple log files exist, each in a different
25064 format, <function>pg_current_logfile</function> without an argument
25065 returns the path of the file having the first format found in the
25066 ordered list: <literal>stderr</literal>,
25067 <literal>csvlog</literal>, <literal>jsonlog</literal>.
25068 <literal>NULL</literal> is returned if no log file has any of these
25069 formats.
25070 To request information about a specific log file format, supply
25071 either <literal>csvlog</literal>, <literal>jsonlog</literal> or
25072 <literal>stderr</literal> as the
25073 value of the optional parameter. The result is <literal>NULL</literal>
25074 if the log format requested is not configured in
25075 <xref linkend="guc-log-destination"/>.
25076 The result reflects the contents of
25077 the <filename>current_logfiles</filename> file.
25078 </para>
25079 <para>
25080 This function is restricted to superusers and roles with privileges of
25081 the <literal>pg_monitor</literal> role by default, but other users can
25082 be granted EXECUTE to run the function.
25083 </para></entry>
25084 </row>
25085
25086 <row>
25087 <entry role="func_table_entry"><para role="func_signature">
25088 <indexterm>
25089 <primary>pg_get_loaded_modules</primary>
25090 </indexterm>
25091 <function>pg_get_loaded_modules</function> ()
25092 <returnvalue>setof record</returnvalue>
25093 ( <parameter>module_name</parameter> <type>text</type>,
25094 <parameter>version</parameter> <type>text</type>,
25095 <parameter>file_name</parameter> <type>text</type> )
25096 </para>
25097 <para>
25098 Returns a list of the loadable modules that are loaded into the
25099 current server session. The <parameter>module_name</parameter>
25100 and <parameter>version</parameter> fields are NULL unless the
25101 module author supplied values for them using
25102 the <literal>PG_MODULE_MAGIC_EXT</literal> macro.
25103 The <parameter>file_name</parameter> field gives the file
25104 name of the module (shared library).
25105 </para></entry>
25106 </row>
25107
25108 <row>
25109 <entry role="func_table_entry"><para role="func_signature">
25110 <indexterm>
25111 <primary>pg_my_temp_schema</primary>
25112 </indexterm>
25113 <function>pg_my_temp_schema</function> ()
25114 <returnvalue>oid</returnvalue>
25115 </para>
25116 <para>
25117 Returns the OID of the current session's temporary schema, or zero if
25118 it has none (because it has not created any temporary tables).
25119 </para></entry>
25120 </row>
25121
25122 <row>
25123 <entry role="func_table_entry"><para role="func_signature">
25124 <indexterm>
25125 <primary>pg_is_other_temp_schema</primary>
25126 </indexterm>
25127 <function>pg_is_other_temp_schema</function> ( <type>oid</type> )
25128 <returnvalue>boolean</returnvalue>
25129 </para>
25130 <para>
25131 Returns true if the given OID is the OID of another session's
25132 temporary schema. (This can be useful, for example, to exclude other
25133 sessions' temporary tables from a catalog display.)
25134 </para></entry>
25135 </row>
25136
25137 <row>
25138 <entry role="func_table_entry"><para role="func_signature">
25139 <indexterm>
25140 <primary>pg_jit_available</primary>
25141 </indexterm>
25142 <function>pg_jit_available</function> ()
25143 <returnvalue>boolean</returnvalue>
25144 </para>
25145 <para>
25146 Returns true if a <acronym>JIT</acronym> compiler extension is
25147 available (see <xref linkend="jit"/>) and the
25148 <xref linkend="guc-jit"/> configuration parameter is set to
25149 <literal>on</literal>.
25150 </para></entry>
25151 </row>
25152
25153 <row>
25154 <entry role="func_table_entry"><para role="func_signature">
25155 <indexterm>
25156 <primary>pg_numa_available</primary>
25157 </indexterm>
25158 <function>pg_numa_available</function> ()
25159 <returnvalue>boolean</returnvalue>
25160 </para>
25161 <para>
25162 Returns true if the server has been compiled with <acronym>NUMA</acronym> support.
25163 </para></entry>
25164 </row>
25165
25166 <row>
25167 <entry role="func_table_entry"><para role="func_signature">
25168 <indexterm>
25169 <primary>pg_listening_channels</primary>
25170 </indexterm>
25171 <function>pg_listening_channels</function> ()
25172 <returnvalue>setof text</returnvalue>
25173 </para>
25174 <para>
25175 Returns the set of names of asynchronous notification channels that
25176 the current session is listening to.
25177 </para></entry>
25178 </row>
25179
25180 <row>
25181 <entry role="func_table_entry"><para role="func_signature">
25182 <indexterm>
25183 <primary>pg_notification_queue_usage</primary>
25184 </indexterm>
25185 <function>pg_notification_queue_usage</function> ()
25186 <returnvalue>double precision</returnvalue>
25187 </para>
25188 <para>
25189 Returns the fraction (0&ndash;1) of the asynchronous notification
25190 queue's maximum size that is currently occupied by notifications that
25191 are waiting to be processed.
25192 See <xref linkend="sql-listen"/> and <xref linkend="sql-notify"/>
25193 for more information.
25194 </para></entry>
25195 </row>
25196
25197 <row>
25198 <entry role="func_table_entry"><para role="func_signature">
25199 <indexterm>
25200 <primary>pg_postmaster_start_time</primary>
25201 </indexterm>
25202 <function>pg_postmaster_start_time</function> ()
25203 <returnvalue>timestamp with time zone</returnvalue>
25204 </para>
25205 <para>
25206 Returns the time when the server started.
25207 </para></entry>
25208 </row>
25209
25210 <row>
25211 <entry role="func_table_entry"><para role="func_signature">
25212 <indexterm>
25213 <primary>pg_safe_snapshot_blocking_pids</primary>
25214 </indexterm>
25215 <function>pg_safe_snapshot_blocking_pids</function> ( <type>integer</type> )
25216 <returnvalue>integer[]</returnvalue>
25217 </para>
25218 <para>
25219 Returns an array of the process ID(s) of the sessions that are blocking
25220 the server process with the specified process ID from acquiring a safe
25221 snapshot, or an empty array if there is no such server process or it
25222 is not blocked.
25223 </para>
25224 <para>
25225 A session running a <literal>SERIALIZABLE</literal> transaction blocks
25226 a <literal>SERIALIZABLE READ ONLY DEFERRABLE</literal> transaction
25227 from acquiring a snapshot until the latter determines that it is safe
25228 to avoid taking any predicate locks. See
25229 <xref linkend="xact-serializable"/> for more information about
25230 serializable and deferrable transactions.
25231 </para>
25232 <para>
25233 Frequent calls to this function could have some impact on database
25234 performance, because it needs access to the predicate lock manager's
25235 shared state for a short time.
25236 </para></entry>
25237 </row>
25238
25239 <row>
25240 <entry role="func_table_entry"><para role="func_signature">
25241 <indexterm>
25242 <primary>pg_trigger_depth</primary>
25243 </indexterm>
25244 <function>pg_trigger_depth</function> ()
25245 <returnvalue>integer</returnvalue>
25246 </para>
25247 <para>
25248 Returns the current nesting level
25249 of <productname>PostgreSQL</productname> triggers (0 if not called,
25250 directly or indirectly, from inside a trigger).
25251 </para></entry>
25252 </row>
25253
25254 <row>
25255 <entry role="func_table_entry"><para role="func_signature">
25256 <indexterm>
25257 <primary>session_user</primary>
25258 </indexterm>
25259 <function>session_user</function>
25260 <returnvalue>name</returnvalue>
25261 </para>
25262 <para>
25263 Returns the session user's name.
25264 </para></entry>
25265 </row>
25266
25267 <row>
25268 <entry role="func_table_entry"><para role="func_signature">
25269 <indexterm>
25270 <primary>system_user</primary>
25271 </indexterm>
25272 <function>system_user</function>
25273 <returnvalue>text</returnvalue>
25274 </para>
25275 <para>
25276 Returns the authentication method and the identity (if any) that the
25277 user presented during the authentication cycle before they were
25278 assigned a database role. It is represented as
25279 <literal>auth_method:identity</literal> or
25280 <literal>NULL</literal> if the user has not been authenticated (for
25281 example if <link linkend="auth-trust">Trust authentication</link> has
25282 been used).
25283 </para></entry>
25284 </row>
25285
25286 <row>
25287 <entry role="func_table_entry"><para role="func_signature">
25288 <indexterm>
25289 <primary>user</primary>
25290 </indexterm>
25291 <function>user</function>
25292 <returnvalue>name</returnvalue>
25293 </para>
25294 <para>
25295 This is equivalent to <function>current_user</function>.
25296 </para></entry>
25297 </row>
25298 </tbody>
25299 </tgroup>
25300 </table>
25301
25302 <note>
25303 <para>
25304 <function>current_catalog</function>,
25305 <function>current_role</function>,
25306 <function>current_schema</function>,
25307 <function>current_user</function>,
25308 <function>session_user</function>,
25309 and <function>user</function> have special syntactic status
25310 in <acronym>SQL</acronym>: they must be called without trailing
25311 parentheses. In PostgreSQL, parentheses can optionally be used with
25312 <function>current_schema</function>, but not with the others.
25313 </para>
25314 </note>
25315
25316 <para>
25317 The <function>session_user</function> is normally the user who initiated
25318 the current database connection; but superusers can change this setting
25319 with <xref linkend="sql-set-session-authorization"/>.
25320 The <function>current_user</function> is the user identifier
25321 that is applicable for permission checking. Normally it is equal
25322 to the session user, but it can be changed with
25323 <xref linkend="sql-set-role"/>.
25324 It also changes during the execution of
25325 functions with the attribute <literal>SECURITY DEFINER</literal>.
25326 In Unix parlance, the session user is the <quote>real user</quote> and
25327 the current user is the <quote>effective user</quote>.
25328 <function>current_role</function> and <function>user</function> are
25329 synonyms for <function>current_user</function>. (The SQL standard draws
25330 a distinction between <function>current_role</function>
25331 and <function>current_user</function>, but <productname>PostgreSQL</productname>
25332 does not, since it unifies users and roles into a single kind of entity.)
25333 </para>
25334
25335 </sect2>
25336
25337 <sect2 id="functions-info-access">
25338 <title>Access Privilege Inquiry Functions</title>
25339
25340 <indexterm>
25341 <primary>privilege</primary>
25342 <secondary>querying</secondary>
25343 </indexterm>
25344
25345 <para>
25346 <xref linkend="functions-info-access-table"/> lists functions that
25347 allow querying object access privileges programmatically.
25348 (See <xref linkend="ddl-priv"/> for more information about
25349 privileges.)
25350 In these functions, the user whose privileges are being inquired about
25351 can be specified by name or by OID
25352 (<structname>pg_authid</structname>.<structfield>oid</structfield>), or if
25353 the name is given as <literal>public</literal> then the privileges of the
25354 PUBLIC pseudo-role are checked. Also, the <parameter>user</parameter>
25355 argument can be omitted entirely, in which case
25356 the <function>current_user</function> is assumed.
25357 The object that is being inquired about can be specified either by name or
25358 by OID, too. When specifying by name, a schema name can be included if
25359 relevant.
25360 The access privilege of interest is specified by a text string, which must
25361 evaluate to one of the appropriate privilege keywords for the object's type
25362 (e.g., <literal>SELECT</literal>). Optionally, <literal>WITH GRANT
25363 OPTION</literal> can be added to a privilege type to test whether the
25364 privilege is held with grant option. Also, multiple privilege types can be
25365 listed separated by commas, in which case the result will be true if any of
25366 the listed privileges is held. (Case of the privilege string is not
25367 significant, and extra whitespace is allowed between but not within
25368 privilege names.)
25369 Some examples:
25370 <programlisting>
25371 SELECT has_table_privilege('myschema.mytable', 'select');
25372 SELECT has_table_privilege('joe', 'mytable', 'INSERT, SELECT WITH GRANT OPTION');
25373 </programlisting>
25374 </para>
25375
25376 <table id="functions-info-access-table">
25377 <title>Access Privilege Inquiry Functions</title>
25378 <tgroup cols="1">
25379 <thead>
25380 <row>
25381 <entry role="func_table_entry"><para role="func_signature">
25382 Function
25383 </para>
25384 <para>
25385 Description
25386 </para></entry>
25387 </row>
25388 </thead>
25389
25390 <tbody>
25391 <row>
25392 <entry role="func_table_entry"><para role="func_signature">
25393 <indexterm>
25394 <primary>has_any_column_privilege</primary>
25395 </indexterm>
25396 <function>has_any_column_privilege</function> (
25397 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25398 <parameter>table</parameter> <type>text</type> or <type>oid</type>,
25399 <parameter>privilege</parameter> <type>text</type> )
25400 <returnvalue>boolean</returnvalue>
25401 </para>
25402 <para>
25403 Does user have privilege for any column of table?
25404 This succeeds either if the privilege is held for the whole table, or
25405 if there is a column-level grant of the privilege for at least one
25406 column.
25407 Allowable privilege types are
25408 <literal>SELECT</literal>, <literal>INSERT</literal>,
25409 <literal>UPDATE</literal>, and <literal>REFERENCES</literal>.
25410 </para></entry>
25411 </row>
25412
25413 <row>
25414 <entry role="func_table_entry"><para role="func_signature">
25415 <indexterm>
25416 <primary>has_column_privilege</primary>
25417 </indexterm>
25418 <function>has_column_privilege</function> (
25419 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25420 <parameter>table</parameter> <type>text</type> or <type>oid</type>,
25421 <parameter>column</parameter> <type>text</type> or <type>smallint</type>,
25422 <parameter>privilege</parameter> <type>text</type> )
25423 <returnvalue>boolean</returnvalue>
25424 </para>
25425 <para>
25426 Does user have privilege for the specified table column?
25427 This succeeds either if the privilege is held for the whole table, or
25428 if there is a column-level grant of the privilege for the column.
25429 The column can be specified by name or by attribute number
25430 (<structname>pg_attribute</structname>.<structfield>attnum</structfield>).
25431 Allowable privilege types are
25432 <literal>SELECT</literal>, <literal>INSERT</literal>,
25433 <literal>UPDATE</literal>, and <literal>REFERENCES</literal>.
25434 </para></entry>
25435 </row>
25436
25437 <row>
25438 <entry role="func_table_entry"><para role="func_signature">
25439 <indexterm>
25440 <primary>has_database_privilege</primary>
25441 </indexterm>
25442 <function>has_database_privilege</function> (
25443 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25444 <parameter>database</parameter> <type>text</type> or <type>oid</type>,
25445 <parameter>privilege</parameter> <type>text</type> )
25446 <returnvalue>boolean</returnvalue>
25447 </para>
25448 <para>
25449 Does user have privilege for database?
25450 Allowable privilege types are
25451 <literal>CREATE</literal>,
25452 <literal>CONNECT</literal>,
25453 <literal>TEMPORARY</literal>, and
25454 <literal>TEMP</literal> (which is equivalent to
25455 <literal>TEMPORARY</literal>).
25456 </para></entry>
25457 </row>
25458
25459 <row>
25460 <entry role="func_table_entry"><para role="func_signature">
25461 <indexterm>
25462 <primary>has_foreign_data_wrapper_privilege</primary>
25463 </indexterm>
25464 <function>has_foreign_data_wrapper_privilege</function> (
25465 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25466 <parameter>fdw</parameter> <type>text</type> or <type>oid</type>,
25467 <parameter>privilege</parameter> <type>text</type> )
25468 <returnvalue>boolean</returnvalue>
25469 </para>
25470 <para>
25471 Does user have privilege for foreign-data wrapper?
25472 The only allowable privilege type is <literal>USAGE</literal>.
25473 </para></entry>
25474 </row>
25475
25476 <row>
25477 <entry role="func_table_entry"><para role="func_signature">
25478 <indexterm>
25479 <primary>has_function_privilege</primary>
25480 </indexterm>
25481 <function>has_function_privilege</function> (
25482 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25483 <parameter>function</parameter> <type>text</type> or <type>oid</type>,
25484 <parameter>privilege</parameter> <type>text</type> )
25485 <returnvalue>boolean</returnvalue>
25486 </para>
25487 <para>
25488 Does user have privilege for function?
25489 The only allowable privilege type is <literal>EXECUTE</literal>.
25490 </para>
25491 <para>
25492 When specifying a function by name rather than by OID, the allowed
25493 input is the same as for the <type>regprocedure</type> data type (see
25494 <xref linkend="datatype-oid"/>).
25495 An example is:
25496 <programlisting>
25497 SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');
25498 </programlisting>
25499 </para></entry>
25500 </row>
25501
25502 <row>
25503 <entry role="func_table_entry"><para role="func_signature">
25504 <indexterm>
25505 <primary>has_language_privilege</primary>
25506 </indexterm>
25507 <function>has_language_privilege</function> (
25508 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25509 <parameter>language</parameter> <type>text</type> or <type>oid</type>,
25510 <parameter>privilege</parameter> <type>text</type> )
25511 <returnvalue>boolean</returnvalue>
25512 </para>
25513 <para>
25514 Does user have privilege for language?
25515 The only allowable privilege type is <literal>USAGE</literal>.
25516 </para></entry>
25517 </row>
25518
25519 <row>
25520 <entry role="func_table_entry"><para role="func_signature">
25521 <indexterm>
25522 <primary>has_largeobject_privilege</primary>
25523 </indexterm>
25524 <function>has_largeobject_privilege</function> (
25525 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25526 <parameter>largeobject</parameter> <type>oid</type>,
25527 <parameter>privilege</parameter> <type>text</type> )
25528 <returnvalue>boolean</returnvalue>
25529 </para>
25530 <para>
25531 Does user have privilege for large object?
25532 Allowable privilege types are
25533 <literal>SELECT</literal> and <literal>UPDATE</literal>.
25534 </para></entry>
25535 </row>
25536
25537 <row>
25538 <entry role="func_table_entry"><para role="func_signature">
25539 <indexterm>
25540 <primary>has_parameter_privilege</primary>
25541 </indexterm>
25542 <function>has_parameter_privilege</function> (
25543 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25544 <parameter>parameter</parameter> <type>text</type>,
25545 <parameter>privilege</parameter> <type>text</type> )
25546 <returnvalue>boolean</returnvalue>
25547 </para>
25548 <para>
25549 Does user have privilege for configuration parameter?
25550 The parameter name is case-insensitive.
25551 Allowable privilege types are <literal>SET</literal>
25552 and <literal>ALTER SYSTEM</literal>.
25553 </para></entry>
25554 </row>
25555
25556 <row>
25557 <entry role="func_table_entry"><para role="func_signature">
25558 <indexterm>
25559 <primary>has_schema_privilege</primary>
25560 </indexterm>
25561 <function>has_schema_privilege</function> (
25562 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25563 <parameter>schema</parameter> <type>text</type> or <type>oid</type>,
25564 <parameter>privilege</parameter> <type>text</type> )
25565 <returnvalue>boolean</returnvalue>
25566 </para>
25567 <para>
25568 Does user have privilege for schema?
25569 Allowable privilege types are
25570 <literal>CREATE</literal> and
25571 <literal>USAGE</literal>.
25572 </para></entry>
25573 </row>
25574
25575 <row>
25576 <entry role="func_table_entry"><para role="func_signature">
25577 <indexterm>
25578 <primary>has_sequence_privilege</primary>
25579 </indexterm>
25580 <function>has_sequence_privilege</function> (
25581 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25582 <parameter>sequence</parameter> <type>text</type> or <type>oid</type>,
25583 <parameter>privilege</parameter> <type>text</type> )
25584 <returnvalue>boolean</returnvalue>
25585 </para>
25586 <para>
25587 Does user have privilege for sequence?
25588 Allowable privilege types are
25589 <literal>USAGE</literal>,
25590 <literal>SELECT</literal>, and
25591 <literal>UPDATE</literal>.
25592 </para></entry>
25593 </row>
25594
25595 <row>
25596 <entry role="func_table_entry"><para role="func_signature">
25597 <indexterm>
25598 <primary>has_server_privilege</primary>
25599 </indexterm>
25600 <function>has_server_privilege</function> (
25601 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25602 <parameter>server</parameter> <type>text</type> or <type>oid</type>,
25603 <parameter>privilege</parameter> <type>text</type> )
25604 <returnvalue>boolean</returnvalue>
25605 </para>
25606 <para>
25607 Does user have privilege for foreign server?
25608 The only allowable privilege type is <literal>USAGE</literal>.
25609 </para></entry>
25610 </row>
25611
25612 <row>
25613 <entry role="func_table_entry"><para role="func_signature">
25614 <indexterm>
25615 <primary>has_table_privilege</primary>
25616 </indexterm>
25617 <function>has_table_privilege</function> (
25618 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25619 <parameter>table</parameter> <type>text</type> or <type>oid</type>,
25620 <parameter>privilege</parameter> <type>text</type> )
25621 <returnvalue>boolean</returnvalue>
25622 </para>
25623 <para>
25624 Does user have privilege for table?
25625 Allowable privilege types
25626 are <literal>SELECT</literal>, <literal>INSERT</literal>,
25627 <literal>UPDATE</literal>, <literal>DELETE</literal>,
25628 <literal>TRUNCATE</literal>, <literal>REFERENCES</literal>,
25629 <literal>TRIGGER</literal>, and <literal>MAINTAIN</literal>.
25630 </para></entry>
25631 </row>
25632
25633 <row>
25634 <entry role="func_table_entry"><para role="func_signature">
25635 <indexterm>
25636 <primary>has_tablespace_privilege</primary>
25637 </indexterm>
25638 <function>has_tablespace_privilege</function> (
25639 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25640 <parameter>tablespace</parameter> <type>text</type> or <type>oid</type>,
25641 <parameter>privilege</parameter> <type>text</type> )
25642 <returnvalue>boolean</returnvalue>
25643 </para>
25644 <para>
25645 Does user have privilege for tablespace?
25646 The only allowable privilege type is <literal>CREATE</literal>.
25647 </para></entry>
25648 </row>
25649
25650 <row>
25651 <entry role="func_table_entry"><para role="func_signature">
25652 <indexterm>
25653 <primary>has_type_privilege</primary>
25654 </indexterm>
25655 <function>has_type_privilege</function> (
25656 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25657 <parameter>type</parameter> <type>text</type> or <type>oid</type>,
25658 <parameter>privilege</parameter> <type>text</type> )
25659 <returnvalue>boolean</returnvalue>
25660 </para>
25661 <para>
25662 Does user have privilege for data type?
25663 The only allowable privilege type is <literal>USAGE</literal>.
25664 When specifying a type by name rather than by OID, the allowed input
25665 is the same as for the <type>regtype</type> data type (see
25666 <xref linkend="datatype-oid"/>).
25667 </para></entry>
25668 </row>
25669
25670 <row>
25671 <entry role="func_table_entry"><para role="func_signature">
25672 <indexterm>
25673 <primary>pg_has_role</primary>
25674 </indexterm>
25675 <function>pg_has_role</function> (
25676 <optional> <parameter>user</parameter> <type>name</type> or <type>oid</type>, </optional>
25677 <parameter>role</parameter> <type>text</type> or <type>oid</type>,
25678 <parameter>privilege</parameter> <type>text</type> )
25679 <returnvalue>boolean</returnvalue>
25680 </para>
25681 <para>
25682 Does user have privilege for role?
25683 Allowable privilege types are
25684 <literal>MEMBER</literal>, <literal>USAGE</literal>,
25685 and <literal>SET</literal>.
25686 <literal>MEMBER</literal> denotes direct or indirect membership in
25687 the role without regard to what specific privileges may be conferred.
25688 <literal>USAGE</literal> denotes whether the privileges of the role
25689 are immediately available without doing <command>SET ROLE</command>,
25690 while <literal>SET</literal> denotes whether it is possible to change
25691 to the role using the <literal>SET ROLE</literal> command.
25692 <literal>WITH ADMIN OPTION</literal> or <literal>WITH GRANT
25693 OPTION</literal> can be added to any of these privilege types to
25694 test whether the <literal>ADMIN</literal> privilege is held (all
25695 six spellings test the same thing).
25696 This function does not allow the special case of
25697 setting <parameter>user</parameter> to <literal>public</literal>,
25698 because the PUBLIC pseudo-role can never be a member of real roles.
25699 </para></entry>
25700 </row>
25701
25702 <row>
25703 <entry role="func_table_entry"><para role="func_signature">
25704 <indexterm>
25705 <primary>row_security_active</primary>
25706 </indexterm>
25707 <function>row_security_active</function> (
25708 <parameter>table</parameter> <type>text</type> or <type>oid</type> )
25709 <returnvalue>boolean</returnvalue>
25710 </para>
25711 <para>
25712 Is row-level security active for the specified table in the context of
25713 the current user and current environment?
25714 </para></entry>
25715 </row>
25716 </tbody>
25717 </tgroup>
25718 </table>
25719
25720 <para>
25721 <xref linkend="functions-aclitem-op-table"/> shows the operators
25722 available for the <type>aclitem</type> type, which is the catalog
25723 representation of access privileges. See <xref linkend="ddl-priv"/>
25724 for information about how to read access privilege values.
25725 </para>
25726
25727 <table id="functions-aclitem-op-table">
25728 <title><type>aclitem</type> Operators</title>
25729 <tgroup cols="1">
25730 <thead>
25731 <row>
25732 <entry role="func_table_entry"><para role="func_signature">
25733 Operator
25734 </para>
25735 <para>
25736 Description
25737 </para>
25738 <para>
25739 Example(s)
25740 </para></entry>
25741 </row>
25742 </thead>
25743
25744 <tbody>
25745 <row>
25746 <entry role="func_table_entry"><para role="func_signature">
25747 <indexterm>
25748 <primary>aclitemeq</primary>
25749 </indexterm>
25750 <type>aclitem</type> <literal>=</literal> <type>aclitem</type>
25751 <returnvalue>boolean</returnvalue>
25752 </para>
25753 <para>
25754 Are <type>aclitem</type>s equal? (Notice that
25755 type <type>aclitem</type> lacks the usual set of comparison
25756 operators; it has only equality. In turn, <type>aclitem</type>
25757 arrays can only be compared for equality.)
25758 </para>
25759 <para>
25760 <literal>'calvin=r*w/hobbes'::aclitem = 'calvin=r*w*/hobbes'::aclitem</literal>
25761 <returnvalue>f</returnvalue>
25762 </para></entry>
25763 </row>
25764
25765 <row>
25766 <entry role="func_table_entry"><para role="func_signature">
25767 <indexterm>
25768 <primary>aclcontains</primary>
25769 </indexterm>
25770 <type>aclitem[]</type> <literal>@&gt;</literal> <type>aclitem</type>
25771 <returnvalue>boolean</returnvalue>
25772 </para>
25773 <para>
25774 Does array contain the specified privileges? (This is true if there
25775 is an array entry that matches the <type>aclitem</type>'s grantee and
25776 grantor, and has at least the specified set of privileges.)
25777 </para>
25778 <para>
25779 <literal>'{calvin=r*w/hobbes,hobbes=r*w*/postgres}'::aclitem[] @&gt; 'calvin=r*/hobbes'::aclitem</literal>
25780 <returnvalue>t</returnvalue>
25781 </para></entry>
25782 </row>
25783 </tbody>
25784 </tgroup>
25785 </table>
25786
25787 <para>
25788 <xref linkend="functions-aclitem-fn-table"/> shows some additional
25789 functions to manage the <type>aclitem</type> type.
25790 </para>
25791
25792 <table id="functions-aclitem-fn-table">
25793 <title><type>aclitem</type> Functions</title>
25794 <tgroup cols="1">
25795 <thead>
25796 <row>
25797 <entry role="func_table_entry"><para role="func_signature">
25798 Function
25799 </para>
25800 <para>
25801 Description
25802 </para></entry>
25803 </row>
25804 </thead>
25805
25806 <tbody>
25807 <row>
25808 <entry role="func_table_entry"><para role="func_signature">
25809 <indexterm>
25810 <primary>acldefault</primary>
25811 </indexterm>
25812 <function>acldefault</function> (
25813 <parameter>type</parameter> <type>"char"</type>,
25814 <parameter>ownerId</parameter> <type>oid</type> )
25815 <returnvalue>aclitem[]</returnvalue>
25816 </para>
25817 <para>
25818 Constructs an <type>aclitem</type> array holding the default access
25819 privileges for an object of type <parameter>type</parameter> belonging
25820 to the role with OID <parameter>ownerId</parameter>. This represents
25821 the access privileges that will be assumed when an object's
25822 <acronym>ACL</acronym> entry is null. (The default access privileges
25823 are described in <xref linkend="ddl-priv"/>.)
25824 The <parameter>type</parameter> parameter must be one of
25825 'c' for <literal>COLUMN</literal>,
25826 'r' for <literal>TABLE</literal> and table-like objects,
25827 's' for <literal>SEQUENCE</literal>,
25828 'd' for <literal>DATABASE</literal>,
25829 'f' for <literal>FUNCTION</literal> or <literal>PROCEDURE</literal>,
25830 'l' for <literal>LANGUAGE</literal>,
25831 'L' for <literal>LARGE OBJECT</literal>,
25832 'n' for <literal>SCHEMA</literal>,
25833 'p' for <literal>PARAMETER</literal>,
25834 't' for <literal>TABLESPACE</literal>,
25835 'F' for <literal>FOREIGN DATA WRAPPER</literal>,
25836 'S' for <literal>FOREIGN SERVER</literal>,
25837 or
25838 'T' for <literal>TYPE</literal> or <literal>DOMAIN</literal>.
25839 </para></entry>
25840 </row>
25841
25842 <row>
25843 <entry role="func_table_entry"><para role="func_signature">
25844 <indexterm>
25845 <primary>aclexplode</primary>
25846 </indexterm>
25847 <function>aclexplode</function> ( <type>aclitem[]</type> )
25848 <returnvalue>setof record</returnvalue>
25849 ( <parameter>grantor</parameter> <type>oid</type>,
25850 <parameter>grantee</parameter> <type>oid</type>,
25851 <parameter>privilege_type</parameter> <type>text</type>,
25852 <parameter>is_grantable</parameter> <type>boolean</type> )
25853 </para>
25854 <para>
25855 Returns the <type>aclitem</type> array as a set of rows.
25856 If the grantee is the pseudo-role PUBLIC, it is represented by zero in
25857 the <parameter>grantee</parameter> column. Each granted privilege is
25858 represented as <literal>SELECT</literal>, <literal>INSERT</literal>,
25859 etc (see <xref linkend="privilege-abbrevs-table"/> for a full list).
25860 Note that each privilege is broken out as a separate row, so
25861 only one keyword appears in the <parameter>privilege_type</parameter>
25862 column.
25863 </para></entry>
25864 </row>
25865
25866 <row>
25867 <entry role="func_table_entry"><para role="func_signature">
25868 <indexterm>
25869 <primary>makeaclitem</primary>
25870 </indexterm>
25871 <function>makeaclitem</function> (
25872 <parameter>grantee</parameter> <type>oid</type>,
25873 <parameter>grantor</parameter> <type>oid</type>,
25874 <parameter>privileges</parameter> <type>text</type>,
25875 <parameter>is_grantable</parameter> <type>boolean</type> )
25876 <returnvalue>aclitem</returnvalue>
25877 </para>
25878 <para>
25879 Constructs an <type>aclitem</type> with the given properties.
25880 <parameter>privileges</parameter> is a comma-separated list of
25881 privilege names such as <literal>SELECT</literal>,
25882 <literal>INSERT</literal>, etc, all of which are set in the
25883 result. (Case of the privilege string is not significant, and
25884 extra whitespace is allowed between but not within privilege
25885 names.)
25886 </para></entry>
25887 </row>
25888 </tbody>
25889 </tgroup>
25890 </table>
25891
25892 </sect2>
25893
25894 <sect2 id="functions-info-schema">
25895 <title>Schema Visibility Inquiry Functions</title>
25896
25897 <para>
25898 <xref linkend="functions-info-schema-table"/> shows functions that
25899 determine whether a certain object is <firstterm>visible</firstterm> in the
25900 current schema search path.
25901 For example, a table is said to be visible if its
25902 containing schema is in the search path and no table of the same
25903 name appears earlier in the search path. This is equivalent to the
25904 statement that the table can be referenced by name without explicit
25905 schema qualification. Thus, to list the names of all visible tables:
25906 <programlisting>
25907 SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
25908 </programlisting>
25909 For functions and operators, an object in the search path is said to be
25910 visible if there is no object of the same name <emphasis>and argument data
25911 type(s)</emphasis> earlier in the path. For operator classes and families,
25912 both the name and the associated index access method are considered.
25913 </para>
25914
25915 <indexterm>
25916 <primary>search path</primary>
25917 <secondary>object visibility</secondary>
25918 </indexterm>
25919
25920 <table id="functions-info-schema-table">
25921 <title>Schema Visibility Inquiry Functions</title>
25922 <tgroup cols="1">
25923 <thead>
25924 <row>
25925 <entry role="func_table_entry"><para role="func_signature">
25926 Function
25927 </para>
25928 <para>
25929 Description
25930 </para></entry>
25931 </row>
25932 </thead>
25933
25934 <tbody>
25935 <row>
25936 <entry role="func_table_entry"><para role="func_signature">
25937 <indexterm>
25938 <primary>pg_collation_is_visible</primary>
25939 </indexterm>
25940 <function>pg_collation_is_visible</function> ( <parameter>collation</parameter> <type>oid</type> )
25941 <returnvalue>boolean</returnvalue>
25942 </para>
25943 <para>
25944 Is collation visible in search path?
25945 </para></entry>
25946 </row>
25947
25948 <row>
25949 <entry role="func_table_entry"><para role="func_signature">
25950 <indexterm>
25951 <primary>pg_conversion_is_visible</primary>
25952 </indexterm>
25953 <function>pg_conversion_is_visible</function> ( <parameter>conversion</parameter> <type>oid</type> )
25954 <returnvalue>boolean</returnvalue>
25955 </para>
25956 <para>
25957 Is conversion visible in search path?
25958 </para></entry>
25959 </row>
25960
25961 <row>
25962 <entry role="func_table_entry"><para role="func_signature">
25963 <indexterm>
25964 <primary>pg_function_is_visible</primary>
25965 </indexterm>
25966 <function>pg_function_is_visible</function> ( <parameter>function</parameter> <type>oid</type> )
25967 <returnvalue>boolean</returnvalue>
25968 </para>
25969 <para>
25970 Is function visible in search path?
25971 (This also works for procedures and aggregates.)
25972 </para></entry>
25973 </row>
25974
25975 <row>
25976 <entry role="func_table_entry"><para role="func_signature">
25977 <indexterm>
25978 <primary>pg_opclass_is_visible</primary>
25979 </indexterm>
25980 <function>pg_opclass_is_visible</function> ( <parameter>opclass</parameter> <type>oid</type> )
25981 <returnvalue>boolean</returnvalue>
25982 </para>
25983 <para>
25984 Is operator class visible in search path?
25985 </para></entry>
25986 </row>
25987
25988 <row>
25989 <entry role="func_table_entry"><para role="func_signature">
25990 <indexterm>
25991 <primary>pg_operator_is_visible</primary>
25992 </indexterm>
25993 <function>pg_operator_is_visible</function> ( <parameter>operator</parameter> <type>oid</type> )
25994 <returnvalue>boolean</returnvalue>
25995 </para>
25996 <para>
25997 Is operator visible in search path?
25998 </para></entry>
25999 </row>
26000
26001 <row>
26002 <entry role="func_table_entry"><para role="func_signature">
26003 <indexterm>
26004 <primary>pg_opfamily_is_visible</primary>
26005 </indexterm>
26006 <function>pg_opfamily_is_visible</function> ( <parameter>opclass</parameter> <type>oid</type> )
26007 <returnvalue>boolean</returnvalue>
26008 </para>
26009 <para>
26010 Is operator family visible in search path?
26011 </para></entry>
26012 </row>
26013
26014 <row>
26015 <entry role="func_table_entry"><para role="func_signature">
26016 <indexterm>
26017 <primary>pg_statistics_obj_is_visible</primary>
26018 </indexterm>
26019 <function>pg_statistics_obj_is_visible</function> ( <parameter>stat</parameter> <type>oid</type> )
26020 <returnvalue>boolean</returnvalue>
26021 </para>
26022 <para>
26023 Is statistics object visible in search path?
26024 </para></entry>
26025 </row>
26026
26027 <row>
26028 <entry role="func_table_entry"><para role="func_signature">
26029 <indexterm>
26030 <primary>pg_table_is_visible</primary>
26031 </indexterm>
26032 <function>pg_table_is_visible</function> ( <parameter>table</parameter> <type>oid</type> )
26033 <returnvalue>boolean</returnvalue>
26034 </para>
26035 <para>
26036 Is table visible in search path?
26037 (This works for all types of relations, including views, materialized
26038 views, indexes, sequences and foreign tables.)
26039 </para></entry>
26040 </row>
26041
26042 <row>
26043 <entry role="func_table_entry"><para role="func_signature">
26044 <indexterm>
26045 <primary>pg_ts_config_is_visible</primary>
26046 </indexterm>
26047 <function>pg_ts_config_is_visible</function> ( <parameter>config</parameter> <type>oid</type> )
26048 <returnvalue>boolean</returnvalue>
26049 </para>
26050 <para>
26051 Is text search configuration visible in search path?
26052 </para></entry>
26053 </row>
26054
26055 <row>
26056 <entry role="func_table_entry"><para role="func_signature">
26057 <indexterm>
26058 <primary>pg_ts_dict_is_visible</primary>
26059 </indexterm>
26060 <function>pg_ts_dict_is_visible</function> ( <parameter>dict</parameter> <type>oid</type> )
26061 <returnvalue>boolean</returnvalue>
26062 </para>
26063 <para>
26064 Is text search dictionary visible in search path?
26065 </para></entry>
26066 </row>
26067
26068 <row>
26069 <entry role="func_table_entry"><para role="func_signature">
26070 <indexterm>
26071 <primary>pg_ts_parser_is_visible</primary>
26072 </indexterm>
26073 <function>pg_ts_parser_is_visible</function> ( <parameter>parser</parameter> <type>oid</type> )
26074 <returnvalue>boolean</returnvalue>
26075 </para>
26076 <para>
26077 Is text search parser visible in search path?
26078 </para></entry>
26079 </row>
26080
26081 <row>
26082 <entry role="func_table_entry"><para role="func_signature">
26083 <indexterm>
26084 <primary>pg_ts_template_is_visible</primary>
26085 </indexterm>
26086 <function>pg_ts_template_is_visible</function> ( <parameter>template</parameter> <type>oid</type> )
26087 <returnvalue>boolean</returnvalue>
26088 </para>
26089 <para>
26090 Is text search template visible in search path?
26091 </para></entry>
26092 </row>
26093
26094 <row>
26095 <entry role="func_table_entry"><para role="func_signature">
26096 <indexterm>
26097 <primary>pg_type_is_visible</primary>
26098 </indexterm>
26099 <function>pg_type_is_visible</function> ( <parameter>type</parameter> <type>oid</type> )
26100 <returnvalue>boolean</returnvalue>
26101 </para>
26102 <para>
26103 Is type (or domain) visible in search path?
26104 </para></entry>
26105 </row>
26106 </tbody>
26107 </tgroup>
26108 </table>
26109
26110 <para>
26111 All these functions require object OIDs to identify the object to be
26112 checked. If you want to test an object by name, it is convenient to use
26113 the OID alias types (<type>regclass</type>, <type>regtype</type>,
26114 <type>regprocedure</type>, <type>regoperator</type>, <type>regconfig</type>,
26115 or <type>regdictionary</type>),
26116 for example:
26117 <programlisting>
26118 SELECT pg_type_is_visible('myschema.widget'::regtype);
26119 </programlisting>
26120 Note that it would not make much sense to test a non-schema-qualified
26121 type name in this way &mdash; if the name can be recognized at all, it must be visible.
26122 </para>
26123
26124 </sect2>
26125
26126 <sect2 id="functions-info-catalog">
26127 <title>System Catalog Information Functions</title>
26128
26129 <para>
26130 <xref linkend="functions-info-catalog-table"/> lists functions that
26131 extract information from the system catalogs.
26132 </para>
26133
26134 <table id="functions-info-catalog-table">
26135 <title>System Catalog Information Functions</title>
26136 <tgroup cols="1">
26137 <thead>
26138 <row>
26139 <entry role="func_table_entry"><para role="func_signature">
26140 Function
26141 </para>
26142 <para>
26143 Description
26144 </para></entry>
26145 </row>
26146 </thead>
26147
26148 <tbody>
26149 <row>
26150 <entry id="format-type" xreflabel="format_type" role="func_table_entry"><para role="func_signature">
26151 <indexterm>
26152 <primary>format_type</primary>
26153 </indexterm>
26154 <function>format_type</function> ( <parameter>type</parameter> <type>oid</type>, <parameter>typemod</parameter> <type>integer</type> )
26155 <returnvalue>text</returnvalue>
26156 </para>
26157 <para>
26158 Returns the SQL name for a data type that is identified by its type
26159 OID and possibly a type modifier. Pass NULL for the type modifier if
26160 no specific modifier is known.
26161 </para></entry>
26162 </row>
26163
26164 <row>
26165 <entry role="func_table_entry"><para role="func_signature">
26166 <indexterm>
26167 <primary>pg_basetype</primary>
26168 </indexterm>
26169 <function>pg_basetype</function> ( <type>regtype</type> )
26170 <returnvalue>regtype</returnvalue>
26171 </para>
26172 <para>
26173 Returns the OID of the base type of a domain identified by its
26174 type OID. If the argument is the OID of a non-domain type,
26175 returns the argument as-is. Returns NULL if the argument is
26176 not a valid type OID. If there's a chain of domain dependencies,
26177 it will recurse until finding the base type.
26178 </para>
26179 <para>
26180 Assuming <literal>CREATE DOMAIN mytext AS text</literal>:
26181 </para>
26182 <para>
26183 <literal>pg_basetype('mytext'::regtype)</literal>
26184 <returnvalue>text</returnvalue>
26185 </para></entry>
26186 </row>
26187
26188 <row>
26189 <entry id="pg-char-to-encoding" role="func_table_entry"><para role="func_signature">
26190 <indexterm>
26191 <primary>pg_char_to_encoding</primary>
26192 </indexterm>
26193 <function>pg_char_to_encoding</function> ( <parameter>encoding</parameter> <type>name</type> )
26194 <returnvalue>integer</returnvalue>
26195 </para>
26196 <para>
26197 Converts the supplied encoding name into an integer representing the
26198 internal identifier used in some system catalog tables.
26199 Returns <literal>-1</literal> if an unknown encoding name is provided.
26200 </para></entry>
26201 </row>
26202
26203 <row>
26204 <entry id="pg-encoding-to-char" role="func_table_entry"><para role="func_signature">
26205 <indexterm>
26206 <primary>pg_encoding_to_char</primary>
26207 </indexterm>
26208 <function>pg_encoding_to_char</function> ( <parameter>encoding</parameter> <type>integer</type> )
26209 <returnvalue>name</returnvalue>
26210 </para>
26211 <para>
26212 Converts the integer used as the internal identifier of an encoding in some
26213 system catalog tables into a human-readable string.
26214 Returns an empty string if an invalid encoding number is provided.
26215 </para></entry>
26216 </row>
26217
26218 <row>
26219 <entry role="func_table_entry"><para role="func_signature">
26220 <indexterm>
26221 <primary>pg_get_catalog_foreign_keys</primary>
26222 </indexterm>
26223 <function>pg_get_catalog_foreign_keys</function> ()
26224 <returnvalue>setof record</returnvalue>
26225 ( <parameter>fktable</parameter> <type>regclass</type>,
26226 <parameter>fkcols</parameter> <type>text[]</type>,
26227 <parameter>pktable</parameter> <type>regclass</type>,
26228 <parameter>pkcols</parameter> <type>text[]</type>,
26229 <parameter>is_array</parameter> <type>boolean</type>,
26230 <parameter>is_opt</parameter> <type>boolean</type> )
26231 </para>
26232 <para>
26233 Returns a set of records describing the foreign key relationships
26234 that exist within the <productname>PostgreSQL</productname> system
26235 catalogs.
26236 The <parameter>fktable</parameter> column contains the name of the
26237 referencing catalog, and the <parameter>fkcols</parameter> column
26238 contains the name(s) of the referencing column(s). Similarly,
26239 the <parameter>pktable</parameter> column contains the name of the
26240 referenced catalog, and the <parameter>pkcols</parameter> column
26241 contains the name(s) of the referenced column(s).
26242 If <parameter>is_array</parameter> is true, the last referencing
26243 column is an array, each of whose elements should match some entry
26244 in the referenced catalog.
26245 If <parameter>is_opt</parameter> is true, the referencing column(s)
26246 are allowed to contain zeroes instead of a valid reference.
26247 </para></entry>
26248 </row>
26249
26250 <row>
26251 <entry role="func_table_entry"><para role="func_signature">
26252 <indexterm>
26253 <primary>pg_get_constraintdef</primary>
26254 </indexterm>
26255 <function>pg_get_constraintdef</function> ( <parameter>constraint</parameter> <type>oid</type> <optional>, <parameter>pretty</parameter> <type>boolean</type> </optional> )
26256 <returnvalue>text</returnvalue>
26257 </para>
26258 <para>
26259 Reconstructs the creating command for a constraint.
26260 (This is a decompiled reconstruction, not the original text
26261 of the command.)
26262 </para></entry>
26263 </row>
26264
26265 <row>
26266 <entry role="func_table_entry"><para role="func_signature">
26267 <indexterm>
26268 <primary>pg_get_expr</primary>
26269 </indexterm>
26270 <function>pg_get_expr</function> ( <parameter>expr</parameter> <type>pg_node_tree</type>, <parameter>relation</parameter> <type>oid</type> <optional>, <parameter>pretty</parameter> <type>boolean</type> </optional> )
26271 <returnvalue>text</returnvalue>
26272 </para>
26273 <para>
26274 Decompiles the internal form of an expression stored in the system
26275 catalogs, such as the default value for a column. If the expression
26276 might contain Vars, specify the OID of the relation they refer to as
26277 the second parameter; if no Vars are expected, passing zero is
26278 sufficient.
26279 </para></entry>
26280 </row>
26281
26282 <row>
26283 <entry role="func_table_entry"><para role="func_signature">
26284 <indexterm>
26285 <primary>pg_get_functiondef</primary>
26286 </indexterm>
26287 <function>pg_get_functiondef</function> ( <parameter>func</parameter> <type>oid</type> )
26288 <returnvalue>text</returnvalue>
26289 </para>
26290 <para>
26291 Reconstructs the creating command for a function or procedure.
26292 (This is a decompiled reconstruction, not the original text
26293 of the command.)
26294 The result is a complete <command>CREATE OR REPLACE FUNCTION</command>
26295 or <command>CREATE OR REPLACE PROCEDURE</command> statement.
26296 </para></entry>
26297 </row>
26298
26299 <row>
26300 <entry role="func_table_entry"><para role="func_signature">
26301 <indexterm>
26302 <primary>pg_get_function_arguments</primary>
26303 </indexterm>
26304 <function>pg_get_function_arguments</function> ( <parameter>func</parameter> <type>oid</type> )
26305 <returnvalue>text</returnvalue>
26306 </para>
26307 <para>
26308 Reconstructs the argument list of a function or procedure, in the form
26309 it would need to appear in within <command>CREATE FUNCTION</command>
26310 (including default values).
26311 </para></entry>
26312 </row>
26313
26314 <row>
26315 <entry role="func_table_entry"><para role="func_signature">
26316 <indexterm>
26317 <primary>pg_get_function_identity_arguments</primary>
26318 </indexterm>
26319 <function>pg_get_function_identity_arguments</function> ( <parameter>func</parameter> <type>oid</type> )
26320 <returnvalue>text</returnvalue>
26321 </para>
26322 <para>
26323 Reconstructs the argument list necessary to identify a function or
26324 procedure, in the form it would need to appear in within commands such
26325 as <command>ALTER FUNCTION</command>. This form omits default values.
26326 </para></entry>
26327 </row>
26328
26329 <row>
26330 <entry role="func_table_entry"><para role="func_signature">
26331 <indexterm>
26332 <primary>pg_get_function_result</primary>
26333 </indexterm>
26334 <function>pg_get_function_result</function> ( <parameter>func</parameter> <type>oid</type> )
26335 <returnvalue>text</returnvalue>
26336 </para>
26337 <para>
26338 Reconstructs the <literal>RETURNS</literal> clause of a function, in
26339 the form it would need to appear in within <command>CREATE
26340 FUNCTION</command>. Returns <literal>NULL</literal> for a procedure.
26341 </para></entry>
26342 </row>
26343
26344 <row>
26345 <entry role="func_table_entry"><para role="func_signature">
26346 <indexterm>
26347 <primary>pg_get_indexdef</primary>
26348 </indexterm>
26349 <function>pg_get_indexdef</function> ( <parameter>index</parameter> <type>oid</type> <optional>, <parameter>column</parameter> <type>integer</type>, <parameter>pretty</parameter> <type>boolean</type> </optional> )
26350 <returnvalue>text</returnvalue>
26351 </para>
26352 <para>
26353 Reconstructs the creating command for an index.
26354 (This is a decompiled reconstruction, not the original text
26355 of the command.) If <parameter>column</parameter> is supplied and is
26356 not zero, only the definition of that column is reconstructed.
26357 </para></entry>
26358 </row>
26359
26360 <row>
26361 <entry role="func_table_entry"><para role="func_signature">
26362 <indexterm>
26363 <primary>pg_get_keywords</primary>
26364 </indexterm>
26365 <function>pg_get_keywords</function> ()
26366 <returnvalue>setof record</returnvalue>
26367 ( <parameter>word</parameter> <type>text</type>,
26368 <parameter>catcode</parameter> <type>"char"</type>,
26369 <parameter>barelabel</parameter> <type>boolean</type>,
26370 <parameter>catdesc</parameter> <type>text</type>,
26371 <parameter>baredesc</parameter> <type>text</type> )
26372 </para>
26373 <para>
26374 Returns a set of records describing the SQL keywords recognized by the
26375 server. The <parameter>word</parameter> column contains the
26376 keyword. The <parameter>catcode</parameter> column contains a
26377 category code: <literal>U</literal> for an unreserved
26378 keyword, <literal>C</literal> for a keyword that can be a column
26379 name, <literal>T</literal> for a keyword that can be a type or
26380 function name, or <literal>R</literal> for a fully reserved keyword.
26381 The <parameter>barelabel</parameter> column
26382 contains <literal>true</literal> if the keyword can be used as
26383 a <quote>bare</quote> column label in <command>SELECT</command> lists,
26384 or <literal>false</literal> if it can only be used
26385 after <literal>AS</literal>.
26386 The <parameter>catdesc</parameter> column contains a
26387 possibly-localized string describing the keyword's category.
26388 The <parameter>baredesc</parameter> column contains a
26389 possibly-localized string describing the keyword's column label status.
26390 </para></entry>
26391 </row>
26392
26393 <row>
26394 <entry role="func_table_entry"><para role="func_signature">
26395 <indexterm>
26396 <primary>pg_get_partition_constraintdef</primary>
26397 </indexterm>
26398 <function>pg_get_partition_constraintdef</function> ( <parameter>table</parameter> <type>oid</type> )
26399 <returnvalue>text</returnvalue>
26400 </para>
26401 <para>
26402 Reconstructs the definition of a partition constraint.
26403 (This is a decompiled reconstruction, not the original text
26404 of the command.)
26405 </para></entry>
26406 </row>
26407
26408 <row>
26409 <entry role="func_table_entry"><para role="func_signature">
26410 <indexterm>
26411 <primary>pg_get_partkeydef</primary>
26412 </indexterm>
26413 <function>pg_get_partkeydef</function> ( <parameter>table</parameter> <type>oid</type> )
26414 <returnvalue>text</returnvalue>
26415 </para>
26416 <para>
26417 Reconstructs the definition of a partitioned table's partition
26418 key, in the form it would have in the <literal>PARTITION
26419 BY</literal> clause of <command>CREATE TABLE</command>.
26420 (This is a decompiled reconstruction, not the original text
26421 of the command.)
26422 </para></entry>
26423 </row>
26424
26425 <row>
26426 <entry role="func_table_entry"><para role="func_signature">
26427 <indexterm>
26428 <primary>pg_get_ruledef</primary>
26429 </indexterm>
26430 <function>pg_get_ruledef</function> ( <parameter>rule</parameter> <type>oid</type> <optional>, <parameter>pretty</parameter> <type>boolean</type> </optional> )
26431 <returnvalue>text</returnvalue>
26432 </para>
26433 <para>
26434 Reconstructs the creating command for a rule.
26435 (This is a decompiled reconstruction, not the original text
26436 of the command.)
26437 </para></entry>
26438 </row>
26439
26440 <row>
26441 <entry role="func_table_entry"><para role="func_signature">
26442 <indexterm>
26443 <primary>pg_get_serial_sequence</primary>
26444 </indexterm>
26445 <function>pg_get_serial_sequence</function> ( <parameter>table</parameter> <type>text</type>, <parameter>column</parameter> <type>text</type> )
26446 <returnvalue>text</returnvalue>
26447 </para>
26448 <para>
26449 Returns the name of the sequence associated with a column,
26450 or NULL if no sequence is associated with the column.
26451 If the column is an identity column, the associated sequence is the
26452 sequence internally created for that column.
26453 For columns created using one of the serial types
26454 (<type>serial</type>, <type>smallserial</type>, <type>bigserial</type>),
26455 it is the sequence created for that serial column definition.
26456 In the latter case, the association can be modified or removed
26457 with <command>ALTER SEQUENCE OWNED BY</command>.
26458 (This function probably should have been
26459 called <function>pg_get_owned_sequence</function>; its current name
26460 reflects the fact that it has historically been used with serial-type
26461 columns.) The first parameter is a table name with optional
26462 schema, and the second parameter is a column name. Because the first
26463 parameter potentially contains both schema and table names, it is
26464 parsed per usual SQL rules, meaning it is lower-cased by default.
26465 The second parameter, being just a column name, is treated literally
26466 and so has its case preserved. The result is suitably formatted
26467 for passing to the sequence functions (see
26468 <xref linkend="functions-sequence"/>).
26469 </para>
26470 <para>
26471 A typical use is in reading the current value of the sequence for an
26472 identity or serial column, for example:
26473 <programlisting>
26474 SELECT currval(pg_get_serial_sequence('sometable', 'id'));
26475 </programlisting>
26476 </para></entry>
26477 </row>
26478
26479 <row>
26480 <entry role="func_table_entry"><para role="func_signature">
26481 <indexterm>
26482 <primary>pg_get_statisticsobjdef</primary>
26483 </indexterm>
26484 <function>pg_get_statisticsobjdef</function> ( <parameter>statobj</parameter> <type>oid</type> )
26485 <returnvalue>text</returnvalue>
26486 </para>
26487 <para>
26488 Reconstructs the creating command for an extended statistics object.
26489 (This is a decompiled reconstruction, not the original text
26490 of the command.)
26491 </para></entry>
26492 </row>
26493
26494 <row>
26495 <entry role="func_table_entry"><para role="func_signature">
26496 <indexterm>
26497 <primary>pg_get_triggerdef</primary>
26498 </indexterm>
26499 <function>pg_get_triggerdef</function> ( <parameter>trigger</parameter> <type>oid</type> <optional>, <parameter>pretty</parameter> <type>boolean</type> </optional> )
26500 <returnvalue>text</returnvalue>
26501 </para>
26502 <para>
26503 Reconstructs the creating command for a trigger.
26504 (This is a decompiled reconstruction, not the original text
26505 of the command.)
26506 </para></entry>
26507 </row>
26508
26509 <row>
26510 <entry role="func_table_entry"><para role="func_signature">
26511 <indexterm>
26512 <primary>pg_get_userbyid</primary>
26513 </indexterm>
26514 <function>pg_get_userbyid</function> ( <parameter>role</parameter> <type>oid</type> )
26515 <returnvalue>name</returnvalue>
26516 </para>
26517 <para>
26518 Returns a role's name given its OID.
26519 </para></entry>
26520 </row>
26521
26522 <row>
26523 <entry role="func_table_entry"><para role="func_signature">
26524 <indexterm>
26525 <primary>pg_get_viewdef</primary>
26526 </indexterm>
26527 <function>pg_get_viewdef</function> ( <parameter>view</parameter> <type>oid</type> <optional>, <parameter>pretty</parameter> <type>boolean</type> </optional> )
26528 <returnvalue>text</returnvalue>
26529 </para>
26530 <para>
26531 Reconstructs the underlying <command>SELECT</command> command for a
26532 view or materialized view. (This is a decompiled reconstruction, not
26533 the original text of the command.)
26534 </para></entry>
26535 </row>
26536
26537 <row>
26538 <entry role="func_table_entry"><para role="func_signature">
26539 <function>pg_get_viewdef</function> ( <parameter>view</parameter> <type>oid</type>, <parameter>wrap_column</parameter> <type>integer</type> )
26540 <returnvalue>text</returnvalue>
26541 </para>
26542 <para>
26543 Reconstructs the underlying <command>SELECT</command> command for a
26544 view or materialized view. (This is a decompiled reconstruction, not
26545 the original text of the command.) In this form of the function,
26546 pretty-printing is always enabled, and long lines are wrapped to try
26547 to keep them shorter than the specified number of columns.
26548 </para></entry>
26549 </row>
26550
26551 <row>
26552 <entry role="func_table_entry"><para role="func_signature">
26553 <function>pg_get_viewdef</function> ( <parameter>view</parameter> <type>text</type> <optional>, <parameter>pretty</parameter> <type>boolean</type> </optional> )
26554 <returnvalue>text</returnvalue>
26555 </para>
26556 <para>
26557 Reconstructs the underlying <command>SELECT</command> command for a
26558 view or materialized view, working from a textual name for the view
26559 rather than its OID. (This is deprecated; use the OID variant
26560 instead.)
26561 </para></entry>
26562 </row>
26563
26564 <row>
26565 <entry role="func_table_entry"><para role="func_signature">
26566 <indexterm>
26567 <primary>pg_index_column_has_property</primary>
26568 </indexterm>
26569 <function>pg_index_column_has_property</function> ( <parameter>index</parameter> <type>regclass</type>, <parameter>column</parameter> <type>integer</type>, <parameter>property</parameter> <type>text</type> )
26570 <returnvalue>boolean</returnvalue>
26571 </para>
26572 <para>
26573 Tests whether an index column has the named property.
26574 Common index column properties are listed in
26575 <xref linkend="functions-info-index-column-props"/>.
26576 (Note that extension access methods can define additional property
26577 names for their indexes.)
26578 <literal>NULL</literal> is returned if the property name is not known
26579 or does not apply to the particular object, or if the OID or column
26580 number does not identify a valid object.
26581 </para></entry>
26582 </row>
26583
26584 <row>
26585 <entry role="func_table_entry"><para role="func_signature">
26586 <indexterm>
26587 <primary>pg_index_has_property</primary>
26588 </indexterm>
26589 <function>pg_index_has_property</function> ( <parameter>index</parameter> <type>regclass</type>, <parameter>property</parameter> <type>text</type> )
26590 <returnvalue>boolean</returnvalue>
26591 </para>
26592 <para>
26593 Tests whether an index has the named property.
26594 Common index properties are listed in
26595 <xref linkend="functions-info-index-props"/>.
26596 (Note that extension access methods can define additional property
26597 names for their indexes.)
26598 <literal>NULL</literal> is returned if the property name is not known
26599 or does not apply to the particular object, or if the OID does not
26600 identify a valid object.
26601 </para></entry>
26602 </row>
26603
26604 <row>
26605 <entry role="func_table_entry"><para role="func_signature">
26606 <indexterm>
26607 <primary>pg_indexam_has_property</primary>
26608 </indexterm>
26609 <function>pg_indexam_has_property</function> ( <parameter>am</parameter> <type>oid</type>, <parameter>property</parameter> <type>text</type> )
26610 <returnvalue>boolean</returnvalue>
26611 </para>
26612 <para>
26613 Tests whether an index access method has the named property.
26614 Access method properties are listed in
26615 <xref linkend="functions-info-indexam-props"/>.
26616 <literal>NULL</literal> is returned if the property name is not known
26617 or does not apply to the particular object, or if the OID does not
26618 identify a valid object.
26619 </para></entry>
26620 </row>
26621
26622 <row>
26623 <entry role="func_table_entry"><para role="func_signature">
26624 <indexterm>
26625 <primary>pg_options_to_table</primary>
26626 </indexterm>
26627 <function>pg_options_to_table</function> ( <parameter>options_array</parameter> <type>text[]</type> )
26628 <returnvalue>setof record</returnvalue>
26629 ( <parameter>option_name</parameter> <type>text</type>,
26630 <parameter>option_value</parameter> <type>text</type> )
26631 </para>
26632 <para>
26633 Returns the set of storage options represented by a value from
26634 <structname>pg_class</structname>.<structfield>reloptions</structfield> or
26635 <structname>pg_attribute</structname>.<structfield>attoptions</structfield>.
26636 </para></entry>
26637 </row>
26638
26639 <row>
26640 <entry role="func_table_entry"><para role="func_signature">
26641 <indexterm>
26642 <primary>pg_settings_get_flags</primary>
26643 </indexterm>
26644 <function>pg_settings_get_flags</function> ( <parameter>guc</parameter> <type>text</type> )
26645 <returnvalue>text[]</returnvalue>
26646 </para>
26647 <para>
26648 Returns an array of the flags associated with the given GUC, or
26649 <literal>NULL</literal> if it does not exist. The result is
26650 an empty array if the GUC exists but there are no flags to show.
26651 Only the most useful flags listed in
26652 <xref linkend="functions-pg-settings-flags"/> are exposed.
26653 </para></entry>
26654 </row>
26655
26656 <row>
26657 <entry role="func_table_entry"><para role="func_signature">
26658 <indexterm>
26659 <primary>pg_tablespace_databases</primary>
26660 </indexterm>
26661 <function>pg_tablespace_databases</function> ( <parameter>tablespace</parameter> <type>oid</type> )
26662 <returnvalue>setof oid</returnvalue>
26663 </para>
26664 <para>
26665 Returns the set of OIDs of databases that have objects stored in the
26666 specified tablespace. If this function returns any rows, the
26667 tablespace is not empty and cannot be dropped. To identify the specific
26668 objects populating the tablespace, you will need to connect to the
26669 database(s) identified by <function>pg_tablespace_databases</function>
26670 and query their <structname>pg_class</structname> catalogs.
26671 </para></entry>
26672 </row>
26673
26674 <row>
26675 <entry role="func_table_entry"><para role="func_signature">
26676 <indexterm>
26677 <primary>pg_tablespace_location</primary>
26678 </indexterm>
26679 <function>pg_tablespace_location</function> ( <parameter>tablespace</parameter> <type>oid</type> )
26680 <returnvalue>text</returnvalue>
26681 </para>
26682 <para>
26683 Returns the file system path that this tablespace is located in.
26684 </para></entry>
26685 </row>
26686
26687 <row>
26688 <entry role="func_table_entry"><para role="func_signature">
26689 <indexterm>
26690 <primary>pg_typeof</primary>
26691 </indexterm>
26692 <function>pg_typeof</function> ( <type>"any"</type> )
26693 <returnvalue>regtype</returnvalue>
26694 </para>
26695 <para>
26696 Returns the OID of the data type of the value that is passed to it.
26697 This can be helpful for troubleshooting or dynamically constructing
26698 SQL queries. The function is declared as
26699 returning <type>regtype</type>, which is an OID alias type (see
26700 <xref linkend="datatype-oid"/>); this means that it is the same as an
26701 OID for comparison purposes but displays as a type name.
26702 </para>
26703 <para>
26704 <literal>pg_typeof(33)</literal>
26705 <returnvalue>integer</returnvalue>
26706 </para></entry>
26707 </row>
26708
26709 <row>
26710 <entry role="func_table_entry"><para role="func_signature">
26711 <indexterm>
26712 <primary>COLLATION FOR</primary>
26713 </indexterm>
26714 <function>COLLATION FOR</function> ( <type>"any"</type> )
26715 <returnvalue>text</returnvalue>
26716 </para>
26717 <para>
26718 Returns the name of the collation of the value that is passed to it.
26719 The value is quoted and schema-qualified if necessary. If no
26720 collation was derived for the argument expression,
26721 then <literal>NULL</literal> is returned. If the argument is not of a
26722 collatable data type, then an error is raised.
26723 </para>
26724 <para>
26725 <literal>collation for ('foo'::text)</literal>
26726 <returnvalue>"default"</returnvalue>
26727 </para>
26728 <para>
26729 <literal>collation for ('foo' COLLATE "de_DE")</literal>
26730 <returnvalue>"de_DE"</returnvalue>
26731 </para></entry>
26732 </row>
26733
26734 <row>
26735 <entry role="func_table_entry"><para role="func_signature">
26736 <indexterm>
26737 <primary>to_regclass</primary>
26738 </indexterm>
26739 <function>to_regclass</function> ( <type>text</type> )
26740 <returnvalue>regclass</returnvalue>
26741 </para>
26742 <para>
26743 Translates a textual relation name to its OID. A similar result is
26744 obtained by casting the string to type <type>regclass</type> (see
26745 <xref linkend="datatype-oid"/>); however, this function will return
26746 <literal>NULL</literal> rather than throwing an error if the name is
26747 not found.
26748 </para></entry>
26749 </row>
26750
26751 <row>
26752 <entry role="func_table_entry"><para role="func_signature">
26753 <indexterm>
26754 <primary>to_regcollation</primary>
26755 </indexterm>
26756 <function>to_regcollation</function> ( <type>text</type> )
26757 <returnvalue>regcollation</returnvalue>
26758 </para>
26759 <para>
26760 Translates a textual collation name to its OID. A similar result is
26761 obtained by casting the string to type <type>regcollation</type> (see
26762 <xref linkend="datatype-oid"/>); however, this function will return
26763 <literal>NULL</literal> rather than throwing an error if the name is
26764 not found.
26765 </para></entry>
26766 </row>
26767
26768 <row>
26769 <entry role="func_table_entry"><para role="func_signature">
26770 <indexterm>
26771 <primary>to_regnamespace</primary>
26772 </indexterm>
26773 <function>to_regnamespace</function> ( <type>text</type> )
26774 <returnvalue>regnamespace</returnvalue>
26775 </para>
26776 <para>
26777 Translates a textual schema name to its OID. A similar result is
26778 obtained by casting the string to type <type>regnamespace</type> (see
26779 <xref linkend="datatype-oid"/>); however, this function will return
26780 <literal>NULL</literal> rather than throwing an error if the name is
26781 not found.
26782 </para></entry>
26783 </row>
26784
26785 <row>
26786 <entry role="func_table_entry"><para role="func_signature">
26787 <indexterm>
26788 <primary>to_regoper</primary>
26789 </indexterm>
26790 <function>to_regoper</function> ( <type>text</type> )
26791 <returnvalue>regoper</returnvalue>
26792 </para>
26793 <para>
26794 Translates a textual operator name to its OID. A similar result is
26795 obtained by casting the string to type <type>regoper</type> (see
26796 <xref linkend="datatype-oid"/>); however, this function will return
26797 <literal>NULL</literal> rather than throwing an error if the name is
26798 not found or is ambiguous.
26799 </para></entry>
26800 </row>
26801
26802 <row>
26803 <entry role="func_table_entry"><para role="func_signature">
26804 <indexterm>
26805 <primary>to_regoperator</primary>
26806 </indexterm>
26807 <function>to_regoperator</function> ( <type>text</type> )
26808 <returnvalue>regoperator</returnvalue>
26809 </para>
26810 <para>
26811 Translates a textual operator name (with parameter types) to its OID. A similar result is
26812 obtained by casting the string to type <type>regoperator</type> (see
26813 <xref linkend="datatype-oid"/>); however, this function will return
26814 <literal>NULL</literal> rather than throwing an error if the name is
26815 not found.
26816 </para></entry>
26817 </row>
26818
26819 <row>
26820 <entry role="func_table_entry"><para role="func_signature">
26821 <indexterm>
26822 <primary>to_regproc</primary>
26823 </indexterm>
26824 <function>to_regproc</function> ( <type>text</type> )
26825 <returnvalue>regproc</returnvalue>
26826 </para>
26827 <para>
26828 Translates a textual function or procedure name to its OID. A similar result is
26829 obtained by casting the string to type <type>regproc</type> (see
26830 <xref linkend="datatype-oid"/>); however, this function will return
26831 <literal>NULL</literal> rather than throwing an error if the name is
26832 not found or is ambiguous.
26833 </para></entry>
26834 </row>
26835
26836 <row>
26837 <entry role="func_table_entry"><para role="func_signature">
26838 <indexterm>
26839 <primary>to_regprocedure</primary>
26840 </indexterm>
26841 <function>to_regprocedure</function> ( <type>text</type> )
26842 <returnvalue>regprocedure</returnvalue>
26843 </para>
26844 <para>
26845 Translates a textual function or procedure name (with argument types) to its OID. A similar result is
26846 obtained by casting the string to type <type>regprocedure</type> (see
26847 <xref linkend="datatype-oid"/>); however, this function will return
26848 <literal>NULL</literal> rather than throwing an error if the name is
26849 not found.
26850 </para></entry>
26851 </row>
26852
26853 <row>
26854 <entry role="func_table_entry"><para role="func_signature">
26855 <indexterm>
26856 <primary>to_regrole</primary>
26857 </indexterm>
26858 <function>to_regrole</function> ( <type>text</type> )
26859 <returnvalue>regrole</returnvalue>
26860 </para>
26861 <para>
26862 Translates a textual role name to its OID. A similar result is
26863 obtained by casting the string to type <type>regrole</type> (see
26864 <xref linkend="datatype-oid"/>); however, this function will return
26865 <literal>NULL</literal> rather than throwing an error if the name is
26866 not found.
26867 </para></entry>
26868 </row>
26869
26870 <row>
26871 <entry id="to-regtype" xreflabel="to_regtype" role="func_table_entry"><para role="func_signature">
26872 <indexterm>
26873 <primary>to_regtype</primary>
26874 </indexterm>
26875 <function>to_regtype</function> ( <type>text</type> )
26876 <returnvalue>regtype</returnvalue>
26877 </para>
26878 <para>
26879 Parses a string of text, extracts a potential type name from it,
26880 and translates that name into a type OID. A syntax error in the
26881 string will result in an error; but if the string is a
26882 syntactically valid type name that happens not to be found in the
26883 catalogs, the result is <literal>NULL</literal>. A similar result
26884 is obtained by casting the string to type <type>regtype</type>
26885 (see <xref linkend="datatype-oid"/>), except that that will throw
26886 error for name not found.
26887 </para></entry>
26888 </row>
26889
26890 <row>
26891 <entry role="func_table_entry"><para role="func_signature">
26892 <indexterm>
26893 <primary>to_regtypemod</primary>
26894 </indexterm>
26895 <function>to_regtypemod</function> ( <type>text</type> )
26896 <returnvalue>integer</returnvalue>
26897 </para>
26898 <para>
26899 Parses a string of text, extracts a potential type name from it,
26900 and translates its type modifier, if any. A syntax error in the
26901 string will result in an error; but if the string is a
26902 syntactically valid type name that happens not to be found in the
26903 catalogs, the result is <literal>NULL</literal>. The result is
26904 <literal>-1</literal> if no type modifier is present.
26905 </para>
26906 <para>
26907 <function>to_regtypemod</function> can be combined with
26908 <xref linkend="to-regtype"/> to produce appropriate inputs for
26909 <xref linkend="format-type"/>, allowing a string representing a
26910 type name to be canonicalized.
26911 </para>
26912 <para>
26913 <literal>format_type(to_regtype('varchar(32)'), to_regtypemod('varchar(32)'))</literal>
26914 <returnvalue>character varying(32)</returnvalue>
26915 </para></entry>
26916 </row>
26917 </tbody>
26918 </tgroup>
26919 </table>
26920
26921 <para>
26922 Most of the functions that reconstruct (decompile) database objects
26923 have an optional <parameter>pretty</parameter> flag, which
26924 if <literal>true</literal> causes the result to
26925 be <quote>pretty-printed</quote>. Pretty-printing suppresses unnecessary
26926 parentheses and adds whitespace for legibility.
26927 The pretty-printed format is more readable, but the default format
26928 is more likely to be interpreted the same way by future versions of
26929 <productname>PostgreSQL</productname>; so avoid using pretty-printed output
26930 for dump purposes. Passing <literal>false</literal> for
26931 the <parameter>pretty</parameter> parameter yields the same result as
26932 omitting the parameter.
26933 </para>
26934
26935 <table id="functions-info-index-column-props">
26936 <title>Index Column Properties</title>
26937 <tgroup cols="2">
26938 <thead>
26939 <row><entry>Name</entry><entry>Description</entry></row>
26940 </thead>
26941 <tbody>
26942 <row>
26943 <entry><literal>asc</literal></entry>
26944 <entry>Does the column sort in ascending order on a forward scan?
26945 </entry>
26946 </row>
26947 <row>
26948 <entry><literal>desc</literal></entry>
26949 <entry>Does the column sort in descending order on a forward scan?
26950 </entry>
26951 </row>
26952 <row>
26953 <entry><literal>nulls_first</literal></entry>
26954 <entry>Does the column sort with nulls first on a forward scan?
26955 </entry>
26956 </row>
26957 <row>
26958 <entry><literal>nulls_last</literal></entry>
26959 <entry>Does the column sort with nulls last on a forward scan?
26960 </entry>
26961 </row>
26962 <row>
26963 <entry><literal>orderable</literal></entry>
26964 <entry>Does the column possess any defined sort ordering?
26965 </entry>
26966 </row>
26967 <row>
26968 <entry><literal>distance_orderable</literal></entry>
26969 <entry>Can the column be scanned in order by a <quote>distance</quote>
26970 operator, for example <literal>ORDER BY col &lt;-&gt; constant</literal> ?
26971 </entry>
26972 </row>
26973 <row>
26974 <entry><literal>returnable</literal></entry>
26975 <entry>Can the column value be returned by an index-only scan?
26976 </entry>
26977 </row>
26978 <row>
26979 <entry><literal>search_array</literal></entry>
26980 <entry>Does the column natively support <literal>col = ANY(array)</literal>
26981 searches?
26982 </entry>
26983 </row>
26984 <row>
26985 <entry><literal>search_nulls</literal></entry>
26986 <entry>Does the column support <literal>IS NULL</literal> and
26987 <literal>IS NOT NULL</literal> searches?
26988 </entry>
26989 </row>
26990 </tbody>
26991 </tgroup>
26992 </table>
26993
26994 <table id="functions-info-index-props">
26995 <title>Index Properties</title>
26996 <tgroup cols="2">
26997 <thead>
26998 <row><entry>Name</entry><entry>Description</entry></row>
26999 </thead>
27000 <tbody>
27001 <row>
27002 <entry><literal>clusterable</literal></entry>
27003 <entry>Can the index be used in a <literal>CLUSTER</literal> command?
27004 </entry>
27005 </row>
27006 <row>
27007 <entry><literal>index_scan</literal></entry>
27008 <entry>Does the index support plain (non-bitmap) scans?
27009 </entry>
27010 </row>
27011 <row>
27012 <entry><literal>bitmap_scan</literal></entry>
27013 <entry>Does the index support bitmap scans?
27014 </entry>
27015 </row>
27016 <row>
27017 <entry><literal>backward_scan</literal></entry>
27018 <entry>Can the scan direction be changed in mid-scan (to
27019 support <literal>FETCH BACKWARD</literal> on a cursor without
27020 needing materialization)?
27021 </entry>
27022 </row>
27023 </tbody>
27024 </tgroup>
27025 </table>
27026
27027 <table id="functions-info-indexam-props">
27028 <title>Index Access Method Properties</title>
27029 <tgroup cols="2">
27030 <thead>
27031 <row><entry>Name</entry><entry>Description</entry></row>
27032 </thead>
27033 <tbody>
27034 <row>
27035 <entry><literal>can_order</literal></entry>
27036 <entry>Does the access method support <literal>ASC</literal>,
27037 <literal>DESC</literal> and related keywords in
27038 <literal>CREATE INDEX</literal>?
27039 </entry>
27040 </row>
27041 <row>
27042 <entry><literal>can_unique</literal></entry>
27043 <entry>Does the access method support unique indexes?
27044 </entry>
27045 </row>
27046 <row>
27047 <entry><literal>can_multi_col</literal></entry>
27048 <entry>Does the access method support indexes with multiple columns?
27049 </entry>
27050 </row>
27051 <row>
27052 <entry><literal>can_exclude</literal></entry>
27053 <entry>Does the access method support exclusion constraints?
27054 </entry>
27055 </row>
27056 <row>
27057 <entry><literal>can_include</literal></entry>
27058 <entry>Does the access method support the <literal>INCLUDE</literal>
27059 clause of <literal>CREATE INDEX</literal>?
27060 </entry>
27061 </row>
27062 </tbody>
27063 </tgroup>
27064 </table>
27065
27066 <table id="functions-pg-settings-flags">
27067 <title>GUC Flags</title>
27068 <tgroup cols="2">
27069 <thead>
27070 <row><entry>Flag</entry><entry>Description</entry></row>
27071 </thead>
27072 <tbody>
27073 <row>
27074 <entry><literal>EXPLAIN</literal></entry>
27075 <entry>Parameters with this flag are included in
27076 <command>EXPLAIN (SETTINGS)</command> commands.
27077 </entry>
27078 </row>
27079 <row>
27080 <entry><literal>NO_SHOW_ALL</literal></entry>
27081 <entry>Parameters with this flag are excluded from
27082 <command>SHOW ALL</command> commands.
27083 </entry>
27084 </row>
27085 <row>
27086 <entry><literal>NO_RESET</literal></entry>
27087 <entry>Parameters with this flag do not support
27088 <command>RESET</command> commands.
27089 </entry>
27090 </row>
27091 <row>
27092 <entry><literal>NO_RESET_ALL</literal></entry>
27093 <entry>Parameters with this flag are excluded from
27094 <command>RESET ALL</command> commands.
27095 </entry>
27096 </row>
27097 <row>
27098 <entry><literal>NOT_IN_SAMPLE</literal></entry>
27099 <entry>Parameters with this flag are not included in
27100 <filename>postgresql.conf</filename> by default.
27101 </entry>
27102 </row>
27103 <row>
27104 <entry><literal>RUNTIME_COMPUTED</literal></entry>
27105 <entry>Parameters with this flag are runtime-computed ones.
27106 </entry>
27107 </row>
27108 </tbody>
27109 </tgroup>
27110 </table>
27111
27112 </sect2>
27113
27114 <sect2 id="functions-info-object">
27115 <title>Object Information and Addressing Functions</title>
27116
27117 <para>
27118 <xref linkend="functions-info-object-table"/> lists functions related to
27119 database object identification and addressing.
27120 </para>
27121
27122 <table id="functions-info-object-table">
27123 <title>Object Information and Addressing Functions</title>
27124 <tgroup cols="1">
27125 <thead>
27126 <row>
27127 <entry role="func_table_entry"><para role="func_signature">
27128 Function
27129 </para>
27130 <para>
27131 Description
27132 </para></entry>
27133 </row>
27134 </thead>
27135
27136 <tbody>
27137 <row>
27138 <entry role="func_table_entry"><para role="func_signature">
27139 <indexterm>
27140 <primary>pg_get_acl</primary>
27141 </indexterm>
27142 <function>pg_get_acl</function> ( <parameter>classid</parameter> <type>oid</type>, <parameter>objid</parameter> <type>oid</type>, <parameter>objsubid</parameter> <type>integer</type> )
27143 <returnvalue>aclitem[]</returnvalue>
27144 </para>
27145 <para>
27146 Returns the <acronym>ACL</acronym> for a database object, specified
27147 by catalog OID, object OID and sub-object ID. This function returns
27148 <literal>NULL</literal> values for undefined objects.
27149 </para></entry>
27150 </row>
27151
27152 <row>
27153 <entry role="func_table_entry"><para role="func_signature">
27154 <indexterm>
27155 <primary>pg_describe_object</primary>
27156 </indexterm>
27157 <function>pg_describe_object</function> ( <parameter>classid</parameter> <type>oid</type>, <parameter>objid</parameter> <type>oid</type>, <parameter>objsubid</parameter> <type>integer</type> )
27158 <returnvalue>text</returnvalue>
27159 </para>
27160 <para>
27161 Returns a textual description of a database object identified by
27162 catalog OID, object OID, and sub-object ID (such as a column number
27163 within a table; the sub-object ID is zero when referring to a whole
27164 object). This description is intended to be human-readable, and might
27165 be translated, depending on server configuration. This is especially
27166 useful to determine the identity of an object referenced in the
27167 <structname>pg_depend</structname> catalog. This function returns
27168 <literal>NULL</literal> values for undefined objects.
27169 </para></entry>
27170 </row>
27171
27172 <row>
27173 <entry role="func_table_entry"><para role="func_signature">
27174 <indexterm>
27175 <primary>pg_identify_object</primary>
27176 </indexterm>
27177 <function>pg_identify_object</function> ( <parameter>classid</parameter> <type>oid</type>, <parameter>objid</parameter> <type>oid</type>, <parameter>objsubid</parameter> <type>integer</type> )
27178 <returnvalue>record</returnvalue>
27179 ( <parameter>type</parameter> <type>text</type>,
27180 <parameter>schema</parameter> <type>text</type>,
27181 <parameter>name</parameter> <type>text</type>,
27182 <parameter>identity</parameter> <type>text</type> )
27183 </para>
27184 <para>
27185 Returns a row containing enough information to uniquely identify the
27186 database object specified by catalog OID, object OID and sub-object
27187 ID.
27188 This information is intended to be machine-readable, and is never
27189 translated.
27190 <parameter>type</parameter> identifies the type of database object;
27191 <parameter>schema</parameter> is the schema name that the object
27192 belongs in, or <literal>NULL</literal> for object types that do not
27193 belong to schemas;
27194 <parameter>name</parameter> is the name of the object, quoted if
27195 necessary, if the name (along with schema name, if pertinent) is
27196 sufficient to uniquely identify the object,
27197 otherwise <literal>NULL</literal>;
27198 <parameter>identity</parameter> is the complete object identity, with
27199 the precise format depending on object type, and each name within the
27200 format being schema-qualified and quoted as necessary. Undefined
27201 objects are identified with <literal>NULL</literal> values.
27202 </para></entry>
27203 </row>
27204
27205 <row>
27206 <entry role="func_table_entry"><para role="func_signature">
27207 <indexterm>
27208 <primary>pg_identify_object_as_address</primary>
27209 </indexterm>
27210 <function>pg_identify_object_as_address</function> ( <parameter>classid</parameter> <type>oid</type>, <parameter>objid</parameter> <type>oid</type>, <parameter>objsubid</parameter> <type>integer</type> )
27211 <returnvalue>record</returnvalue>
27212 ( <parameter>type</parameter> <type>text</type>,
27213 <parameter>object_names</parameter> <type>text[]</type>,
27214 <parameter>object_args</parameter> <type>text[]</type> )
27215 </para>
27216 <para>
27217 Returns a row containing enough information to uniquely identify the
27218 database object specified by catalog OID, object OID and sub-object
27219 ID.
27220 The returned information is independent of the current server, that
27221 is, it could be used to identify an identically named object in
27222 another server.
27223 <parameter>type</parameter> identifies the type of database object;
27224 <parameter>object_names</parameter> and
27225 <parameter>object_args</parameter>
27226 are text arrays that together form a reference to the object.
27227 These three values can be passed
27228 to <function>pg_get_object_address</function> to obtain the internal
27229 address of the object.
27230 </para></entry>
27231 </row>
27232
27233 <row>
27234 <entry role="func_table_entry"><para role="func_signature">
27235 <indexterm>
27236 <primary>pg_get_object_address</primary>
27237 </indexterm>
27238 <function>pg_get_object_address</function> ( <parameter>type</parameter> <type>text</type>, <parameter>object_names</parameter> <type>text[]</type>, <parameter>object_args</parameter> <type>text[]</type> )
27239 <returnvalue>record</returnvalue>
27240 ( <parameter>classid</parameter> <type>oid</type>,
27241 <parameter>objid</parameter> <type>oid</type>,
27242 <parameter>objsubid</parameter> <type>integer</type> )
27243 </para>
27244 <para>
27245 Returns a row containing enough information to uniquely identify the
27246 database object specified by a type code and object name and argument
27247 arrays.
27248 The returned values are the ones that would be used in system catalogs
27249 such as <structname>pg_depend</structname>; they can be passed to
27250 other system functions such as <function>pg_describe_object</function>
27251 or <function>pg_identify_object</function>.
27252 <parameter>classid</parameter> is the OID of the system catalog
27253 containing the object;
27254 <parameter>objid</parameter> is the OID of the object itself, and
27255 <parameter>objsubid</parameter> is the sub-object ID, or zero if none.
27256 This function is the inverse
27257 of <function>pg_identify_object_as_address</function>.
27258 Undefined objects are identified with <literal>NULL</literal> values.
27259 </para></entry>
27260 </row>
27261 </tbody>
27262 </tgroup>
27263 </table>
27264
27265 <para>
27266 <function>pg_get_acl</function> is useful for retrieving and inspecting
27267 the privileges associated with database objects without looking at
27268 specific catalogs. For example, to retrieve all the granted privileges
27269 on objects in the current database:
27270 <programlisting>
27271 postgres=# SELECT
27272 (pg_identify_object(s.classid,s.objid,s.objsubid)).*,
27273 pg_catalog.pg_get_acl(s.classid,s.objid,s.objsubid) AS acl
27274 FROM pg_catalog.pg_shdepend AS s
27275 JOIN pg_catalog.pg_database AS d
27276 ON d.datname = current_database() AND
27277 d.oid = s.dbid
27278 JOIN pg_catalog.pg_authid AS a
27279 ON a.oid = s.refobjid AND
27280 s.refclassid = 'pg_authid'::regclass
27281 WHERE s.deptype = 'a';
27282 -[ RECORD 1 ]-----------------------------------------
27283 type | table
27284 schema | public
27285 name | testtab
27286 identity | public.testtab
27287 acl | {postgres=arwdDxtm/postgres,foo=r/postgres}
27288 </programlisting>
27289 </para>
27290
27291 </sect2>
27292
27293 <sect2 id="functions-info-comment">
27294 <title>Comment Information Functions</title>
27295
27296 <indexterm>
27297 <primary>comment</primary>
27298 <secondary sortas="database objects">about database objects</secondary>
27299 </indexterm>
27300
27301 <para>
27302 The functions shown in <xref linkend="functions-info-comment-table"/>
27303 extract comments previously stored with the <xref linkend="sql-comment"/>
27304 command. A null value is returned if no
27305 comment could be found for the specified parameters.
27306 </para>
27307
27308 <table id="functions-info-comment-table">
27309 <title>Comment Information Functions</title>
27310 <tgroup cols="1">
27311 <thead>
27312 <row>
27313 <entry role="func_table_entry"><para role="func_signature">
27314 Function
27315 </para>
27316 <para>
27317 Description
27318 </para></entry>
27319 </row>
27320 </thead>
27321
27322 <tbody>
27323 <row>
27324 <entry role="func_table_entry"><para role="func_signature">
27325 <indexterm>
27326 <primary>col_description</primary>
27327 </indexterm>
27328 <function>col_description</function> ( <parameter>table</parameter> <type>oid</type>, <parameter>column</parameter> <type>integer</type> )
27329 <returnvalue>text</returnvalue>
27330 </para>
27331 <para>
27332 Returns the comment for a table column, which is specified by the OID
27333 of its table and its column number.
27334 (<function>obj_description</function> cannot be used for table
27335 columns, since columns do not have OIDs of their own.)
27336 </para></entry>
27337 </row>
27338
27339 <row>
27340 <entry role="func_table_entry"><para role="func_signature">
27341 <indexterm>
27342 <primary>obj_description</primary>
27343 </indexterm>
27344 <function>obj_description</function> ( <parameter>object</parameter> <type>oid</type>, <parameter>catalog</parameter> <type>name</type> )
27345 <returnvalue>text</returnvalue>
27346 </para>
27347 <para>
27348 Returns the comment for a database object specified by its OID and the
27349 name of the containing system catalog. For
27350 example, <literal>obj_description(123456, 'pg_class')</literal> would
27351 retrieve the comment for the table with OID 123456.
27352 </para></entry>
27353 </row>
27354
27355 <row>
27356 <entry role="func_table_entry"><para role="func_signature">
27357 <function>obj_description</function> ( <parameter>object</parameter> <type>oid</type> )
27358 <returnvalue>text</returnvalue>
27359 </para>
27360 <para>
27361 Returns the comment for a database object specified by its OID alone.
27362 This is <emphasis>deprecated</emphasis> since there is no guarantee
27363 that OIDs are unique across different system catalogs; therefore, the
27364 wrong comment might be returned.
27365 </para></entry>
27366 </row>
27367
27368 <row>
27369 <entry role="func_table_entry"><para role="func_signature">
27370 <indexterm>
27371 <primary>shobj_description</primary>
27372 </indexterm>
27373 <function>shobj_description</function> ( <parameter>object</parameter> <type>oid</type>, <parameter>catalog</parameter> <type>name</type> )
27374 <returnvalue>text</returnvalue>
27375 </para>
27376 <para>
27377 Returns the comment for a shared database object specified by its OID
27378 and the name of the containing system catalog. This is just
27379 like <function>obj_description</function> except that it is used for
27380 retrieving comments on shared objects (that is, databases, roles, and
27381 tablespaces). Some system catalogs are global to all databases within
27382 each cluster, and the descriptions for objects in them are stored
27383 globally as well.
27384 </para></entry>
27385 </row>
27386 </tbody>
27387 </tgroup>
27388 </table>
27389
27390 </sect2>
27391
27392 <sect2 id="functions-info-validity">
27393 <title>Data Validity Checking Functions</title>
27394
27395 <para>
27396 The functions shown in <xref linkend="functions-info-validity-table"/>
27397 can be helpful for checking validity of proposed input data.
27398 </para>
27399
27400 <table id="functions-info-validity-table">
27401 <title>Data Validity Checking Functions</title>
27402 <tgroup cols="1">
27403 <thead>
27404 <row>
27405 <entry role="func_table_entry"><para role="func_signature">
27406 Function
27407 </para>
27408 <para>
27409 Description
27410 </para>
27411 <para>
27412 Example(s)
27413 </para></entry>
27414 </row>
27415 </thead>
27416
27417 <tbody>
27418 <row>
27419 <entry role="func_table_entry"><para role="func_signature">
27420 <indexterm>
27421 <primary>pg_input_is_valid</primary>
27422 </indexterm>
27423 <function>pg_input_is_valid</function> (
27424 <parameter>string</parameter> <type>text</type>,
27425 <parameter>type</parameter> <type>text</type>
27426 )
27427 <returnvalue>boolean</returnvalue>
27428 </para>
27429 <para>
27430 Tests whether the given <parameter>string</parameter> is valid
27431 input for the specified data type, returning true or false.
27432 </para>
27433 <para>
27434 This function will only work as desired if the data type's input
27435 function has been updated to report invalid input as
27436 a <quote>soft</quote> error. Otherwise, invalid input will abort
27437 the transaction, just as if the string had been cast to the type
27438 directly.
27439 </para>
27440 <para>
27441 <literal>pg_input_is_valid('42', 'integer')</literal>
27442 <returnvalue>t</returnvalue>
27443 </para>
27444 <para>
27445 <literal>pg_input_is_valid('42000000000', 'integer')</literal>
27446 <returnvalue>f</returnvalue>
27447 </para>
27448 <para>
27449 <literal>pg_input_is_valid('1234.567', 'numeric(7,4)')</literal>
27450 <returnvalue>f</returnvalue>
27451 </para></entry>
27452 </row>
27453 <row>
27454 <entry role="func_table_entry"><para role="func_signature">
27455 <indexterm>
27456 <primary>pg_input_error_info</primary>
27457 </indexterm>
27458 <function>pg_input_error_info</function> (
27459 <parameter>string</parameter> <type>text</type>,
27460 <parameter>type</parameter> <type>text</type>
27461 )
27462 <returnvalue>record</returnvalue>
27463 ( <parameter>message</parameter> <type>text</type>,
27464 <parameter>detail</parameter> <type>text</type>,
27465 <parameter>hint</parameter> <type>text</type>,
27466 <parameter>sql_error_code</parameter> <type>text</type> )
27467 </para>
27468 <para>
27469 Tests whether the given <parameter>string</parameter> is valid
27470 input for the specified data type; if not, return the details of
27471 the error that would have been thrown. If the input is valid, the
27472 results are NULL. The inputs are the same as
27473 for <function>pg_input_is_valid</function>.
27474 </para>
27475 <para>
27476 This function will only work as desired if the data type's input
27477 function has been updated to report invalid input as
27478 a <quote>soft</quote> error. Otherwise, invalid input will abort
27479 the transaction, just as if the string had been cast to the type
27480 directly.
27481 </para>
27482 <para>
27483 <literal>SELECT * FROM pg_input_error_info('42000000000', 'integer')</literal>
27484 <returnvalue></returnvalue>
27485 <programlisting>
27486 message | detail | hint | sql_error_code
27487 ------------------------------------------------------+--------+------+----------------
27488 value "42000000000" is out of range for type integer | | | 22003
27489 </programlisting>
27490 </para></entry>
27491 </row>
27492 </tbody>
27493 </tgroup>
27494 </table>
27495
27496 </sect2>
27497
27498 <sect2 id="functions-info-snapshot">
27499 <title>Transaction ID and Snapshot Information Functions</title>
27500
27501 <para>
27502 The functions shown in <xref linkend="functions-pg-snapshot"/>
27503 provide server transaction information in an exportable form. The main
27504 use of these functions is to determine which transactions were committed
27505 between two snapshots.
27506 </para>
27507
27508 <table id="functions-pg-snapshot">
27509 <title>Transaction ID and Snapshot Information Functions</title>
27510 <tgroup cols="1">
27511 <thead>
27512 <row>
27513 <entry role="func_table_entry"><para role="func_signature">
27514 Function
27515 </para>
27516 <para>
27517 Description
27518 </para></entry>
27519 </row>
27520 </thead>
27521
27522 <tbody>
27523 <row>
27524 <entry role="func_table_entry"><para role="func_signature">
27525 <indexterm>
27526 <primary>age</primary>
27527 </indexterm>
27528 <function>age</function> ( <type>xid</type> )
27529 <returnvalue>integer</returnvalue>
27530 </para>
27531 <para>
27532 Returns the number of transactions between the supplied
27533 transaction id and the current transaction counter.
27534 </para></entry>
27535 </row>
27536
27537 <row>
27538 <entry role="func_table_entry"><para role="func_signature">
27539 <indexterm>
27540 <primary>mxid_age</primary>
27541 </indexterm>
27542 <function>mxid_age</function> ( <type>xid</type> )
27543 <returnvalue>integer</returnvalue>
27544 </para>
27545 <para>
27546 Returns the number of multixacts IDs between the supplied
27547 multixact ID and the current multixacts counter.
27548 </para></entry>
27549 </row>
27550
27551 <row>
27552 <entry role="func_table_entry"><para role="func_signature">
27553 <indexterm>
27554 <primary>pg_current_xact_id</primary>
27555 </indexterm>
27556 <function>pg_current_xact_id</function> ()
27557 <returnvalue>xid8</returnvalue>
27558 </para>
27559 <para>
27560 Returns the current transaction's ID. It will assign a new one if the
27561 current transaction does not have one already (because it has not
27562 performed any database updates); see <xref
27563 linkend="transaction-id"/> for details. If executed in a
27564 subtransaction, this will return the top-level transaction ID;
27565 see <xref linkend="subxacts"/> for details.
27566 </para></entry>
27567 </row>
27568
27569 <row>
27570 <entry role="func_table_entry"><para role="func_signature">
27571 <indexterm>
27572 <primary>pg_current_xact_id_if_assigned</primary>
27573 </indexterm>
27574 <function>pg_current_xact_id_if_assigned</function> ()
27575 <returnvalue>xid8</returnvalue>
27576 </para>
27577 <para>
27578 Returns the current transaction's ID, or <literal>NULL</literal> if no
27579 ID is assigned yet. (It's best to use this variant if the transaction
27580 might otherwise be read-only, to avoid unnecessary consumption of an
27581 XID.)
27582 If executed in a subtransaction, this will return the top-level
27583 transaction ID.
27584 </para></entry>
27585 </row>
27586
27587 <row>
27588 <entry role="func_table_entry"><para role="func_signature">
27589 <indexterm>
27590 <primary>pg_xact_status</primary>
27591 </indexterm>
27592 <function>pg_xact_status</function> ( <type>xid8</type> )
27593 <returnvalue>text</returnvalue>
27594 </para>
27595 <para>
27596 Reports the commit status of a recent transaction.
27597 The result is one of <literal>in progress</literal>,
27598 <literal>committed</literal>, or <literal>aborted</literal>,
27599 provided that the transaction is recent enough that the system retains
27600 the commit status of that transaction.
27601 If it is old enough that no references to the transaction survive in
27602 the system and the commit status information has been discarded, the
27603 result is <literal>NULL</literal>.
27604 Applications might use this function, for example, to determine
27605 whether their transaction committed or aborted after the application
27606 and database server become disconnected while
27607 a <literal>COMMIT</literal> is in progress.
27608 Note that prepared transactions are reported as <literal>in
27609 progress</literal>; applications must check <link
27610 linkend="view-pg-prepared-xacts"><structname>pg_prepared_xacts</structname></link>
27611 if they need to determine whether a transaction ID belongs to a
27612 prepared transaction.
27613 </para></entry>
27614 </row>
27615
27616 <row>
27617 <entry role="func_table_entry"><para role="func_signature">
27618 <indexterm>
27619 <primary>pg_current_snapshot</primary>
27620 </indexterm>
27621 <function>pg_current_snapshot</function> ()
27622 <returnvalue>pg_snapshot</returnvalue>
27623 </para>
27624 <para>
27625 Returns a current <firstterm>snapshot</firstterm>, a data structure
27626 showing which transaction IDs are now in-progress.
27627 Only top-level transaction IDs are included in the snapshot;
27628 subtransaction IDs are not shown; see <xref linkend="subxacts"/>
27629 for details.
27630 </para></entry>
27631 </row>
27632
27633 <row>
27634 <entry role="func_table_entry"><para role="func_signature">
27635 <indexterm>
27636 <primary>pg_snapshot_xip</primary>
27637 </indexterm>
27638 <function>pg_snapshot_xip</function> ( <type>pg_snapshot</type> )
27639 <returnvalue>setof xid8</returnvalue>
27640 </para>
27641 <para>
27642 Returns the set of in-progress transaction IDs contained in a snapshot.
27643 </para></entry>
27644 </row>
27645
27646 <row>
27647 <entry role="func_table_entry"><para role="func_signature">
27648 <indexterm>
27649 <primary>pg_snapshot_xmax</primary>
27650 </indexterm>
27651 <function>pg_snapshot_xmax</function> ( <type>pg_snapshot</type> )
27652 <returnvalue>xid8</returnvalue>
27653 </para>
27654 <para>
27655 Returns the <structfield>xmax</structfield> of a snapshot.
27656 </para></entry>
27657 </row>
27658
27659 <row>
27660 <entry role="func_table_entry"><para role="func_signature">
27661 <indexterm>
27662 <primary>pg_snapshot_xmin</primary>
27663 </indexterm>
27664 <function>pg_snapshot_xmin</function> ( <type>pg_snapshot</type> )
27665 <returnvalue>xid8</returnvalue>
27666 </para>
27667 <para>
27668 Returns the <structfield>xmin</structfield> of a snapshot.
27669 </para></entry>
27670 </row>
27671
27672 <row>
27673 <entry role="func_table_entry"><para role="func_signature">
27674 <indexterm>
27675 <primary>pg_visible_in_snapshot</primary>
27676 </indexterm>
27677 <function>pg_visible_in_snapshot</function> ( <type>xid8</type>, <type>pg_snapshot</type> )
27678 <returnvalue>boolean</returnvalue>
27679 </para>
27680 <para>
27681 Is the given transaction ID <firstterm>visible</firstterm> according
27682 to this snapshot (that is, was it completed before the snapshot was
27683 taken)? Note that this function will not give the correct answer for
27684 a subtransaction ID (subxid); see <xref linkend="subxacts"/> for
27685 details.
27686 </para></entry>
27687 </row>
27688
27689 <row>
27690 <entry role="func_table_entry"><para role="func_signature">
27691 <indexterm>
27692 <primary>pg_get_multixact_members</primary>
27693 </indexterm>
27694 <function>pg_get_multixact_members</function> ( <parameter>multixid</parameter> <type>xid</type> )
27695 <returnvalue>setof record</returnvalue>
27696 ( <parameter>xid</parameter> <type>xid</type>,
27697 <parameter>mode</parameter> <type>text</type> )
27698 </para>
27699 <para>
27700 Returns the transaction ID and lock mode for each member of the
27701 specified multixact ID. The lock modes <literal>forupd</literal>,
27702 <literal>fornokeyupd</literal>, <literal>sh</literal>, and
27703 <literal>keysh</literal> correspond to the row-level locks
27704 <literal>FOR UPDATE</literal>, <literal>FOR NO KEY UPDATE</literal>,
27705 <literal>FOR SHARE</literal>, and <literal>FOR KEY SHARE</literal>,
27706 respectively, as described in <xref linkend="locking-rows"/>. Two
27707 additional modes are specific to multixacts:
27708 <literal>nokeyupd</literal>, used by updates that do not modify key
27709 columns, and <literal>upd</literal>, used by updates or deletes that
27710 modify key columns.
27711 </para></entry>
27712 </row>
27713 </tbody>
27714 </tgroup>
27715 </table>
27716
27717 <para>
27718 The internal transaction ID type <type>xid</type> is 32 bits wide and
27719 wraps around every 4 billion transactions. However,
27720 the functions shown in <xref linkend="functions-pg-snapshot"/>, except
27721 <function>age</function>, <function>mxid_age</function>, and
27722 <function>pg_get_multixact_members</function>, use a
27723 64-bit type <type>xid8</type> that does not wrap around during the life
27724 of an installation and can be converted to <type>xid</type> by casting if
27725 required; see <xref linkend="transaction-id"/> for details.
27726 The data type <type>pg_snapshot</type> stores information about
27727 transaction ID visibility at a particular moment in time. Its components
27728 are described in <xref linkend="functions-pg-snapshot-parts"/>.
27729 <type>pg_snapshot</type>'s textual representation is
27730 <literal><replaceable>xmin</replaceable>:<replaceable>xmax</replaceable>:<replaceable>xip_list</replaceable></literal>.
27731 For example <literal>10:20:10,14,15</literal> means
27732 <literal>xmin=10, xmax=20, xip_list=10, 14, 15</literal>.
27733 </para>
27734
27735 <table id="functions-pg-snapshot-parts">
27736 <title>Snapshot Components</title>
27737 <tgroup cols="2">
27738 <thead>
27739 <row>
27740 <entry>Name</entry>
27741 <entry>Description</entry>
27742 </row>
27743 </thead>
27744
27745 <tbody>
27746 <row>
27747 <entry><structfield>xmin</structfield></entry>
27748 <entry>
27749 Lowest transaction ID that was still active. All transaction IDs
27750 less than <structfield>xmin</structfield> are either committed and visible,
27751 or rolled back and dead.
27752 </entry>
27753 </row>
27754
27755 <row>
27756 <entry><structfield>xmax</structfield></entry>
27757 <entry>
27758 One past the highest completed transaction ID. All transaction IDs
27759 greater than or equal to <structfield>xmax</structfield> had not yet
27760 completed as of the time of the snapshot, and thus are invisible.
27761 </entry>
27762 </row>
27763
27764 <row>
27765 <entry><structfield>xip_list</structfield></entry>
27766 <entry>
27767 Transactions in progress at the time of the snapshot. A transaction
27768 ID that is <literal>xmin &lt;= <replaceable>X</replaceable> &lt;
27769 xmax</literal> and not in this list was already completed at the time
27770 of the snapshot, and thus is either visible or dead according to its
27771 commit status. This list does not include the transaction IDs of
27772 subtransactions (subxids).
27773 </entry>
27774 </row>
27775 </tbody>
27776 </tgroup>
27777 </table>
27778
27779 <para>
27780 In releases of <productname>PostgreSQL</productname> before 13 there was
27781 no <type>xid8</type> type, so variants of these functions were provided
27782 that used <type>bigint</type> to represent a 64-bit XID, with a
27783 correspondingly distinct snapshot data type <type>txid_snapshot</type>.
27784 These older functions have <literal>txid</literal> in their names. They
27785 are still supported for backward compatibility, but may be removed from a
27786 future release. See <xref linkend="functions-txid-snapshot"/>.
27787 </para>
27788
27789 <table id="functions-txid-snapshot">
27790 <title>Deprecated Transaction ID and Snapshot Information Functions</title>
27791 <tgroup cols="1">
27792 <thead>
27793 <row>
27794 <entry role="func_table_entry"><para role="func_signature">
27795 Function
27796 </para>
27797 <para>
27798 Description
27799 </para></entry>
27800 </row>
27801 </thead>
27802
27803 <tbody>
27804
27805 <row>
27806 <entry role="func_table_entry"><para role="func_signature">
27807 <indexterm>
27808 <primary>txid_current</primary>
27809 </indexterm>
27810 <function>txid_current</function> ()
27811 <returnvalue>bigint</returnvalue>
27812 </para>
27813 <para>
27814 See <function>pg_current_xact_id()</function>.
27815 </para></entry>
27816 </row>
27817
27818 <row>
27819 <entry role="func_table_entry"><para role="func_signature">
27820 <indexterm>
27821 <primary>txid_current_if_assigned</primary>
27822 </indexterm>
27823 <function>txid_current_if_assigned</function> ()
27824 <returnvalue>bigint</returnvalue>
27825 </para>
27826 <para>
27827 See <function>pg_current_xact_id_if_assigned()</function>.
27828 </para></entry>
27829 </row>
27830
27831 <row>
27832 <entry role="func_table_entry"><para role="func_signature">
27833 <indexterm>
27834 <primary>txid_current_snapshot</primary>
27835 </indexterm>
27836 <function>txid_current_snapshot</function> ()
27837 <returnvalue>txid_snapshot</returnvalue>
27838 </para>
27839 <para>
27840 See <function>pg_current_snapshot()</function>.
27841 </para></entry>
27842 </row>
27843
27844 <row>
27845 <entry role="func_table_entry"><para role="func_signature">
27846 <indexterm>
27847 <primary>txid_snapshot_xip</primary>
27848 </indexterm>
27849 <function>txid_snapshot_xip</function> ( <type>txid_snapshot</type> )
27850 <returnvalue>setof bigint</returnvalue>
27851 </para>
27852 <para>
27853 See <function>pg_snapshot_xip()</function>.
27854 </para></entry>
27855 </row>
27856
27857 <row>
27858 <entry role="func_table_entry"><para role="func_signature">
27859 <indexterm>
27860 <primary>txid_snapshot_xmax</primary>
27861 </indexterm>
27862 <function>txid_snapshot_xmax</function> ( <type>txid_snapshot</type> )
27863 <returnvalue>bigint</returnvalue>
27864 </para>
27865 <para>
27866 See <function>pg_snapshot_xmax()</function>.
27867 </para></entry>
27868 </row>
27869
27870 <row>
27871 <entry role="func_table_entry"><para role="func_signature">
27872 <indexterm>
27873 <primary>txid_snapshot_xmin</primary>
27874 </indexterm>
27875 <function>txid_snapshot_xmin</function> ( <type>txid_snapshot</type> )
27876 <returnvalue>bigint</returnvalue>
27877 </para>
27878 <para>
27879 See <function>pg_snapshot_xmin()</function>.
27880 </para></entry>
27881 </row>
27882
27883 <row>
27884 <entry role="func_table_entry"><para role="func_signature">
27885 <indexterm>
27886 <primary>txid_visible_in_snapshot</primary>
27887 </indexterm>
27888 <function>txid_visible_in_snapshot</function> ( <type>bigint</type>, <type>txid_snapshot</type> )
27889 <returnvalue>boolean</returnvalue>
27890 </para>
27891 <para>
27892 See <function>pg_visible_in_snapshot()</function>.
27893 </para></entry>
27894 </row>
27895
27896 <row>
27897 <entry role="func_table_entry"><para role="func_signature">
27898 <indexterm>
27899 <primary>txid_status</primary>
27900 </indexterm>
27901 <function>txid_status</function> ( <type>bigint</type> )
27902 <returnvalue>text</returnvalue>
27903 </para>
27904 <para>
27905 See <function>pg_xact_status()</function>.
27906 </para></entry>
27907 </row>
27908 </tbody>
27909 </tgroup>
27910 </table>
27911
27912 </sect2>
27913
27914 <sect2 id="functions-info-commit-timestamp">
27915 <title>Committed Transaction Information Functions</title>
27916
27917 <para>
27918 The functions shown in <xref linkend="functions-commit-timestamp"/>
27919 provide information about when past transactions were committed.
27920 They only provide useful data when the
27921 <xref linkend="guc-track-commit-timestamp"/> configuration option is
27922 enabled, and only for transactions that were committed after it was
27923 enabled. Commit timestamp information is routinely removed during
27924 vacuum.
27925 </para>
27926
27927 <table id="functions-commit-timestamp">
27928 <title>Committed Transaction Information Functions</title>
27929 <tgroup cols="1">
27930 <thead>
27931 <row>
27932 <entry role="func_table_entry"><para role="func_signature">
27933 Function
27934 </para>
27935 <para>
27936 Description
27937 </para></entry>
27938 </row>
27939 </thead>
27940
27941 <tbody>
27942 <row>
27943 <entry role="func_table_entry"><para role="func_signature">
27944 <indexterm>
27945 <primary>pg_xact_commit_timestamp</primary>
27946 </indexterm>
27947 <function>pg_xact_commit_timestamp</function> ( <type>xid</type> )
27948 <returnvalue>timestamp with time zone</returnvalue>
27949 </para>
27950 <para>
27951 Returns the commit timestamp of a transaction.
27952 </para></entry>
27953 </row>
27954
27955 <row>
27956 <entry role="func_table_entry"><para role="func_signature">
27957 <indexterm>
27958 <primary>pg_xact_commit_timestamp_origin</primary>
27959 </indexterm>
27960 <function>pg_xact_commit_timestamp_origin</function> ( <type>xid</type> )
27961 <returnvalue>record</returnvalue>
27962 ( <parameter>timestamp</parameter> <type>timestamp with time zone</type>,
27963 <parameter>roident</parameter> <type>oid</type>)
27964 </para>
27965 <para>
27966 Returns the commit timestamp and replication origin of a transaction.
27967 </para></entry>
27968 </row>
27969
27970 <row>
27971 <entry role="func_table_entry"><para role="func_signature">
27972 <indexterm>
27973 <primary>pg_last_committed_xact</primary>
27974 </indexterm>
27975 <function>pg_last_committed_xact</function> ()
27976 <returnvalue>record</returnvalue>
27977 ( <parameter>xid</parameter> <type>xid</type>,
27978 <parameter>timestamp</parameter> <type>timestamp with time zone</type>,
27979 <parameter>roident</parameter> <type>oid</type> )
27980 </para>
27981 <para>
27982 Returns the transaction ID, commit timestamp and replication origin
27983 of the latest committed transaction.
27984 </para></entry>
27985 </row>
27986 </tbody>
27987 </tgroup>
27988 </table>
27989
27990 </sect2>
27991
27992 <sect2 id="functions-info-controldata">
27993 <title>Control Data Functions</title>
27994
27995 <para>
27996 The functions shown in <xref linkend="functions-controldata"/>
27997 print information initialized during <command>initdb</command>, such
27998 as the catalog version. They also show information about write-ahead
27999 logging and checkpoint processing. This information is cluster-wide,
28000 not specific to any one database. These functions provide most of the same
28001 information, from the same source, as the
28002 <xref linkend="app-pgcontroldata"/> application.
28003 </para>
28004
28005 <table id="functions-controldata">
28006 <title>Control Data Functions</title>
28007 <tgroup cols="1">
28008 <thead>
28009 <row>
28010 <entry role="func_table_entry"><para role="func_signature">
28011 Function
28012 </para>
28013 <para>
28014 Description
28015 </para></entry>
28016 </row>
28017 </thead>
28018
28019 <tbody>
28020 <row>
28021 <entry role="func_table_entry"><para role="func_signature">
28022 <indexterm>
28023 <primary>pg_control_checkpoint</primary>
28024 </indexterm>
28025 <function>pg_control_checkpoint</function> ()
28026 <returnvalue>record</returnvalue>
28027 </para>
28028 <para>
28029 Returns information about current checkpoint state, as shown in
28030 <xref linkend="functions-pg-control-checkpoint"/>.
28031 </para></entry>
28032 </row>
28033
28034 <row>
28035 <entry role="func_table_entry"><para role="func_signature">
28036 <indexterm>
28037 <primary>pg_control_system</primary>
28038 </indexterm>
28039 <function>pg_control_system</function> ()
28040 <returnvalue>record</returnvalue>
28041 </para>
28042 <para>
28043 Returns information about current control file state, as shown in
28044 <xref linkend="functions-pg-control-system"/>.
28045 </para></entry>
28046 </row>
28047
28048 <row>
28049 <entry role="func_table_entry"><para role="func_signature">
28050 <indexterm>
28051 <primary>pg_control_init</primary>
28052 </indexterm>
28053 <function>pg_control_init</function> ()
28054 <returnvalue>record</returnvalue>
28055 </para>
28056 <para>
28057 Returns information about cluster initialization state, as shown in
28058 <xref linkend="functions-pg-control-init"/>.
28059 </para></entry>
28060 </row>
28061
28062 <row>
28063 <entry role="func_table_entry"><para role="func_signature">
28064 <indexterm>
28065 <primary>pg_control_recovery</primary>
28066 </indexterm>
28067 <function>pg_control_recovery</function> ()
28068 <returnvalue>record</returnvalue>
28069 </para>
28070 <para>
28071 Returns information about recovery state, as shown in
28072 <xref linkend="functions-pg-control-recovery"/>.
28073 </para></entry>
28074 </row>
28075 </tbody>
28076 </tgroup>
28077 </table>
28078
28079 <table id="functions-pg-control-checkpoint">
28080 <title><function>pg_control_checkpoint</function> Output Columns</title>
28081 <tgroup cols="2">
28082 <thead>
28083 <row>
28084 <entry>Column Name</entry>
28085 <entry>Data Type</entry>
28086 </row>
28087 </thead>
28088
28089 <tbody>
28090
28091 <row>
28092 <entry><structfield>checkpoint_lsn</structfield></entry>
28093 <entry><type>pg_lsn</type></entry>
28094 </row>
28095
28096 <row>
28097 <entry><structfield>redo_lsn</structfield></entry>
28098 <entry><type>pg_lsn</type></entry>
28099 </row>
28100
28101 <row>
28102 <entry><structfield>redo_wal_file</structfield></entry>
28103 <entry><type>text</type></entry>
28104 </row>
28105
28106 <row>
28107 <entry><structfield>timeline_id</structfield></entry>
28108 <entry><type>integer</type></entry>
28109 </row>
28110
28111 <row>
28112 <entry><structfield>prev_timeline_id</structfield></entry>
28113 <entry><type>integer</type></entry>
28114 </row>
28115
28116 <row>
28117 <entry><structfield>full_page_writes</structfield></entry>
28118 <entry><type>boolean</type></entry>
28119 </row>
28120
28121 <row>
28122 <entry><structfield>next_xid</structfield></entry>
28123 <entry><type>text</type></entry>
28124 </row>
28125
28126 <row>
28127 <entry><structfield>next_oid</structfield></entry>
28128 <entry><type>oid</type></entry>
28129 </row>
28130
28131 <row>
28132 <entry><structfield>next_multixact_id</structfield></entry>
28133 <entry><type>xid</type></entry>
28134 </row>
28135
28136 <row>
28137 <entry><structfield>next_multi_offset</structfield></entry>
28138 <entry><type>xid</type></entry>
28139 </row>
28140
28141 <row>
28142 <entry><structfield>oldest_xid</structfield></entry>
28143 <entry><type>xid</type></entry>
28144 </row>
28145
28146 <row>
28147 <entry><structfield>oldest_xid_dbid</structfield></entry>
28148 <entry><type>oid</type></entry>
28149 </row>
28150
28151 <row>
28152 <entry><structfield>oldest_active_xid</structfield></entry>
28153 <entry><type>xid</type></entry>
28154 </row>
28155
28156 <row>
28157 <entry><structfield>oldest_multi_xid</structfield></entry>
28158 <entry><type>xid</type></entry>
28159 </row>
28160
28161 <row>
28162 <entry><structfield>oldest_multi_dbid</structfield></entry>
28163 <entry><type>oid</type></entry>
28164 </row>
28165
28166 <row>
28167 <entry><structfield>oldest_commit_ts_xid</structfield></entry>
28168 <entry><type>xid</type></entry>
28169 </row>
28170
28171 <row>
28172 <entry><structfield>newest_commit_ts_xid</structfield></entry>
28173 <entry><type>xid</type></entry>
28174 </row>
28175
28176 <row>
28177 <entry><structfield>checkpoint_time</structfield></entry>
28178 <entry><type>timestamp with time zone</type></entry>
28179 </row>
28180
28181 </tbody>
28182 </tgroup>
28183 </table>
28184
28185 <table id="functions-pg-control-system">
28186 <title><function>pg_control_system</function> Output Columns</title>
28187 <tgroup cols="2">
28188 <thead>
28189 <row>
28190 <entry>Column Name</entry>
28191 <entry>Data Type</entry>
28192 </row>
28193 </thead>
28194
28195 <tbody>
28196
28197 <row>
28198 <entry><structfield>pg_control_version</structfield></entry>
28199 <entry><type>integer</type></entry>
28200 </row>
28201
28202 <row>
28203 <entry><structfield>catalog_version_no</structfield></entry>
28204 <entry><type>integer</type></entry>
28205 </row>
28206
28207 <row>
28208 <entry><structfield>system_identifier</structfield></entry>
28209 <entry><type>bigint</type></entry>
28210 </row>
28211
28212 <row>
28213 <entry><structfield>pg_control_last_modified</structfield></entry>
28214 <entry><type>timestamp with time zone</type></entry>
28215 </row>
28216
28217 </tbody>
28218 </tgroup>
28219 </table>
28220
28221 <table id="functions-pg-control-init">
28222 <title><function>pg_control_init</function> Output Columns</title>
28223 <tgroup cols="2">
28224 <thead>
28225 <row>
28226 <entry>Column Name</entry>
28227 <entry>Data Type</entry>
28228 </row>
28229 </thead>
28230
28231 <tbody>
28232
28233 <row>
28234 <entry><structfield>max_data_alignment</structfield></entry>
28235 <entry><type>integer</type></entry>
28236 </row>
28237
28238 <row>
28239 <entry><structfield>database_block_size</structfield></entry>
28240 <entry><type>integer</type></entry>
28241 </row>
28242
28243 <row>
28244 <entry><structfield>blocks_per_segment</structfield></entry>
28245 <entry><type>integer</type></entry>
28246 </row>
28247
28248 <row>
28249 <entry><structfield>wal_block_size</structfield></entry>
28250 <entry><type>integer</type></entry>
28251 </row>
28252
28253 <row>
28254 <entry><structfield>bytes_per_wal_segment</structfield></entry>
28255 <entry><type>integer</type></entry>
28256 </row>
28257
28258 <row>
28259 <entry><structfield>max_identifier_length</structfield></entry>
28260 <entry><type>integer</type></entry>
28261 </row>
28262
28263 <row>
28264 <entry><structfield>max_index_columns</structfield></entry>
28265 <entry><type>integer</type></entry>
28266 </row>
28267
28268 <row>
28269 <entry><structfield>max_toast_chunk_size</structfield></entry>
28270 <entry><type>integer</type></entry>
28271 </row>
28272
28273 <row>
28274 <entry><structfield>large_object_chunk_size</structfield></entry>
28275 <entry><type>integer</type></entry>
28276 </row>
28277
28278 <row>
28279 <entry><structfield>float8_pass_by_value</structfield></entry>
28280 <entry><type>boolean</type></entry>
28281 </row>
28282
28283 <row>
28284 <entry><structfield>data_page_checksum_version</structfield></entry>
28285 <entry><type>integer</type></entry>
28286 </row>
28287
28288 <row>
28289 <entry><structfield>default_char_signedness</structfield></entry>
28290 <entry><type>boolean</type></entry>
28291 </row>
28292
28293 </tbody>
28294 </tgroup>
28295 </table>
28296
28297 <table id="functions-pg-control-recovery">
28298 <title><function>pg_control_recovery</function> Output Columns</title>
28299 <tgroup cols="2">
28300 <thead>
28301 <row>
28302 <entry>Column Name</entry>
28303 <entry>Data Type</entry>
28304 </row>
28305 </thead>
28306
28307 <tbody>
28308
28309 <row>
28310 <entry><structfield>min_recovery_end_lsn</structfield></entry>
28311 <entry><type>pg_lsn</type></entry>
28312 </row>
28313
28314 <row>
28315 <entry><structfield>min_recovery_end_timeline</structfield></entry>
28316 <entry><type>integer</type></entry>
28317 </row>
28318
28319 <row>
28320 <entry><structfield>backup_start_lsn</structfield></entry>
28321 <entry><type>pg_lsn</type></entry>
28322 </row>
28323
28324 <row>
28325 <entry><structfield>backup_end_lsn</structfield></entry>
28326 <entry><type>pg_lsn</type></entry>
28327 </row>
28328
28329 <row>
28330 <entry><structfield>end_of_backup_record_required</structfield></entry>
28331 <entry><type>boolean</type></entry>
28332 </row>
28333
28334 </tbody>
28335 </tgroup>
28336 </table>
28337
28338 </sect2>
28339
28340 <sect2 id="functions-info-version">
28341 <title>Version Information Functions</title>
28342
28343 <para>
28344 The functions shown in <xref linkend="functions-version"/>
28345 print version information.
28346 </para>
28347
28348 <table id="functions-version">
28349 <title>Version Information Functions</title>
28350 <tgroup cols="1">
28351 <thead>
28352 <row>
28353 <entry role="func_table_entry"><para role="func_signature">
28354 Function
28355 </para>
28356 <para>
28357 Description
28358 </para></entry>
28359 </row>
28360 </thead>
28361
28362 <tbody>
28363 <row>
28364 <entry role="func_table_entry"><para role="func_signature">
28365 <indexterm>
28366 <primary>version</primary>
28367 </indexterm>
28368 <function>version</function> ()
28369 <returnvalue>text</returnvalue>
28370 </para>
28371 <para>
28372 Returns a string describing the <productname>PostgreSQL</productname>
28373 server's version. You can also get this information from
28374 <xref linkend="guc-server-version"/>, or for a machine-readable
28375 version use <xref linkend="guc-server-version-num"/>. Software
28376 developers should use <varname>server_version_num</varname> (available
28377 since 8.2) or <xref linkend="libpq-PQserverVersion"/> instead of
28378 parsing the text version.
28379 </para></entry>
28380 </row>
28381
28382 <row>
28383 <entry role="func_table_entry"><para role="func_signature">
28384 <indexterm>
28385 <primary>unicode_version</primary>
28386 </indexterm>
28387 <function>unicode_version</function> ()
28388 <returnvalue>text</returnvalue>
28389 </para>
28390 <para>
28391 Returns a string representing the version of Unicode used by
28392 <productname>PostgreSQL</productname>.
28393 </para></entry>
28394 </row>
28395 <row>
28396 <entry role="func_table_entry"><para role="func_signature">
28397 <indexterm>
28398 <primary>icu_unicode_version</primary>
28399 </indexterm>
28400 <function>icu_unicode_version</function> ()
28401 <returnvalue>text</returnvalue>
28402 </para>
28403 <para>
28404 Returns a string representing the version of Unicode used by ICU, if
28405 the server was built with ICU support; otherwise returns
28406 <literal>NULL</literal> </para></entry>
28407 </row>
28408 </tbody>
28409 </tgroup>
28410 </table>
28411
28412 </sect2>
28413
28414 <sect2 id="functions-info-wal-summary">
28415 <title>WAL Summarization Information Functions</title>
28416
28417 <para>
28418 The functions shown in <xref linkend="functions-wal-summary"/>
28419 print information about the status of WAL summarization.
28420 See <xref linkend="guc-summarize-wal" />.
28421 </para>
28422
28423 <table id="functions-wal-summary">
28424 <title>WAL Summarization Information Functions</title>
28425 <tgroup cols="1">
28426 <thead>
28427 <row>
28428 <entry role="func_table_entry"><para role="func_signature">
28429 Function
28430 </para>
28431 <para>
28432 Description
28433 </para></entry>
28434 </row>
28435 </thead>
28436
28437 <tbody>
28438 <row>
28439 <entry role="func_table_entry"><para role="func_signature">
28440 <indexterm>
28441 <primary>pg_available_wal_summaries</primary>
28442 </indexterm>
28443 <function>pg_available_wal_summaries</function> ()
28444 <returnvalue>setof record</returnvalue>
28445 ( <parameter>tli</parameter> <type>bigint</type>,
28446 <parameter>start_lsn</parameter> <type>pg_lsn</type>,
28447 <parameter>end_lsn</parameter> <type>pg_lsn</type> )
28448 </para>
28449 <para>
28450 Returns information about the WAL summary files present in the
28451 data directory, under <literal>pg_wal/summaries</literal>.
28452 One row will be returned per WAL summary file. Each file summarizes
28453 WAL on the indicated TLI within the indicated LSN range. This function
28454 might be useful to determine whether enough WAL summaries are present
28455 on the server to take an incremental backup based on some prior
28456 backup whose start LSN is known.
28457 </para></entry>
28458 </row>
28459
28460 <row>
28461 <entry role="func_table_entry"><para role="func_signature">
28462 <indexterm>
28463 <primary>pg_wal_summary_contents</primary>
28464 </indexterm>
28465 <function>pg_wal_summary_contents</function> ( <parameter>tli</parameter> <type>bigint</type>, <parameter>start_lsn</parameter> <type>pg_lsn</type>, <parameter>end_lsn</parameter> <type>pg_lsn</type> )
28466 <returnvalue>setof record</returnvalue>
28467 ( <parameter>relfilenode</parameter> <type>oid</type>,
28468 <parameter>reltablespace</parameter> <type>oid</type>,
28469 <parameter>reldatabase</parameter> <type>oid</type>,
28470 <parameter>relforknumber</parameter> <type>smallint</type>,
28471 <parameter>relblocknumber</parameter> <type>bigint</type>,
28472 <parameter>is_limit_block</parameter> <type>boolean</type> )
28473 </para>
28474 <para>
28475 Returns one information about the contents of a single WAL summary file
28476 identified by TLI and starting and ending LSNs. Each row with
28477 <literal>is_limit_block</literal> false indicates that the block
28478 identified by the remaining output columns was modified by at least
28479 one WAL record within the range of records summarized by this file.
28480 Each row with <literal>is_limit_block</literal> true indicates either
28481 that (a) the relation fork was truncated to the length given by
28482 <literal>relblocknumber</literal> within the relevant range of WAL
28483 records or (b) that the relation fork was created or dropped within
28484 the relevant range of WAL records; in such cases,
28485 <literal>relblocknumber</literal> will be zero.
28486 </para></entry>
28487 </row>
28488
28489 <row>
28490 <entry role="func_table_entry"><para role="func_signature">
28491 <indexterm>
28492 <primary>pg_get_wal_summarizer_state</primary>
28493 </indexterm>
28494 <function>pg_get_wal_summarizer_state</function> ()
28495 <returnvalue>record</returnvalue>
28496 ( <parameter>summarized_tli</parameter> <type>bigint</type>,
28497 <parameter>summarized_lsn</parameter> <type>pg_lsn</type>,
28498 <parameter>pending_lsn</parameter> <type>pg_lsn</type>,
28499 <parameter>summarizer_pid</parameter> <type>int</type> )
28500 </para>
28501 <para>
28502 Returns information about the progress of the WAL summarizer. If the
28503 WAL summarizer has never run since the instance was started, then
28504 <literal>summarized_tli</literal> and <literal>summarized_lsn</literal>
28505 will be <literal>0</literal> and <literal>0/0</literal> respectively;
28506 otherwise, they will be the TLI and ending LSN of the last WAL summary
28507 file written to disk. If the WAL summarizer is currently running,
28508 <literal>pending_lsn</literal> will be the ending LSN of the last
28509 record that it has consumed, which must always be greater than or
28510 equal to <literal>summarized_lsn</literal>; if the WAL summarizer is
28511 not running, it will be equal to <literal>summarized_lsn</literal>.
28512 <literal>summarizer_pid</literal> is the PID of the WAL summarizer
28513 process, if it is running, and otherwise NULL.
28514 </para>
28515 <para>
28516 As a special exception, the WAL summarizer will refuse to generate
28517 WAL summary files if run on WAL generated under
28518 <literal>wal_level=minimal</literal>, since such summaries would be
28519 unsafe to use as the basis for an incremental backup. In this case,
28520 the fields above will continue to advance as if summaries were being
28521 generated, but nothing will be written to disk. Once the summarizer
28522 reaches WAL generated while <literal>wal_level</literal> was set
28523 to <literal>replica</literal> or higher, it will resume writing
28524 summaries to disk.
28525 </para></entry>
28526 </row>
28527 </tbody>
28528 </tgroup>
28529 </table>
28530
28531 </sect2>
28532
28533 </sect1>
28534
28535 <sect1 id="functions-admin">
28536 <title>System Administration Functions</title>
28537
28538 <para>
28539 The functions described in this section are used to control and
28540 monitor a <productname>PostgreSQL</productname> installation.
28541 </para>
28542
28543 <sect2 id="functions-admin-set">
28544 <title>Configuration Settings Functions</title>
28545
28546 <indexterm>
28547 <primary>SET</primary>
28548 </indexterm>
28549
28550 <indexterm>
28551 <primary>SHOW</primary>
28552 </indexterm>
28553
28554 <indexterm>
28555 <primary>configuration</primary>
28556 <secondary sortas="server">of the server</secondary>
28557 <tertiary>functions</tertiary>
28558 </indexterm>
28559
28560 <para>
28561 <xref linkend="functions-admin-set-table"/> shows the functions
28562 available to query and alter run-time configuration parameters.
28563 </para>
28564
28565 <table id="functions-admin-set-table">
28566 <title>Configuration Settings Functions</title>
28567 <tgroup cols="1">
28568 <thead>
28569 <row>
28570 <entry role="func_table_entry"><para role="func_signature">
28571 Function
28572 </para>
28573 <para>
28574 Description
28575 </para>
28576 <para>
28577 Example(s)
28578 </para></entry>
28579 </row>
28580 </thead>
28581
28582 <tbody>
28583 <row>
28584 <entry role="func_table_entry"><para role="func_signature">
28585 <indexterm>
28586 <primary>current_setting</primary>
28587 </indexterm>
28588 <function>current_setting</function> ( <parameter>setting_name</parameter> <type>text</type> <optional>, <parameter>missing_ok</parameter> <type>boolean</type> </optional> )
28589 <returnvalue>text</returnvalue>
28590 </para>
28591 <para>
28592 Returns the current value of the
28593 setting <parameter>setting_name</parameter>. If there is no such
28594 setting, <function>current_setting</function> throws an error
28595 unless <parameter>missing_ok</parameter> is supplied and
28596 is <literal>true</literal> (in which case NULL is returned).
28597 This function corresponds to
28598 the <acronym>SQL</acronym> command <xref linkend="sql-show"/>.
28599 </para>
28600 <para>
28601 <literal>current_setting('datestyle')</literal>
28602 <returnvalue>ISO, MDY</returnvalue>
28603 </para></entry>
28604 </row>
28605
28606 <row>
28607 <entry role="func_table_entry"><para role="func_signature">
28608 <indexterm>
28609 <primary>set_config</primary>
28610 </indexterm>
28611 <function>set_config</function> (
28612 <parameter>setting_name</parameter> <type>text</type>,
28613 <parameter>new_value</parameter> <type>text</type>,
28614 <parameter>is_local</parameter> <type>boolean</type> )
28615 <returnvalue>text</returnvalue>
28616 </para>
28617 <para>
28618 Sets the parameter <parameter>setting_name</parameter>
28619 to <parameter>new_value</parameter>, and returns that value.
28620 If <parameter>is_local</parameter> is <literal>true</literal>, the new
28621 value will only apply during the current transaction. If you want the
28622 new value to apply for the rest of the current session,
28623 use <literal>false</literal> instead. This function corresponds to
28624 the SQL command <xref linkend="sql-set"/>.
28625 </para>
28626 <para>
28627 <function>set_config</function> accepts the NULL value for
28628 <parameter>new_value</parameter>, but as settings cannot be null, it
28629 is interpreted as a request to reset the setting to its default value.
28630 </para>
28631 <para>
28632 <literal>set_config('log_statement_stats', 'off', false)</literal>
28633 <returnvalue>off</returnvalue>
28634 </para></entry>
28635 </row>
28636 </tbody>
28637 </tgroup>
28638 </table>
28639
28640 </sect2>
28641
28642 <sect2 id="functions-admin-signal">
28643 <title>Server Signaling Functions</title>
28644
28645 <indexterm>
28646 <primary>signal</primary>
28647 <secondary sortas="backend">backend processes</secondary>
28648 </indexterm>
28649
28650 <para>
28651 The functions shown in <xref
28652 linkend="functions-admin-signal-table"/> send control signals to
28653 other server processes. Use of these functions is restricted to
28654 superusers by default but access may be granted to others using
28655 <command>GRANT</command>, with noted exceptions.
28656 </para>
28657
28658 <para>
28659 Each of these functions returns <literal>true</literal> if
28660 the signal was successfully sent and <literal>false</literal>
28661 if sending the signal failed.
28662 </para>
28663
28664 <table id="functions-admin-signal-table">
28665 <title>Server Signaling Functions</title>
28666 <tgroup cols="1">
28667 <thead>
28668 <row>
28669 <entry role="func_table_entry"><para role="func_signature">
28670 Function
28671 </para>
28672 <para>
28673 Description
28674 </para></entry>
28675 </row>
28676 </thead>
28677
28678 <tbody>
28679 <row>
28680 <entry role="func_table_entry"><para role="func_signature">
28681 <indexterm>
28682 <primary>pg_cancel_backend</primary>
28683 </indexterm>
28684 <function>pg_cancel_backend</function> ( <parameter>pid</parameter> <type>integer</type> )
28685 <returnvalue>boolean</returnvalue>
28686 </para>
28687 <para>
28688 Cancels the current query of the session whose backend process has the
28689 specified process ID. This is also allowed if the
28690 calling role is a member of the role whose backend is being canceled or
28691 the calling role has privileges of <literal>pg_signal_backend</literal>,
28692 however only superusers can cancel superuser backends.
28693 As an exception, roles with privileges of
28694 <literal>pg_signal_autovacuum_worker</literal> are permitted to
28695 cancel autovacuum worker processes, which are otherwise considered
28696 superuser backends.
28697 </para></entry>
28698 </row>
28699
28700 <row>
28701 <entry role="func_table_entry"><para role="func_signature">
28702 <indexterm>
28703 <primary>pg_log_backend_memory_contexts</primary>
28704 </indexterm>
28705 <function>pg_log_backend_memory_contexts</function> ( <parameter>pid</parameter> <type>integer</type> )
28706 <returnvalue>boolean</returnvalue>
28707 </para>
28708 <para>
28709 Requests to log the memory contexts of the backend with the
28710 specified process ID. This function can send the request to
28711 backends and auxiliary processes except logger. These memory contexts
28712 will be logged at
28713 <literal>LOG</literal> message level. They will appear in
28714 the server log based on the log configuration set
28715 (see <xref linkend="runtime-config-logging"/> for more information),
28716 but will not be sent to the client regardless of
28717 <xref linkend="guc-client-min-messages"/>.
28718 </para></entry>
28719 </row>
28720
28721 <row>
28722 <entry role="func_table_entry"><para role="func_signature">
28723 <indexterm>
28724 <primary>pg_reload_conf</primary>
28725 </indexterm>
28726 <function>pg_reload_conf</function> ()
28727 <returnvalue>boolean</returnvalue>
28728 </para>
28729 <para>
28730 Causes all processes of the <productname>PostgreSQL</productname>
28731 server to reload their configuration files. (This is initiated by
28732 sending a <systemitem>SIGHUP</systemitem> signal to the postmaster
28733 process, which in turn sends <systemitem>SIGHUP</systemitem> to each
28734 of its children.) You can use the
28735 <link linkend="view-pg-file-settings"><structname>pg_file_settings</structname></link>,
28736 <link linkend="view-pg-hba-file-rules"><structname>pg_hba_file_rules</structname></link> and
28737 <link linkend="view-pg-ident-file-mappings"><structname>pg_ident_file_mappings</structname></link> views
28738 to check the configuration files for possible errors, before reloading.
28739 </para></entry>
28740 </row>
28741
28742 <row>
28743 <entry role="func_table_entry"><para role="func_signature">
28744 <indexterm>
28745 <primary>pg_rotate_logfile</primary>
28746 </indexterm>
28747 <function>pg_rotate_logfile</function> ()
28748 <returnvalue>boolean</returnvalue>
28749 </para>
28750 <para>
28751 Signals the log-file manager to switch to a new output file
28752 immediately. This works only when the built-in log collector is
28753 running, since otherwise there is no log-file manager subprocess.
28754 </para></entry>
28755 </row>
28756
28757 <row>
28758 <entry role="func_table_entry"><para role="func_signature">
28759 <indexterm>
28760 <primary>pg_terminate_backend</primary>
28761 </indexterm>
28762 <function>pg_terminate_backend</function> ( <parameter>pid</parameter> <type>integer</type>, <parameter>timeout</parameter> <type>bigint</type> <literal>DEFAULT</literal> <literal>0</literal> )
28763 <returnvalue>boolean</returnvalue>
28764 </para>
28765 <para>
28766 Terminates the session whose backend process has the
28767 specified process ID. This is also allowed if the calling role
28768 is a member of the role whose backend is being terminated or the
28769 calling role has privileges of <literal>pg_signal_backend</literal>,
28770 however only superusers can terminate superuser backends.
28771 As an exception, roles with privileges of
28772 <literal>pg_signal_autovacuum_worker</literal> are permitted to
28773 terminate autovacuum worker processes, which are otherwise considered
28774 superuser backends.
28775 </para>
28776 <para>
28777 If <parameter>timeout</parameter> is not specified or zero, this
28778 function returns <literal>true</literal> whether the process actually
28779 terminates or not, indicating only that the sending of the signal was
28780 successful. If the <parameter>timeout</parameter> is specified (in
28781 milliseconds) and greater than zero, the function waits until the
28782 process is actually terminated or until the given time has passed. If
28783 the process is terminated, the function
28784 returns <literal>true</literal>. On timeout, a warning is emitted and
28785 <literal>false</literal> is returned.
28786 </para></entry>
28787 </row>
28788 </tbody>
28789 </tgroup>
28790 </table>
28791
28792 <para>
28793 <function>pg_cancel_backend</function> and <function>pg_terminate_backend</function>
28794 send signals (<systemitem>SIGINT</systemitem> or <systemitem>SIGTERM</systemitem>
28795 respectively) to backend processes identified by process ID.
28796 The process ID of an active backend can be found from
28797 the <structfield>pid</structfield> column of the
28798 <structname>pg_stat_activity</structname> view, or by listing the
28799 <command>postgres</command> processes on the server (using
28800 <application>ps</application> on Unix or the <application>Task
28801 Manager</application> on <productname>Windows</productname>).
28802 The role of an active backend can be found from the
28803 <structfield>usename</structfield> column of the
28804 <structname>pg_stat_activity</structname> view.
28805 </para>
28806
28807 <para>
28808 <function>pg_log_backend_memory_contexts</function> can be used
28809 to log the memory contexts of a backend process. For example:
28810 <programlisting>
28811 postgres=# SELECT pg_log_backend_memory_contexts(pg_backend_pid());
28812 pg_log_backend_memory_contexts
28813 --------------------------------
28814 t
28815 (1 row)
28816 </programlisting>
28817 One message for each memory context will be logged. For example:
28818 <screen>
28819 LOG: logging memory contexts of PID 10377
28820 STATEMENT: SELECT pg_log_backend_memory_contexts(pg_backend_pid());
28821 LOG: level: 1; TopMemoryContext: 80800 total in 6 blocks; 14432 free (5 chunks); 66368 used
28822 LOG: level: 2; pgstat TabStatusArray lookup hash table: 8192 total in 1 blocks; 1408 free (0 chunks); 6784 used
28823 LOG: level: 2; TopTransactionContext: 8192 total in 1 blocks; 7720 free (1 chunks); 472 used
28824 LOG: level: 2; RowDescriptionContext: 8192 total in 1 blocks; 6880 free (0 chunks); 1312 used
28825 LOG: level: 2; MessageContext: 16384 total in 2 blocks; 5152 free (0 chunks); 11232 used
28826 LOG: level: 2; Operator class cache: 8192 total in 1 blocks; 512 free (0 chunks); 7680 used
28827 LOG: level: 2; smgr relation table: 16384 total in 2 blocks; 4544 free (3 chunks); 11840 used
28828 LOG: level: 2; TransactionAbortContext: 32768 total in 1 blocks; 32504 free (0 chunks); 264 used
28829 ...
28830 LOG: level: 2; ErrorContext: 8192 total in 1 blocks; 7928 free (3 chunks); 264 used
28831 LOG: Grand total: 1651920 bytes in 201 blocks; 622360 free (88 chunks); 1029560 used
28832 </screen>
28833 If there are more than 100 child contexts under the same parent, the first
28834 100 child contexts are logged, along with a summary of the remaining contexts.
28835 Note that frequent calls to this function could incur significant overhead,
28836 because it may generate a large number of log messages.
28837 </para>
28838
28839 </sect2>
28840
28841 <sect2 id="functions-admin-backup">
28842 <title>Backup Control Functions</title>
28843
28844 <indexterm>
28845 <primary>backup</primary>
28846 </indexterm>
28847
28848 <para>
28849 The functions shown in <xref
28850 linkend="functions-admin-backup-table"/> assist in making on-line backups.
28851 These functions cannot be executed during recovery (except
28852 <function>pg_backup_start</function>,
28853 <function>pg_backup_stop</function>,
28854 and <function>pg_wal_lsn_diff</function>).
28855 </para>
28856
28857 <para>
28858 For details about proper usage of these functions, see
28859 <xref linkend="continuous-archiving"/>.
28860 </para>
28861
28862 <table id="functions-admin-backup-table">
28863 <title>Backup Control Functions</title>
28864 <tgroup cols="1">
28865 <thead>
28866 <row>
28867 <entry role="func_table_entry"><para role="func_signature">
28868 Function
28869 </para>
28870 <para>
28871 Description
28872 </para></entry>
28873 </row>
28874 </thead>
28875
28876 <tbody>
28877 <row>
28878 <entry role="func_table_entry"><para role="func_signature">
28879 <indexterm>
28880 <primary>pg_create_restore_point</primary>
28881 </indexterm>
28882 <function>pg_create_restore_point</function> ( <parameter>name</parameter> <type>text</type> )
28883 <returnvalue>pg_lsn</returnvalue>
28884 </para>
28885 <para>
28886 Creates a named marker record in the write-ahead log that can later be
28887 used as a recovery target, and returns the corresponding write-ahead
28888 log location. The given name can then be used with
28889 <xref linkend="guc-recovery-target-name"/> to specify the point up to
28890 which recovery will proceed. Avoid creating multiple restore points
28891 with the same name, since recovery will stop at the first one whose
28892 name matches the recovery target.
28893 </para>
28894 <para>
28895 This function is restricted to superusers by default, but other users
28896 can be granted EXECUTE to run the function.
28897 </para></entry>
28898 </row>
28899
28900 <row>
28901 <entry role="func_table_entry"><para role="func_signature">
28902 <indexterm>
28903 <primary>pg_current_wal_flush_lsn</primary>
28904 </indexterm>
28905 <function>pg_current_wal_flush_lsn</function> ()
28906 <returnvalue>pg_lsn</returnvalue>
28907 </para>
28908 <para>
28909 Returns the current write-ahead log flush location (see notes below).
28910 </para></entry>
28911 </row>
28912
28913 <row>
28914 <entry role="func_table_entry"><para role="func_signature">
28915 <indexterm>
28916 <primary>pg_current_wal_insert_lsn</primary>
28917 </indexterm>
28918 <function>pg_current_wal_insert_lsn</function> ()
28919 <returnvalue>pg_lsn</returnvalue>
28920 </para>
28921 <para>
28922 Returns the current write-ahead log insert location (see notes below).
28923 </para></entry>
28924 </row>
28925
28926 <row>
28927 <entry role="func_table_entry"><para role="func_signature">
28928 <indexterm>
28929 <primary>pg_current_wal_lsn</primary>
28930 </indexterm>
28931 <function>pg_current_wal_lsn</function> ()
28932 <returnvalue>pg_lsn</returnvalue>
28933 </para>
28934 <para>
28935 Returns the current write-ahead log write location (see notes below).
28936 </para></entry>
28937 </row>
28938
28939 <row>
28940 <entry role="func_table_entry"><para role="func_signature">
28941 <indexterm>
28942 <primary>pg_backup_start</primary>
28943 </indexterm>
28944 <function>pg_backup_start</function> (
28945 <parameter>label</parameter> <type>text</type>
28946 <optional>, <parameter>fast</parameter> <type>boolean</type>
28947 </optional> )
28948 <returnvalue>pg_lsn</returnvalue>
28949 </para>
28950 <para>
28951 Prepares the server to begin an on-line backup. The only required
28952 parameter is an arbitrary user-defined label for the backup.
28953 (Typically this would be the name under which the backup dump file
28954 will be stored.)
28955 If the optional second parameter is given as <literal>true</literal>,
28956 it specifies executing <function>pg_backup_start</function> as quickly
28957 as possible. This forces an immediate checkpoint which will cause a
28958 spike in I/O operations, slowing any concurrently executing queries.
28959 </para>
28960 <para>
28961 This function is restricted to superusers by default, but other users
28962 can be granted EXECUTE to run the function.
28963 </para></entry>
28964 </row>
28965
28966 <row>
28967 <entry role="func_table_entry"><para role="func_signature">
28968 <indexterm>
28969 <primary>pg_backup_stop</primary>
28970 </indexterm>
28971 <function>pg_backup_stop</function> (
28972 <optional><parameter>wait_for_archive</parameter> <type>boolean</type>
28973 </optional> )
28974 <returnvalue>record</returnvalue>
28975 ( <parameter>lsn</parameter> <type>pg_lsn</type>,
28976 <parameter>labelfile</parameter> <type>text</type>,
28977 <parameter>spcmapfile</parameter> <type>text</type> )
28978 </para>
28979 <para>
28980 Finishes performing an on-line backup. The desired contents of the
28981 backup label file and the tablespace map file are returned as part of
28982 the result of the function and must be written to files in the
28983 backup area. These files must not be written to the live data directory
28984 (doing so will cause PostgreSQL to fail to restart in the event of a
28985 crash).
28986 </para>
28987 <para>
28988 There is an optional parameter of type <type>boolean</type>.
28989 If false, the function will return immediately after the backup is
28990 completed, without waiting for WAL to be archived. This behavior is
28991 only useful with backup software that independently monitors WAL
28992 archiving. Otherwise, WAL required to make the backup consistent might
28993 be missing and make the backup useless. By default or when this
28994 parameter is true, <function>pg_backup_stop</function> will wait for
28995 WAL to be archived when archiving is enabled. (On a standby, this
28996 means that it will wait only when <varname>archive_mode</varname> =
28997 <literal>always</literal>. If write activity on the primary is low,
28998 it may be useful to run <function>pg_switch_wal</function> on the
28999 primary in order to trigger an immediate segment switch.)
29000 </para>
29001 <para>
29002 When executed on a primary, this function also creates a backup
29003 history file in the write-ahead log archive area. The history file
29004 includes the label given to <function>pg_backup_start</function>, the
29005 starting and ending write-ahead log locations for the backup, and the
29006 starting and ending times of the backup. After recording the ending
29007 location, the current write-ahead log insertion point is automatically
29008 advanced to the next write-ahead log file, so that the ending
29009 write-ahead log file can be archived immediately to complete the
29010 backup.
29011 </para>
29012 <para>
29013 The result of the function is a single record.
29014 The <parameter>lsn</parameter> column holds the backup's ending
29015 write-ahead log location (which again can be ignored). The second
29016 column returns the contents of the backup label file, and the third
29017 column returns the contents of the tablespace map file. These must be
29018 stored as part of the backup and are required as part of the restore
29019 process.
29020 </para>
29021 <para>
29022 This function is restricted to superusers by default, but other users
29023 can be granted EXECUTE to run the function.
29024 </para></entry>
29025 </row>
29026
29027 <row>
29028 <entry role="func_table_entry"><para role="func_signature">
29029 <indexterm>
29030 <primary>pg_switch_wal</primary>
29031 </indexterm>
29032 <function>pg_switch_wal</function> ()
29033 <returnvalue>pg_lsn</returnvalue>
29034 </para>
29035 <para>
29036 Forces the server to switch to a new write-ahead log file, which
29037 allows the current file to be archived (assuming you are using
29038 continuous archiving). The result is the ending write-ahead log
29039 location plus 1 within the just-completed write-ahead log file. If
29040 there has been no write-ahead log activity since the last write-ahead
29041 log switch, <function>pg_switch_wal</function> does nothing and
29042 returns the start location of the write-ahead log file currently in
29043 use.
29044 </para>
29045 <para>
29046 This function is restricted to superusers by default, but other users
29047 can be granted EXECUTE to run the function.
29048 </para></entry>
29049 </row>
29050
29051 <row>
29052 <entry role="func_table_entry"><para role="func_signature">
29053 <indexterm>
29054 <primary>pg_walfile_name</primary>
29055 </indexterm>
29056 <function>pg_walfile_name</function> ( <parameter>lsn</parameter> <type>pg_lsn</type> )
29057 <returnvalue>text</returnvalue>
29058 </para>
29059 <para>
29060 Converts a write-ahead log location to the name of the WAL file
29061 holding that location.
29062 </para></entry>
29063 </row>
29064
29065 <row>
29066 <entry role="func_table_entry"><para role="func_signature">
29067 <indexterm>
29068 <primary>pg_walfile_name_offset</primary>
29069 </indexterm>
29070 <function>pg_walfile_name_offset</function> ( <parameter>lsn</parameter> <type>pg_lsn</type> )
29071 <returnvalue>record</returnvalue>
29072 ( <parameter>file_name</parameter> <type>text</type>,
29073 <parameter>file_offset</parameter> <type>integer</type> )
29074 </para>
29075 <para>
29076 Converts a write-ahead log location to a WAL file name and byte offset
29077 within that file.
29078 </para></entry>
29079 </row>
29080
29081 <row>
29082 <entry role="func_table_entry"><para role="func_signature">
29083 <indexterm>
29084 <primary>pg_split_walfile_name</primary>
29085 </indexterm>
29086 <function>pg_split_walfile_name</function> ( <parameter>file_name</parameter> <type>text</type> )
29087 <returnvalue>record</returnvalue>
29088 ( <parameter>segment_number</parameter> <type>numeric</type>,
29089 <parameter>timeline_id</parameter> <type>bigint</type> )
29090 </para>
29091 <para>
29092 Extracts the sequence number and timeline ID from a WAL file
29093 name.
29094 </para></entry>
29095 </row>
29096
29097 <row>
29098 <entry role="func_table_entry"><para role="func_signature">
29099 <indexterm>
29100 <primary>pg_wal_lsn_diff</primary>
29101 </indexterm>
29102 <function>pg_wal_lsn_diff</function> ( <parameter>lsn1</parameter> <type>pg_lsn</type>, <parameter>lsn2</parameter> <type>pg_lsn</type> )
29103 <returnvalue>numeric</returnvalue>
29104 </para>
29105 <para>
29106 Calculates the difference in bytes (<parameter>lsn1</parameter> - <parameter>lsn2</parameter>) between two write-ahead log
29107 locations. This can be used
29108 with <structname>pg_stat_replication</structname> or some of the
29109 functions shown in <xref linkend="functions-admin-backup-table"/> to
29110 get the replication lag.
29111 </para></entry>
29112 </row>
29113 </tbody>
29114 </tgroup>
29115 </table>
29116
29117 <para>
29118 <function>pg_current_wal_lsn</function> displays the current write-ahead
29119 log write location in the same format used by the above functions.
29120 Similarly, <function>pg_current_wal_insert_lsn</function> displays the
29121 current write-ahead log insertion location
29122 and <function>pg_current_wal_flush_lsn</function> displays the current
29123 write-ahead log flush location. The insertion location is
29124 the <quote>logical</quote> end of the write-ahead log at any instant,
29125 while the write location is the end of what has actually been written out
29126 from the server's internal buffers, and the flush location is the last
29127 location known to be written to durable storage. The write location is the
29128 end of what can be examined from outside the server, and is usually what
29129 you want if you are interested in archiving partially-complete write-ahead
29130 log files. The insertion and flush locations are made available primarily
29131 for server debugging purposes. These are all read-only operations and do
29132 not require superuser permissions.
29133 </para>
29134
29135 <para>
29136 You can use <function>pg_walfile_name_offset</function> to extract the
29137 corresponding write-ahead log file name and byte offset from
29138 a <type>pg_lsn</type> value. For example:
29139 <programlisting>
29140 postgres=# SELECT * FROM pg_walfile_name_offset((pg_backup_stop()).lsn);
29141 file_name | file_offset
29142 --------------------------+-------------
29143 00000001000000000000000D | 4039624
29144 (1 row)
29145 </programlisting>
29146 Similarly, <function>pg_walfile_name</function> extracts just the write-ahead log file name.
29147 </para>
29148
29149 <para>
29150 <function>pg_split_walfile_name</function> is useful to compute a
29151 <acronym>LSN</acronym> from a file offset and WAL file name, for example:
29152 <programlisting>
29153 postgres=# \set file_name '000000010000000100C000AB'
29154 postgres=# \set offset 256
29155 postgres=# SELECT '0/0'::pg_lsn + pd.segment_number * ps.setting::int + :offset AS lsn
29156 FROM pg_split_walfile_name(:'file_name') pd,
29157 pg_show_all_settings() ps
29158 WHERE ps.name = 'wal_segment_size';
29159 lsn
29160 ---------------
29161 C001/AB000100
29162 (1 row)
29163 </programlisting>
29164 </para>
29165
29166 </sect2>
29167
29168 <sect2 id="functions-recovery-control">
29169 <title>Recovery Control Functions</title>
29170
29171 <para>
29172 The functions shown in <xref
29173 linkend="functions-recovery-info-table"/> provide information
29174 about the current status of a standby server.
29175 These functions may be executed both during recovery and in normal running.
29176 </para>
29177
29178 <table id="functions-recovery-info-table">
29179 <title>Recovery Information Functions</title>
29180 <tgroup cols="1">
29181 <thead>
29182 <row>
29183 <entry role="func_table_entry"><para role="func_signature">
29184 Function
29185 </para>
29186 <para>
29187 Description
29188 </para></entry>
29189 </row>
29190 </thead>
29191
29192 <tbody>
29193 <row>
29194 <entry role="func_table_entry"><para role="func_signature">
29195 <indexterm>
29196 <primary>pg_is_in_recovery</primary>
29197 </indexterm>
29198 <function>pg_is_in_recovery</function> ()
29199 <returnvalue>boolean</returnvalue>
29200 </para>
29201 <para>
29202 Returns true if recovery is still in progress.
29203 </para></entry>
29204 </row>
29205
29206 <row>
29207 <entry role="func_table_entry"><para role="func_signature">
29208 <indexterm>
29209 <primary>pg_last_wal_receive_lsn</primary>
29210 </indexterm>
29211 <function>pg_last_wal_receive_lsn</function> ()
29212 <returnvalue>pg_lsn</returnvalue>
29213 </para>
29214 <para>
29215 Returns the last write-ahead log location that has been received and
29216 synced to disk by streaming replication. While streaming replication
29217 is in progress this will increase monotonically. If recovery has
29218 completed then this will remain static at the location of the last WAL
29219 record received and synced to disk during recovery. If streaming
29220 replication is disabled, or if it has not yet started, the function
29221 returns <literal>NULL</literal>.
29222 </para></entry>
29223 </row>
29224
29225 <row>
29226 <entry role="func_table_entry"><para role="func_signature">
29227 <indexterm>
29228 <primary>pg_last_wal_replay_lsn</primary>
29229 </indexterm>
29230 <function>pg_last_wal_replay_lsn</function> ()
29231 <returnvalue>pg_lsn</returnvalue>
29232 </para>
29233 <para>
29234 Returns the last write-ahead log location that has been replayed
29235 during recovery. If recovery is still in progress this will increase
29236 monotonically. If recovery has completed then this will remain
29237 static at the location of the last WAL record applied during recovery.
29238 When the server has been started normally without recovery, the
29239 function returns <literal>NULL</literal>.
29240 </para></entry>
29241 </row>
29242
29243 <row>
29244 <entry role="func_table_entry"><para role="func_signature">
29245 <indexterm>
29246 <primary>pg_last_xact_replay_timestamp</primary>
29247 </indexterm>
29248 <function>pg_last_xact_replay_timestamp</function> ()
29249 <returnvalue>timestamp with time zone</returnvalue>
29250 </para>
29251 <para>
29252 Returns the time stamp of the last transaction replayed during
29253 recovery. This is the time at which the commit or abort WAL record
29254 for that transaction was generated on the primary. If no transactions
29255 have been replayed during recovery, the function
29256 returns <literal>NULL</literal>. Otherwise, if recovery is still in
29257 progress this will increase monotonically. If recovery has completed
29258 then this will remain static at the time of the last transaction
29259 applied during recovery. When the server has been started normally
29260 without recovery, the function returns <literal>NULL</literal>.
29261 </para></entry>
29262 </row>
29263
29264 <row>
29265 <entry role="func_table_entry"><para role="func_signature">
29266 <indexterm>
29267 <primary>pg_get_wal_resource_managers</primary>
29268 </indexterm>
29269 <function>pg_get_wal_resource_managers</function> ()
29270 <returnvalue>setof record</returnvalue>
29271 ( <parameter>rm_id</parameter> <type>integer</type>,
29272 <parameter>rm_name</parameter> <type>text</type>,
29273 <parameter>rm_builtin</parameter> <type>boolean</type> )
29274 </para>
29275 <para>
29276 Returns the currently-loaded WAL resource managers in the system. The
29277 column <parameter>rm_builtin</parameter> indicates whether it's a
29278 built-in resource manager, or a custom resource manager loaded by an
29279 extension.
29280 </para></entry>
29281 </row>
29282 </tbody>
29283 </tgroup>
29284 </table>
29285
29286 <para>
29287 The functions shown in <xref
29288 linkend="functions-recovery-control-table"/> control the progress of recovery.
29289 These functions may be executed only during recovery.
29290 </para>
29291
29292 <table id="functions-recovery-control-table">
29293 <title>Recovery Control Functions</title>
29294 <tgroup cols="1">
29295 <thead>
29296 <row>
29297 <entry role="func_table_entry"><para role="func_signature">
29298 Function
29299 </para>
29300 <para>
29301 Description
29302 </para></entry>
29303 </row>
29304 </thead>
29305
29306 <tbody>
29307 <row>
29308 <entry role="func_table_entry"><para role="func_signature">
29309 <indexterm>
29310 <primary>pg_is_wal_replay_paused</primary>
29311 </indexterm>
29312 <function>pg_is_wal_replay_paused</function> ()
29313 <returnvalue>boolean</returnvalue>
29314 </para>
29315 <para>
29316 Returns true if recovery pause is requested.
29317 </para></entry>
29318 </row>
29319
29320 <row>
29321 <entry role="func_table_entry"><para role="func_signature">
29322 <indexterm>
29323 <primary>pg_get_wal_replay_pause_state</primary>
29324 </indexterm>
29325 <function>pg_get_wal_replay_pause_state</function> ()
29326 <returnvalue>text</returnvalue>
29327 </para>
29328 <para>
29329 Returns recovery pause state. The return values are <literal>
29330 not paused</literal> if pause is not requested, <literal>
29331 pause requested</literal> if pause is requested but recovery is
29332 not yet paused, and <literal>paused</literal> if the recovery is
29333 actually paused.
29334 </para></entry>
29335 </row>
29336
29337 <row>
29338 <entry role="func_table_entry"><para role="func_signature">
29339 <indexterm>
29340 <primary>pg_promote</primary>
29341 </indexterm>
29342 <function>pg_promote</function> ( <parameter>wait</parameter> <type>boolean</type> <literal>DEFAULT</literal> <literal>true</literal>, <parameter>wait_seconds</parameter> <type>integer</type> <literal>DEFAULT</literal> <literal>60</literal> )
29343 <returnvalue>boolean</returnvalue>
29344 </para>
29345 <para>
29346 Promotes a standby server to primary status.
29347 With <parameter>wait</parameter> set to <literal>true</literal> (the
29348 default), the function waits until promotion is completed
29349 or <parameter>wait_seconds</parameter> seconds have passed, and
29350 returns <literal>true</literal> if promotion is successful
29351 and <literal>false</literal> otherwise.
29352 If <parameter>wait</parameter> is set to <literal>false</literal>, the
29353 function returns <literal>true</literal> immediately after sending a
29354 <literal>SIGUSR1</literal> signal to the postmaster to trigger
29355 promotion.
29356 </para>
29357 <para>
29358 This function is restricted to superusers by default, but other users
29359 can be granted EXECUTE to run the function.
29360 </para></entry>
29361 </row>
29362
29363 <row>
29364 <entry role="func_table_entry"><para role="func_signature">
29365 <indexterm>
29366 <primary>pg_wal_replay_pause</primary>
29367 </indexterm>
29368 <function>pg_wal_replay_pause</function> ()
29369 <returnvalue>void</returnvalue>
29370 </para>
29371 <para>
29372 Request to pause recovery. A request doesn't mean that recovery stops
29373 right away. If you want a guarantee that recovery is actually paused,
29374 you need to check for the recovery pause state returned by
29375 <function>pg_get_wal_replay_pause_state()</function>. Note that
29376 <function>pg_is_wal_replay_paused()</function> returns whether a request
29377 is made. While recovery is paused, no further database changes are applied.
29378 If hot standby is active, all new queries will see the same consistent
29379 snapshot of the database, and no further query conflicts will be generated
29380 until recovery is resumed.
29381 </para>
29382 <para>
29383 This function is restricted to superusers by default, but other users
29384 can be granted EXECUTE to run the function.
29385 </para></entry>
29386 </row>
29387
29388 <row>
29389 <entry role="func_table_entry"><para role="func_signature">
29390 <indexterm>
29391 <primary>pg_wal_replay_resume</primary>
29392 </indexterm>
29393 <function>pg_wal_replay_resume</function> ()
29394 <returnvalue>void</returnvalue>
29395 </para>
29396 <para>
29397 Restarts recovery if it was paused.
29398 </para>
29399 <para>
29400 This function is restricted to superusers by default, but other users
29401 can be granted EXECUTE to run the function.
29402 </para></entry>
29403 </row>
29404 </tbody>
29405 </tgroup>
29406 </table>
29407
29408 <para>
29409 <function>pg_wal_replay_pause</function> and
29410 <function>pg_wal_replay_resume</function> cannot be executed while
29411 a promotion is ongoing. If a promotion is triggered while recovery
29412 is paused, the paused state ends and promotion continues.
29413 </para>
29414
29415 <para>
29416 If streaming replication is disabled, the paused state may continue
29417 indefinitely without a problem. If streaming replication is in
29418 progress then WAL records will continue to be received, which will
29419 eventually fill available disk space, depending upon the duration of
29420 the pause, the rate of WAL generation and available disk space.
29421 </para>
29422
29423 </sect2>
29424
29425 <sect2 id="functions-snapshot-synchronization">
29426 <title>Snapshot Synchronization Functions</title>
29427
29428 <para>
29429 <productname>PostgreSQL</productname> allows database sessions to synchronize their
29430 snapshots. A <firstterm>snapshot</firstterm> determines which data is visible to the
29431 transaction that is using the snapshot. Synchronized snapshots are
29432 necessary when two or more sessions need to see identical content in the
29433 database. If two sessions just start their transactions independently,
29434 there is always a possibility that some third transaction commits
29435 between the executions of the two <command>START TRANSACTION</command> commands,
29436 so that one session sees the effects of that transaction and the other
29437 does not.
29438 </para>
29439
29440 <para>
29441 To solve this problem, <productname>PostgreSQL</productname> allows a transaction to
29442 <firstterm>export</firstterm> the snapshot it is using. As long as the exporting
29443 transaction remains open, other transactions can <firstterm>import</firstterm> its
29444 snapshot, and thereby be guaranteed that they see exactly the same view
29445 of the database that the first transaction sees. But note that any
29446 database changes made by any one of these transactions remain invisible
29447 to the other transactions, as is usual for changes made by uncommitted
29448 transactions. So the transactions are synchronized with respect to
29449 pre-existing data, but act normally for changes they make themselves.
29450 </para>
29451
29452 <para>
29453 Snapshots are exported with the <function>pg_export_snapshot</function> function,
29454 shown in <xref linkend="functions-snapshot-synchronization-table"/>, and
29455 imported with the <xref linkend="sql-set-transaction"/> command.
29456 </para>
29457
29458 <table id="functions-snapshot-synchronization-table">
29459 <title>Snapshot Synchronization Functions</title>
29460 <tgroup cols="1">
29461 <thead>
29462 <row>
29463 <entry role="func_table_entry"><para role="func_signature">
29464 Function
29465 </para>
29466 <para>
29467 Description
29468 </para></entry>
29469 </row>
29470 </thead>
29471
29472 <tbody>
29473 <row>
29474 <entry role="func_table_entry"><para role="func_signature">
29475 <indexterm>
29476 <primary>pg_export_snapshot</primary>
29477 </indexterm>
29478 <function>pg_export_snapshot</function> ()
29479 <returnvalue>text</returnvalue>
29480 </para>
29481 <para>
29482 Saves the transaction's current snapshot and returns
29483 a <type>text</type> string identifying the snapshot. This string must
29484 be passed (outside the database) to clients that want to import the
29485 snapshot. The snapshot is available for import only until the end of
29486 the transaction that exported it.
29487 </para>
29488 <para>
29489 A transaction can export more than one snapshot, if needed. Note that
29490 doing so is only useful in <literal>READ COMMITTED</literal>
29491 transactions, since in <literal>REPEATABLE READ</literal> and higher
29492 isolation levels, transactions use the same snapshot throughout their
29493 lifetime. Once a transaction has exported any snapshots, it cannot be
29494 prepared with <xref linkend="sql-prepare-transaction"/>.
29495 </para></entry>
29496 </row>
29497 <row>
29498 <entry role="func_table_entry"><para role="func_signature">
29499 <indexterm>
29500 <primary>pg_log_standby_snapshot</primary>
29501 </indexterm>
29502 <function>pg_log_standby_snapshot</function> ()
29503 <returnvalue>pg_lsn</returnvalue>
29504 </para>
29505 <para>
29506 Take a snapshot of running transactions and write it to WAL, without
29507 having to wait for bgwriter or checkpointer to log one. This is useful
29508 for logical decoding on standby, as logical slot creation has to wait
29509 until such a record is replayed on the standby.
29510 </para></entry>
29511 </row>
29512 </tbody>
29513 </tgroup>
29514 </table>
29515
29516 </sect2>
29517
29518 <sect2 id="functions-replication">
29519 <title>Replication Management Functions</title>
29520
29521 <para>
29522 The functions shown
29523 in <xref linkend="functions-replication-table"/> are for
29524 controlling and interacting with replication features.
29525 See <xref linkend="streaming-replication"/>,
29526 <xref linkend="streaming-replication-slots"/>, and
29527 <xref linkend="replication-origins"/>
29528 for information about the underlying features.
29529 Use of functions for replication origin is only allowed to the
29530 superuser by default, but may be allowed to other users by using the
29531 <literal>GRANT</literal> command.
29532 Use of functions for replication slots is restricted to superusers
29533 and users having <literal>REPLICATION</literal> privilege.
29534 </para>
29535
29536 <para>
29537 Many of these functions have equivalent commands in the replication
29538 protocol; see <xref linkend="protocol-replication"/>.
29539 </para>
29540
29541 <para>
29542 The functions described in
29543 <xref linkend="functions-admin-backup"/>,
29544 <xref linkend="functions-recovery-control"/>, and
29545 <xref linkend="functions-snapshot-synchronization"/>
29546 are also relevant for replication.
29547 </para>
29548
29549 <table id="functions-replication-table">
29550 <title>Replication Management Functions</title>
29551 <tgroup cols="1">
29552 <thead>
29553 <row>
29554 <entry role="func_table_entry"><para role="func_signature">
29555 Function
29556 </para>
29557 <para>
29558 Description
29559 </para></entry>
29560 </row>
29561 </thead>
29562
29563 <tbody>
29564 <row>
29565 <entry role="func_table_entry"><para role="func_signature">
29566 <indexterm>
29567 <primary>pg_create_physical_replication_slot</primary>
29568 </indexterm>
29569 <function>pg_create_physical_replication_slot</function> ( <parameter>slot_name</parameter> <type>name</type> <optional>, <parameter>immediately_reserve</parameter> <type>boolean</type>, <parameter>temporary</parameter> <type>boolean</type> </optional> )
29570 <returnvalue>record</returnvalue>
29571 ( <parameter>slot_name</parameter> <type>name</type>,
29572 <parameter>lsn</parameter> <type>pg_lsn</type> )
29573 </para>
29574 <para>
29575 Creates a new physical replication slot named
29576 <parameter>slot_name</parameter>. The optional second parameter,
29577 when <literal>true</literal>, specifies that the <acronym>LSN</acronym> for this
29578 replication slot be reserved immediately; otherwise
29579 the <acronym>LSN</acronym> is reserved on first connection from a streaming
29580 replication client. Streaming changes from a physical slot is only
29581 possible with the streaming-replication protocol &mdash;
29582 see <xref linkend="protocol-replication"/>. The optional third
29583 parameter, <parameter>temporary</parameter>, when set to true, specifies that
29584 the slot should not be permanently stored to disk and is only meant
29585 for use by the current session. Temporary slots are also
29586 released upon any error. This function corresponds
29587 to the replication protocol command <literal>CREATE_REPLICATION_SLOT
29588 ... PHYSICAL</literal>.
29589 </para></entry>
29590 </row>
29591
29592 <row>
29593 <entry role="func_table_entry"><para role="func_signature">
29594 <indexterm>
29595 <primary>pg_drop_replication_slot</primary>
29596 </indexterm>
29597 <function>pg_drop_replication_slot</function> ( <parameter>slot_name</parameter> <type>name</type> )
29598 <returnvalue>void</returnvalue>
29599 </para>
29600 <para>
29601 Drops the physical or logical replication slot
29602 named <parameter>slot_name</parameter>. Same as replication protocol
29603 command <literal>DROP_REPLICATION_SLOT</literal>.
29604 </para></entry>
29605 </row>
29606
29607 <row>
29608 <entry id="pg-create-logical-replication-slot" role="func_table_entry"><para role="func_signature">
29609 <indexterm>
29610 <primary>pg_create_logical_replication_slot</primary>
29611 </indexterm>
29612 <function>pg_create_logical_replication_slot</function> ( <parameter>slot_name</parameter> <type>name</type>, <parameter>plugin</parameter> <type>name</type> <optional>, <parameter>temporary</parameter> <type>boolean</type>, <parameter>twophase</parameter> <type>boolean</type>, <parameter>failover</parameter> <type>boolean</type> </optional> )
29613 <returnvalue>record</returnvalue>
29614 ( <parameter>slot_name</parameter> <type>name</type>,
29615 <parameter>lsn</parameter> <type>pg_lsn</type> )
29616 </para>
29617 <para>
29618 Creates a new logical (decoding) replication slot named
29619 <parameter>slot_name</parameter> using the output plugin
29620 <parameter>plugin</parameter>. The optional third
29621 parameter, <parameter>temporary</parameter>, when set to true, specifies that
29622 the slot should not be permanently stored to disk and is only meant
29623 for use by the current session. Temporary slots are also
29624 released upon any error. The optional fourth parameter,
29625 <parameter>twophase</parameter>, when set to true, specifies
29626 that the decoding of prepared transactions is enabled for this
29627 slot. The optional fifth parameter,
29628 <parameter>failover</parameter>, when set to true,
29629 specifies that this slot is enabled to be synced to the
29630 standbys so that logical replication can be resumed after
29631 failover. A call to this function has the same effect as
29632 the replication protocol command
29633 <literal>CREATE_REPLICATION_SLOT ... LOGICAL</literal>.
29634 </para></entry>
29635 </row>
29636
29637 <row>
29638 <entry role="func_table_entry"><para role="func_signature">
29639 <indexterm>
29640 <primary>pg_copy_physical_replication_slot</primary>
29641 </indexterm>
29642 <function>pg_copy_physical_replication_slot</function> ( <parameter>src_slot_name</parameter> <type>name</type>, <parameter>dst_slot_name</parameter> <type>name</type> <optional>, <parameter>temporary</parameter> <type>boolean</type> </optional> )
29643 <returnvalue>record</returnvalue>
29644 ( <parameter>slot_name</parameter> <type>name</type>,
29645 <parameter>lsn</parameter> <type>pg_lsn</type> )
29646 </para>
29647 <para>
29648 Copies an existing physical replication slot named <parameter>src_slot_name</parameter>
29649 to a physical replication slot named <parameter>dst_slot_name</parameter>.
29650 The copied physical slot starts to reserve WAL from the same <acronym>LSN</acronym> as the
29651 source slot.
29652 <parameter>temporary</parameter> is optional. If <parameter>temporary</parameter>
29653 is omitted, the same value as the source slot is used. Copy of an
29654 invalidated slot is not allowed.
29655 </para></entry>
29656 </row>
29657
29658 <row>
29659 <entry role="func_table_entry"><para role="func_signature">
29660 <indexterm>
29661 <primary>pg_copy_logical_replication_slot</primary>
29662 </indexterm>
29663 <function>pg_copy_logical_replication_slot</function> ( <parameter>src_slot_name</parameter> <type>name</type>, <parameter>dst_slot_name</parameter> <type>name</type> <optional>, <parameter>temporary</parameter> <type>boolean</type> <optional>, <parameter>plugin</parameter> <type>name</type> </optional></optional> )
29664 <returnvalue>record</returnvalue>
29665 ( <parameter>slot_name</parameter> <type>name</type>,
29666 <parameter>lsn</parameter> <type>pg_lsn</type> )
29667 </para>
29668 <para>
29669 Copies an existing logical replication slot
29670 named <parameter>src_slot_name</parameter> to a logical replication
29671 slot named <parameter>dst_slot_name</parameter>, optionally changing
29672 the output plugin and persistence. The copied logical slot starts
29673 from the same <acronym>LSN</acronym> as the source logical slot. Both
29674 <parameter>temporary</parameter> and <parameter>plugin</parameter> are
29675 optional; if they are omitted, the values of the source slot are used.
29676 The <literal>failover</literal> option of the source logical slot
29677 is not copied and is set to <literal>false</literal> by default. This
29678 is to avoid the risk of being unable to continue logical replication
29679 after failover to standby where the slot is being synchronized. Copy of
29680 an invalidated slot is not allowed.
29681 </para></entry>
29682 </row>
29683
29684 <row>
29685 <entry id="pg-logical-slot-get-changes" role="func_table_entry"><para role="func_signature">
29686 <indexterm>
29687 <primary>pg_logical_slot_get_changes</primary>
29688 </indexterm>
29689 <function>pg_logical_slot_get_changes</function> ( <parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>integer</type>, <literal>VARIADIC</literal> <parameter>options</parameter> <type>text[]</type> )
29690 <returnvalue>setof record</returnvalue>
29691 ( <parameter>lsn</parameter> <type>pg_lsn</type>,
29692 <parameter>xid</parameter> <type>xid</type>,
29693 <parameter>data</parameter> <type>text</type> )
29694 </para>
29695 <para>
29696 Returns changes in the slot <parameter>slot_name</parameter>, starting
29697 from the point from which changes have been consumed last. If
29698 <parameter>upto_lsn</parameter>
29699 and <parameter>upto_nchanges</parameter> are NULL,
29700 logical decoding will continue until end of WAL. If
29701 <parameter>upto_lsn</parameter> is non-NULL, decoding will include only
29702 those transactions which commit prior to the specified LSN. If
29703 <parameter>upto_nchanges</parameter> is non-NULL, decoding will
29704 stop when the number of rows produced by decoding exceeds
29705 the specified value. Note, however, that the actual number of
29706 rows returned may be larger, since this limit is only checked after
29707 adding the rows produced when decoding each new transaction commit.
29708 If the specified slot is a logical failover slot then the function will
29709 not return until all physical slots specified in
29710 <link linkend="guc-synchronized-standby-slots"><varname>synchronized_standby_slots</varname></link>
29711 have confirmed WAL receipt.
29712 </para></entry>
29713 </row>
29714
29715 <row>
29716 <entry id="pg-logical-slot-peek-changes" role="func_table_entry"><para role="func_signature">
29717 <indexterm>
29718 <primary>pg_logical_slot_peek_changes</primary>
29719 </indexterm>
29720 <function>pg_logical_slot_peek_changes</function> ( <parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>integer</type>, <literal>VARIADIC</literal> <parameter>options</parameter> <type>text[]</type> )
29721 <returnvalue>setof record</returnvalue>
29722 ( <parameter>lsn</parameter> <type>pg_lsn</type>,
29723 <parameter>xid</parameter> <type>xid</type>,
29724 <parameter>data</parameter> <type>text</type> )
29725 </para>
29726 <para>
29727 Behaves just like
29728 the <function>pg_logical_slot_get_changes()</function> function,
29729 except that changes are not consumed; that is, they will be returned
29730 again on future calls.
29731 </para></entry>
29732 </row>
29733
29734 <row>
29735 <entry id="pg-logical-slot-get-binary-changes" role="func_table_entry"><para role="func_signature">
29736 <indexterm>
29737 <primary>pg_logical_slot_get_binary_changes</primary>
29738 </indexterm>
29739 <function>pg_logical_slot_get_binary_changes</function> ( <parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>integer</type>, <literal>VARIADIC</literal> <parameter>options</parameter> <type>text[]</type> )
29740 <returnvalue>setof record</returnvalue>
29741 ( <parameter>lsn</parameter> <type>pg_lsn</type>,
29742 <parameter>xid</parameter> <type>xid</type>,
29743 <parameter>data</parameter> <type>bytea</type> )
29744 </para>
29745 <para>
29746 Behaves just like
29747 the <function>pg_logical_slot_get_changes()</function> function,
29748 except that changes are returned as <type>bytea</type>.
29749 </para></entry>
29750 </row>
29751
29752 <row>
29753 <entry role="func_table_entry"><para role="func_signature">
29754 <indexterm>
29755 <primary>pg_logical_slot_peek_binary_changes</primary>
29756 </indexterm>
29757 <function>pg_logical_slot_peek_binary_changes</function> ( <parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type>, <parameter>upto_nchanges</parameter> <type>integer</type>, <literal>VARIADIC</literal> <parameter>options</parameter> <type>text[]</type> )
29758 <returnvalue>setof record</returnvalue>
29759 ( <parameter>lsn</parameter> <type>pg_lsn</type>,
29760 <parameter>xid</parameter> <type>xid</type>,
29761 <parameter>data</parameter> <type>bytea</type> )
29762 </para>
29763 <para>
29764 Behaves just like
29765 the <function>pg_logical_slot_peek_changes()</function> function,
29766 except that changes are returned as <type>bytea</type>.
29767 </para></entry>
29768 </row>
29769
29770 <row>
29771 <entry id="pg-replication-slot-advance" role="func_table_entry"><para role="func_signature">
29772 <indexterm>
29773 <primary>pg_replication_slot_advance</primary>
29774 </indexterm>
29775 <function>pg_replication_slot_advance</function> ( <parameter>slot_name</parameter> <type>name</type>, <parameter>upto_lsn</parameter> <type>pg_lsn</type> )
29776 <returnvalue>record</returnvalue>
29777 ( <parameter>slot_name</parameter> <type>name</type>,
29778 <parameter>end_lsn</parameter> <type>pg_lsn</type> )
29779 </para>
29780 <para>
29781 Advances the current confirmed position of a replication slot named
29782 <parameter>slot_name</parameter>. The slot will not be moved backwards,
29783 and it will not be moved beyond the current insert location. Returns
29784 the name of the slot and the actual position that it was advanced to.
29785 The updated slot position information is written out at the next
29786 checkpoint if any advancing is done. So in the event of a crash, the
29787 slot may return to an earlier position. If the specified slot is a
29788 logical failover slot then the function will not return until all
29789 physical slots specified in
29790 <link linkend="guc-synchronized-standby-slots"><varname>synchronized_standby_slots</varname></link>
29791 have confirmed WAL receipt.
29792 </para></entry>
29793 </row>
29794
29795 <row>
29796 <entry id="pg-replication-origin-create" role="func_table_entry"><para role="func_signature">
29797 <indexterm>
29798 <primary>pg_replication_origin_create</primary>
29799 </indexterm>
29800 <function>pg_replication_origin_create</function> ( <parameter>node_name</parameter> <type>text</type> )
29801 <returnvalue>oid</returnvalue>
29802 </para>
29803 <para>
29804 Creates a replication origin with the given external
29805 name, and returns the internal ID assigned to it.
29806 The name must be no longer than 512 bytes.
29807 </para></entry>
29808 </row>
29809
29810 <row>
29811 <entry id="pg-replication-origin-drop" role="func_table_entry"><para role="func_signature">
29812 <indexterm>
29813 <primary>pg_replication_origin_drop</primary>
29814 </indexterm>
29815 <function>pg_replication_origin_drop</function> ( <parameter>node_name</parameter> <type>text</type> )
29816 <returnvalue>void</returnvalue>
29817 </para>
29818 <para>
29819 Deletes a previously-created replication origin, including any
29820 associated replay progress.
29821 </para></entry>
29822 </row>
29823
29824 <row>
29825 <entry role="func_table_entry"><para role="func_signature">
29826 <indexterm>
29827 <primary>pg_replication_origin_oid</primary>
29828 </indexterm>
29829 <function>pg_replication_origin_oid</function> ( <parameter>node_name</parameter> <type>text</type> )
29830 <returnvalue>oid</returnvalue>
29831 </para>
29832 <para>
29833 Looks up a replication origin by name and returns the internal ID. If
29834 no such replication origin is found, <literal>NULL</literal> is
29835 returned.
29836 </para></entry>
29837 </row>
29838
29839 <row>
29840 <entry id="pg-replication-origin-session-setup" role="func_table_entry"><para role="func_signature">
29841 <indexterm>
29842 <primary>pg_replication_origin_session_setup</primary>
29843 </indexterm>
29844 <function>pg_replication_origin_session_setup</function> ( <parameter>node_name</parameter> <type>text</type> )
29845 <returnvalue>void</returnvalue>
29846 </para>
29847 <para>
29848 Marks the current session as replaying from the given
29849 origin, allowing replay progress to be tracked.
29850 Can only be used if no origin is currently selected.
29851 Use <function>pg_replication_origin_session_reset</function> to undo.
29852 </para></entry>
29853 </row>
29854
29855 <row>
29856 <entry role="func_table_entry"><para role="func_signature">
29857 <indexterm>
29858 <primary>pg_replication_origin_session_reset</primary>
29859 </indexterm>
29860 <function>pg_replication_origin_session_reset</function> ()
29861 <returnvalue>void</returnvalue>
29862 </para>
29863 <para>
29864 Cancels the effects
29865 of <function>pg_replication_origin_session_setup()</function>.
29866 </para></entry>
29867 </row>
29868
29869 <row>
29870 <entry role="func_table_entry"><para role="func_signature">
29871 <indexterm>
29872 <primary>pg_replication_origin_session_is_setup</primary>
29873 </indexterm>
29874 <function>pg_replication_origin_session_is_setup</function> ()
29875 <returnvalue>boolean</returnvalue>
29876 </para>
29877 <para>
29878 Returns true if a replication origin has been selected in the
29879 current session.
29880 </para></entry>
29881 </row>
29882
29883 <row>
29884 <entry id="pg-replication-origin-session-progress" role="func_table_entry"><para role="func_signature">
29885 <indexterm>
29886 <primary>pg_replication_origin_session_progress</primary>
29887 </indexterm>
29888 <function>pg_replication_origin_session_progress</function> ( <parameter>flush</parameter> <type>boolean</type> )
29889 <returnvalue>pg_lsn</returnvalue>
29890 </para>
29891 <para>
29892 Returns the replay location for the replication origin selected in
29893 the current session. The parameter <parameter>flush</parameter>
29894 determines whether the corresponding local transaction will be
29895 guaranteed to have been flushed to disk or not.
29896 </para></entry>
29897 </row>
29898
29899 <row>
29900 <entry id="pg-replication-origin-xact-setup" role="func_table_entry"><para role="func_signature">
29901 <indexterm>
29902 <primary>pg_replication_origin_xact_setup</primary>
29903 </indexterm>
29904 <function>pg_replication_origin_xact_setup</function> ( <parameter>origin_lsn</parameter> <type>pg_lsn</type>, <parameter>origin_timestamp</parameter> <type>timestamp with time zone</type> )
29905 <returnvalue>void</returnvalue>
29906 </para>
29907 <para>
29908 Marks the current transaction as replaying a transaction that has
29909 committed at the given <acronym>LSN</acronym> and timestamp. Can
29910 only be called when a replication origin has been selected
29911 using <function>pg_replication_origin_session_setup</function>.
29912 </para></entry>
29913 </row>
29914
29915 <row>
29916 <entry id="pg-replication-origin-xact-reset" role="func_table_entry"><para role="func_signature">
29917 <indexterm>
29918 <primary>pg_replication_origin_xact_reset</primary>
29919 </indexterm>
29920 <function>pg_replication_origin_xact_reset</function> ()
29921 <returnvalue>void</returnvalue>
29922 </para>
29923 <para>
29924 Cancels the effects of
29925 <function>pg_replication_origin_xact_setup()</function>.
29926 </para></entry>
29927 </row>
29928
29929 <row>
29930 <entry id="pg-replication-origin-advance" role="func_table_entry"><para role="func_signature">
29931 <indexterm>
29932 <primary>pg_replication_origin_advance</primary>
29933 </indexterm>
29934 <function>pg_replication_origin_advance</function> ( <parameter>node_name</parameter> <type>text</type>, <parameter>lsn</parameter> <type>pg_lsn</type> )
29935 <returnvalue>void</returnvalue>
29936 </para>
29937 <para>
29938 Sets replication progress for the given node to the given
29939 location. This is primarily useful for setting up the initial
29940 location, or setting a new location after configuration changes and
29941 similar. Be aware that careless use of this function can lead to
29942 inconsistently replicated data.
29943 </para></entry>
29944 </row>
29945
29946 <row>
29947 <entry id="pg-replication-origin-progress" role="func_table_entry"><para role="func_signature">
29948 <indexterm>
29949 <primary>pg_replication_origin_progress</primary>
29950 </indexterm>
29951 <function>pg_replication_origin_progress</function> ( <parameter>node_name</parameter> <type>text</type>, <parameter>flush</parameter> <type>boolean</type> )
29952 <returnvalue>pg_lsn</returnvalue>
29953 </para>
29954 <para>
29955 Returns the replay location for the given replication origin. The
29956 parameter <parameter>flush</parameter> determines whether the
29957 corresponding local transaction will be guaranteed to have been
29958 flushed to disk or not.
29959 </para></entry>
29960 </row>
29961
29962 <row>
29963 <entry id="pg-logical-emit-message" role="func_table_entry"><para role="func_signature">
29964 <indexterm>
29965 <primary>pg_logical_emit_message</primary>
29966 </indexterm>
29967 <function>pg_logical_emit_message</function> ( <parameter>transactional</parameter> <type>boolean</type>, <parameter>prefix</parameter> <type>text</type>, <parameter>content</parameter> <type>text</type> <optional>, <parameter>flush</parameter> <type>boolean</type> <literal>DEFAULT</literal> <literal>false</literal></optional> )
29968 <returnvalue>pg_lsn</returnvalue>
29969 </para>
29970 <para role="func_signature">
29971 <function>pg_logical_emit_message</function> ( <parameter>transactional</parameter> <type>boolean</type>, <parameter>prefix</parameter> <type>text</type>, <parameter>content</parameter> <type>bytea</type> <optional>, <parameter>flush</parameter> <type>boolean</type> <literal>DEFAULT</literal> <literal>false</literal></optional> )
29972 <returnvalue>pg_lsn</returnvalue>
29973 </para>
29974 <para>
29975 Emits a logical decoding message. This can be used to pass generic
29976 messages to logical decoding plugins through
29977 WAL. The <parameter>transactional</parameter> parameter specifies if
29978 the message should be part of the current transaction, or if it should
29979 be written immediately and decoded as soon as the logical decoder
29980 reads the record. The <parameter>prefix</parameter> parameter is a
29981 textual prefix that can be used by logical decoding plugins to easily
29982 recognize messages that are interesting for them.
29983 The <parameter>content</parameter> parameter is the content of the
29984 message, given either in text or binary form.
29985 The <parameter>flush</parameter> parameter (default set to
29986 <literal>false</literal>) controls if the message is immediately
29987 flushed to WAL or not. <parameter>flush</parameter> has no effect
29988 with <parameter>transactional</parameter>, as the message's WAL
29989 record is flushed along with its transaction.
29990 </para></entry>
29991 </row>
29992
29993 <row>
29994 <entry id="pg-sync-replication-slots" role="func_table_entry"><para role="func_signature">
29995 <indexterm>
29996 <primary>pg_sync_replication_slots</primary>
29997 </indexterm>
29998 <function>pg_sync_replication_slots</function> ()
29999 <returnvalue>void</returnvalue>
30000 </para>
30001 <para>
30002 Synchronize the logical failover replication slots from the primary
30003 server to the standby server. This function can only be executed on the
30004 standby server. Temporary synced slots, if any, cannot be used for
30005 logical decoding and must be dropped after promotion. See
30006 <xref linkend="logicaldecoding-replication-slots-synchronization"/> for details.
30007 Note that this function is primarily intended for testing and
30008 debugging purposes and should be used with caution. Additionally,
30009 this function cannot be executed if
30010 <link linkend="guc-sync-replication-slots"><varname>
30011 sync_replication_slots</varname></link> is enabled and the slotsync
30012 worker is already running to perform the synchronization of slots.
30013 </para>
30014
30015 <caution>
30016 <para>
30017 If, after executing the function,
30018 <link linkend="guc-hot-standby-feedback">
30019 <varname>hot_standby_feedback</varname></link> is disabled on
30020 the standby or the physical slot configured in
30021 <link linkend="guc-primary-slot-name">
30022 <varname>primary_slot_name</varname></link> is
30023 removed, then it is possible that the necessary rows of the
30024 synchronized slot will be removed by the VACUUM process on the primary
30025 server, resulting in the synchronized slot becoming invalidated.
30026 </para>
30027 </caution>
30028 </entry>
30029 </row>
30030
30031 </tbody>
30032 </tgroup>
30033 </table>
30034
30035 </sect2>
30036
30037 <sect2 id="functions-admin-dbobject">
30038 <title>Database Object Management Functions</title>
30039
30040 <para>
30041 The functions shown in <xref linkend="functions-admin-dbsize"/> calculate
30042 the disk space usage of database objects, or assist in presentation
30043 or understanding of usage results. <literal>bigint</literal> results
30044 are measured in bytes. If an OID that does
30045 not represent an existing object is passed to one of these
30046 functions, <literal>NULL</literal> is returned.
30047 </para>
30048
30049 <table id="functions-admin-dbsize">
30050 <title>Database Object Size Functions</title>
30051 <tgroup cols="1">
30052 <thead>
30053 <row>
30054 <entry role="func_table_entry"><para role="func_signature">
30055 Function
30056 </para>
30057 <para>
30058 Description
30059 </para></entry>
30060 </row>
30061 </thead>
30062
30063 <tbody>
30064 <row>
30065 <entry role="func_table_entry"><para role="func_signature">
30066 <indexterm>
30067 <primary>pg_column_size</primary>
30068 </indexterm>
30069 <function>pg_column_size</function> ( <type>"any"</type> )
30070 <returnvalue>integer</returnvalue>
30071 </para>
30072 <para>
30073 Shows the number of bytes used to store any individual data value. If
30074 applied directly to a table column value, this reflects any
30075 compression that was done.
30076 </para></entry>
30077 </row>
30078
30079 <row>
30080 <entry role="func_table_entry"><para role="func_signature">
30081 <indexterm>
30082 <primary>pg_column_compression</primary>
30083 </indexterm>
30084 <function>pg_column_compression</function> ( <type>"any"</type> )
30085 <returnvalue>text</returnvalue>
30086 </para>
30087 <para>
30088 Shows the compression algorithm that was used to compress
30089 an individual variable-length value. Returns <literal>NULL</literal>
30090 if the value is not compressed.
30091 </para></entry>
30092 </row>
30093
30094 <row>
30095 <entry role="func_table_entry"><para role="func_signature">
30096 <indexterm>
30097 <primary>pg_column_toast_chunk_id</primary>
30098 </indexterm>
30099 <function>pg_column_toast_chunk_id</function> ( <type>"any"</type> )
30100 <returnvalue>oid</returnvalue>
30101 </para>
30102 <para>
30103 Shows the <structfield>chunk_id</structfield> of an on-disk
30104 <acronym>TOAST</acronym>ed value. Returns <literal>NULL</literal>
30105 if the value is un-<acronym>TOAST</acronym>ed or not on-disk. See
30106 <xref linkend="storage-toast"/> for more information about
30107 <acronym>TOAST</acronym>.
30108 </para></entry>
30109 </row>
30110
30111 <row>
30112 <entry role="func_table_entry"><para role="func_signature">
30113 <indexterm>
30114 <primary>pg_database_size</primary>
30115 </indexterm>
30116 <function>pg_database_size</function> ( <type>name</type> )
30117 <returnvalue>bigint</returnvalue>
30118 </para>
30119 <para role="func_signature">
30120 <function>pg_database_size</function> ( <type>oid</type> )
30121 <returnvalue>bigint</returnvalue>
30122 </para>
30123 <para>
30124 Computes the total disk space used by the database with the specified
30125 name or OID. To use this function, you must
30126 have <literal>CONNECT</literal> privilege on the specified database
30127 (which is granted by default) or have privileges of
30128 the <literal>pg_read_all_stats</literal> role.
30129 </para></entry>
30130 </row>
30131
30132 <row>
30133 <entry role="func_table_entry"><para role="func_signature">
30134 <indexterm>
30135 <primary>pg_indexes_size</primary>
30136 </indexterm>
30137 <function>pg_indexes_size</function> ( <type>regclass</type> )
30138 <returnvalue>bigint</returnvalue>
30139 </para>
30140 <para>
30141 Computes the total disk space used by indexes attached to the
30142 specified table.
30143 </para></entry>
30144 </row>
30145
30146 <row>
30147 <entry role="func_table_entry"><para role="func_signature">
30148 <indexterm>
30149 <primary>pg_relation_size</primary>
30150 </indexterm>
30151 <function>pg_relation_size</function> ( <parameter>relation</parameter> <type>regclass</type> <optional>, <parameter>fork</parameter> <type>text</type> </optional> )
30152 <returnvalue>bigint</returnvalue>
30153 </para>
30154 <para>
30155 Computes the disk space used by one <quote>fork</quote> of the
30156 specified relation. (Note that for most purposes it is more
30157 convenient to use the higher-level
30158 functions <function>pg_total_relation_size</function>
30159 or <function>pg_table_size</function>, which sum the sizes of all
30160 forks.) With one argument, this returns the size of the main data
30161 fork of the relation. The second argument can be provided to specify
30162 which fork to examine:
30163 <itemizedlist spacing="compact">
30164 <listitem>
30165 <para>
30166 <literal>main</literal> returns the size of the main
30167 data fork of the relation.
30168 </para>
30169 </listitem>
30170 <listitem>
30171 <para>
30172 <literal>fsm</literal> returns the size of the Free Space Map
30173 (see <xref linkend="storage-fsm"/>) associated with the relation.
30174 </para>
30175 </listitem>
30176 <listitem>
30177 <para>
30178 <literal>vm</literal> returns the size of the Visibility Map
30179 (see <xref linkend="storage-vm"/>) associated with the relation.
30180 </para>
30181 </listitem>
30182 <listitem>
30183 <para>
30184 <literal>init</literal> returns the size of the initialization
30185 fork, if any, associated with the relation.
30186 </para>
30187 </listitem>
30188 </itemizedlist>
30189 </para></entry>
30190 </row>
30191
30192 <row>
30193 <entry role="func_table_entry"><para role="func_signature">
30194 <indexterm>
30195 <primary>pg_size_bytes</primary>
30196 </indexterm>
30197 <function>pg_size_bytes</function> ( <type>text</type> )
30198 <returnvalue>bigint</returnvalue>
30199 </para>
30200 <para>
30201 Converts a size in human-readable format (as returned
30202 by <function>pg_size_pretty</function>) into bytes. Valid units are
30203 <literal>bytes</literal>, <literal>B</literal>, <literal>kB</literal>,
30204 <literal>MB</literal>, <literal>GB</literal>, <literal>TB</literal>,
30205 and <literal>PB</literal>.
30206 </para></entry>
30207 </row>
30208
30209 <row>
30210 <entry role="func_table_entry"><para role="func_signature">
30211 <indexterm>
30212 <primary>pg_size_pretty</primary>
30213 </indexterm>
30214 <function>pg_size_pretty</function> ( <type>bigint</type> )
30215 <returnvalue>text</returnvalue>
30216 </para>
30217 <para role="func_signature">
30218 <function>pg_size_pretty</function> ( <type>numeric</type> )
30219 <returnvalue>text</returnvalue>
30220 </para>
30221 <para>
30222 Converts a size in bytes into a more easily human-readable format with
30223 size units (bytes, kB, MB, GB, TB, or PB as appropriate). Note that the
30224 units are powers of 2 rather than powers of 10, so 1kB is 1024 bytes,
30225 1MB is 1024<superscript>2</superscript> = 1048576 bytes, and so on.
30226 </para></entry>
30227 </row>
30228
30229 <row>
30230 <entry role="func_table_entry"><para role="func_signature">
30231 <indexterm>
30232 <primary>pg_table_size</primary>
30233 </indexterm>
30234 <function>pg_table_size</function> ( <type>regclass</type> )
30235 <returnvalue>bigint</returnvalue>
30236 </para>
30237 <para>
30238 Computes the disk space used by the specified table, excluding indexes
30239 (but including its TOAST table if any, free space map, and visibility
30240 map).
30241 </para></entry>
30242 </row>
30243
30244 <row>
30245 <entry role="func_table_entry"><para role="func_signature">
30246 <indexterm>
30247 <primary>pg_tablespace_size</primary>
30248 </indexterm>
30249 <function>pg_tablespace_size</function> ( <type>name</type> )
30250 <returnvalue>bigint</returnvalue>
30251 </para>
30252 <para role="func_signature">
30253 <function>pg_tablespace_size</function> ( <type>oid</type> )
30254 <returnvalue>bigint</returnvalue>
30255 </para>
30256 <para>
30257 Computes the total disk space used in the tablespace with the
30258 specified name or OID. To use this function, you must
30259 have <literal>CREATE</literal> privilege on the specified tablespace
30260 or have privileges of the <literal>pg_read_all_stats</literal> role,
30261 unless it is the default tablespace for the current database.
30262 </para></entry>
30263 </row>
30264
30265 <row>
30266 <entry role="func_table_entry"><para role="func_signature">
30267 <indexterm>
30268 <primary>pg_total_relation_size</primary>
30269 </indexterm>
30270 <function>pg_total_relation_size</function> ( <type>regclass</type> )
30271 <returnvalue>bigint</returnvalue>
30272 </para>
30273 <para>
30274 Computes the total disk space used by the specified table, including
30275 all indexes and <acronym>TOAST</acronym> data. The result is
30276 equivalent to <function>pg_table_size</function>
30277 <literal>+</literal> <function>pg_indexes_size</function>.
30278 </para></entry>
30279 </row>
30280 </tbody>
30281 </tgroup>
30282 </table>
30283
30284 <para>
30285 The functions above that operate on tables or indexes accept a
30286 <type>regclass</type> argument, which is simply the OID of the table or index
30287 in the <structname>pg_class</structname> system catalog. You do not have to look up
30288 the OID by hand, however, since the <type>regclass</type> data type's input
30289 converter will do the work for you. See <xref linkend="datatype-oid"/>
30290 for details.
30291 </para>
30292
30293 <para>
30294 The functions shown in <xref linkend="functions-admin-dblocation"/> assist
30295 in identifying the specific disk files associated with database objects.
30296 </para>
30297
30298 <table id="functions-admin-dblocation">
30299 <title>Database Object Location Functions</title>
30300 <tgroup cols="1">
30301 <thead>
30302 <row>
30303 <entry role="func_table_entry"><para role="func_signature">
30304 Function
30305 </para>
30306 <para>
30307 Description
30308 </para></entry>
30309 </row>
30310 </thead>
30311
30312 <tbody>
30313 <row>
30314 <entry role="func_table_entry"><para role="func_signature">
30315 <indexterm>
30316 <primary>pg_relation_filenode</primary>
30317 </indexterm>
30318 <function>pg_relation_filenode</function> ( <parameter>relation</parameter> <type>regclass</type> )
30319 <returnvalue>oid</returnvalue>
30320 </para>
30321 <para>
30322 Returns the <quote>filenode</quote> number currently assigned to the
30323 specified relation. The filenode is the base component of the file
30324 name(s) used for the relation (see
30325 <xref linkend="storage-file-layout"/> for more information).
30326 For most relations the result is the same as
30327 <structname>pg_class</structname>.<structfield>relfilenode</structfield>,
30328 but for certain system catalogs <structfield>relfilenode</structfield>
30329 is zero and this function must be used to get the correct value. The
30330 function returns NULL if passed a relation that does not have storage,
30331 such as a view.
30332 </para></entry>
30333 </row>
30334
30335 <row>
30336 <entry role="func_table_entry"><para role="func_signature">
30337 <indexterm>
30338 <primary>pg_relation_filepath</primary>
30339 </indexterm>
30340 <function>pg_relation_filepath</function> ( <parameter>relation</parameter> <type>regclass</type> )
30341 <returnvalue>text</returnvalue>
30342 </para>
30343 <para>
30344 Returns the entire file path name (relative to the database cluster's
30345 data directory, <varname>PGDATA</varname>) of the relation.
30346 </para></entry>
30347 </row>
30348
30349 <row>
30350 <entry role="func_table_entry"><para role="func_signature">
30351 <indexterm>
30352 <primary>pg_filenode_relation</primary>
30353 </indexterm>
30354 <function>pg_filenode_relation</function> ( <parameter>tablespace</parameter> <type>oid</type>, <parameter>filenode</parameter> <type>oid</type> )
30355 <returnvalue>regclass</returnvalue>
30356 </para>
30357 <para>
30358 Returns a relation's OID given the tablespace OID and filenode it is
30359 stored under. This is essentially the inverse mapping of
30360 <function>pg_relation_filepath</function>. For a relation in the
30361 database's default tablespace, the tablespace can be specified as zero.
30362 Returns <literal>NULL</literal> if no relation in the current database
30363 is associated with the given values, or if dealing with a temporary
30364 relation.
30365 </para></entry>
30366 </row>
30367 </tbody>
30368 </tgroup>
30369 </table>
30370
30371 <para>
30372 <xref linkend="functions-admin-collation"/> lists functions used to manage
30373 collations.
30374 </para>
30375
30376 <table id="functions-admin-collation">
30377 <title>Collation Management Functions</title>
30378 <tgroup cols="1">
30379 <thead>
30380 <row>
30381 <entry role="func_table_entry"><para role="func_signature">
30382 Function
30383 </para>
30384 <para>
30385 Description
30386 </para></entry>
30387 </row>
30388 </thead>
30389
30390 <tbody>
30391 <row>
30392 <entry role="func_table_entry"><para role="func_signature">
30393 <indexterm>
30394 <primary>pg_collation_actual_version</primary>
30395 </indexterm>
30396 <function>pg_collation_actual_version</function> ( <type>oid</type> )
30397 <returnvalue>text</returnvalue>
30398 </para>
30399 <para>
30400 Returns the actual version of the collation object as it is currently
30401 installed in the operating system. If this is different from the
30402 value in
30403 <structname>pg_collation</structname>.<structfield>collversion</structfield>,
30404 then objects depending on the collation might need to be rebuilt. See
30405 also <xref linkend="sql-altercollation"/>.
30406 </para></entry>
30407 </row>
30408
30409 <row>
30410 <entry role="func_table_entry"><para role="func_signature">
30411 <indexterm>
30412 <primary>pg_database_collation_actual_version</primary>
30413 </indexterm>
30414 <function>pg_database_collation_actual_version</function> ( <type>oid</type> )
30415 <returnvalue>text</returnvalue>
30416 </para>
30417 <para>
30418 Returns the actual version of the database's collation as it is currently
30419 installed in the operating system. If this is different from the
30420 value in
30421 <structname>pg_database</structname>.<structfield>datcollversion</structfield>,
30422 then objects depending on the collation might need to be rebuilt. See
30423 also <xref linkend="sql-alterdatabase"/>.
30424 </para></entry>
30425 </row>
30426
30427 <row>
30428 <entry role="func_table_entry"><para role="func_signature">
30429 <indexterm>
30430 <primary>pg_import_system_collations</primary>
30431 </indexterm>
30432 <function>pg_import_system_collations</function> ( <parameter>schema</parameter> <type>regnamespace</type> )
30433 <returnvalue>integer</returnvalue>
30434 </para>
30435 <para>
30436 Adds collations to the system
30437 catalog <structname>pg_collation</structname> based on all the locales
30438 it finds in the operating system. This is
30439 what <command>initdb</command> uses; see
30440 <xref linkend="collation-managing"/> for more details. If additional
30441 locales are installed into the operating system later on, this
30442 function can be run again to add collations for the new locales.
30443 Locales that match existing entries
30444 in <structname>pg_collation</structname> will be skipped. (But
30445 collation objects based on locales that are no longer present in the
30446 operating system are not removed by this function.)
30447 The <parameter>schema</parameter> parameter would typically
30448 be <literal>pg_catalog</literal>, but that is not a requirement; the
30449 collations could be installed into some other schema as well. The
30450 function returns the number of new collation objects it created.
30451 Use of this function is restricted to superusers.
30452 </para></entry>
30453 </row>
30454 </tbody>
30455 </tgroup>
30456 </table>
30457
30458 <para>
30459 <xref linkend="functions-admin-statsmod"/> lists functions used to
30460 manipulate statistics.
30461 These functions cannot be executed during recovery.
30462 <warning>
30463 <para>
30464 Changes made by these statistics manipulation functions are likely to be
30465 overwritten by <link linkend="autovacuum">autovacuum</link> (or manual
30466 <command>VACUUM</command> or <command>ANALYZE</command>) and should be
30467 considered temporary.
30468 </para>
30469 </warning>
30470 </para>
30471
30472 <table id="functions-admin-statsmod">
30473 <title>Database Object Statistics Manipulation Functions</title>
30474 <tgroup cols="1">
30475 <thead>
30476 <row>
30477 <entry role="func_table_entry"><para role="func_signature">
30478 Function
30479 </para>
30480 <para>
30481 Description
30482 </para></entry>
30483 </row>
30484 </thead>
30485
30486 <tbody>
30487 <row>
30488 <entry role="func_table_entry"><para role="func_signature">
30489 <indexterm>
30490 <primary>pg_restore_relation_stats</primary>
30491 </indexterm>
30492 <function>pg_restore_relation_stats</function> (
30493 <literal>VARIADIC</literal> <parameter>kwargs</parameter> <type>"any"</type> )
30494 <returnvalue>boolean</returnvalue>
30495 </para>
30496 <para>
30497 Updates table-level statistics. Ordinarily, these statistics are
30498 collected automatically or updated as a part of <xref
30499 linkend="sql-vacuum"/> or <xref linkend="sql-analyze"/>, so it's not
30500 necessary to call this function. However, it is useful after a
30501 restore to enable the optimizer to choose better plans if
30502 <command>ANALYZE</command> has not been run yet.
30503 </para>
30504 <para>
30505 The tracked statistics may change from version to version, so
30506 arguments are passed as pairs of <replaceable>argname</replaceable>
30507 and <replaceable>argvalue</replaceable> in the form:
30508 <programlisting>
30509 SELECT pg_restore_relation_stats(
30510 '<replaceable>arg1name</replaceable>', '<replaceable>arg1value</replaceable>'::<replaceable>arg1type</replaceable>,
30511 '<replaceable>arg2name</replaceable>', '<replaceable>arg2value</replaceable>'::<replaceable>arg2type</replaceable>,
30512 '<replaceable>arg3name</replaceable>', '<replaceable>arg3value</replaceable>'::<replaceable>arg3type</replaceable>);
30513 </programlisting>
30514 </para>
30515 <para>
30516 For example, to set the <structfield>relpages</structfield> and
30517 <structfield>reltuples</structfield> values for the table
30518 <structname>mytable</structname>:
30519 <programlisting>
30520 SELECT pg_restore_relation_stats(
30521 'schemaname', 'myschema',
30522 'relname', 'mytable',
30523 'relpages', 173::integer,
30524 'reltuples', 10000::real);
30525 </programlisting>
30526 </para>
30527 <para>
30528 The arguments <literal>schemaname</literal> and
30529 <literal>relname</literal> are required, and specify the table. Other
30530 arguments are the names and values of statistics corresponding to
30531 certain columns in <link
30532 linkend="catalog-pg-class"><structname>pg_class</structname></link>.
30533 The currently-supported relation statistics are
30534 <literal>relpages</literal> with a value of type
30535 <type>integer</type>, <literal>reltuples</literal> with a value of
30536 type <type>real</type>, <literal>relallvisible</literal> with a value
30537 of type <type>integer</type>, and <literal>relallfrozen</literal>
30538 with a value of type <type>integer</type>.
30539 </para>
30540 <para>
30541 Additionally, this function accepts argument name
30542 <literal>version</literal> of type <type>integer</type>, which
30543 specifies the server version from which the statistics originated.
30544 This is anticipated to be helpful in porting statistics from older
30545 versions of <productname>PostgreSQL</productname>.
30546 </para>
30547 <para>
30548 Minor errors are reported as a <literal>WARNING</literal> and
30549 ignored, and remaining statistics will still be restored. If all
30550 specified statistics are successfully restored, returns
30551 <literal>true</literal>, otherwise <literal>false</literal>.
30552 </para>
30553 <para>
30554 The caller must have the <literal>MAINTAIN</literal> privilege on the
30555 table or be the owner of the database.
30556 </para>
30557 </entry>
30558 </row>
30559
30560 <row>
30561 <entry role="func_table_entry">
30562 <para role="func_signature">
30563 <indexterm>
30564 <primary>pg_clear_relation_stats</primary>
30565 </indexterm>
30566 <function>pg_clear_relation_stats</function> ( <parameter>schemaname</parameter> <type>text</type>, <parameter>relname</parameter> <type>text</type> )
30567 <returnvalue>void</returnvalue>
30568 </para>
30569 <para>
30570 Clears table-level statistics for the given relation, as though the
30571 table was newly created.
30572 </para>
30573 <para>
30574 The caller must have the <literal>MAINTAIN</literal> privilege on the
30575 table or be the owner of the database.
30576 </para>
30577 </entry>
30578 </row>
30579
30580 <row>
30581 <entry role="func_table_entry"><para role="func_signature">
30582 <indexterm>
30583 <primary>pg_restore_attribute_stats</primary>
30584 </indexterm>
30585 <function>pg_restore_attribute_stats</function> (
30586 <literal>VARIADIC</literal> <parameter>kwargs</parameter> <type>"any"</type> )
30587 <returnvalue>boolean</returnvalue>
30588 </para>
30589 <para>
30590 Creates or updates column-level statistics. Ordinarily, these
30591 statistics are collected automatically or updated as a part of <xref
30592 linkend="sql-vacuum"/> or <xref linkend="sql-analyze"/>, so it's not
30593 necessary to call this function. However, it is useful after a
30594 restore to enable the optimizer to choose better plans if
30595 <command>ANALYZE</command> has not been run yet.
30596 </para>
30597 <para>
30598 The tracked statistics may change from version to version, so
30599 arguments are passed as pairs of <replaceable>argname</replaceable>
30600 and <replaceable>argvalue</replaceable> in the form:
30601 <programlisting>
30602 SELECT pg_restore_attribute_stats(
30603 '<replaceable>arg1name</replaceable>', '<replaceable>arg1value</replaceable>'::<replaceable>arg1type</replaceable>,
30604 '<replaceable>arg2name</replaceable>', '<replaceable>arg2value</replaceable>'::<replaceable>arg2type</replaceable>,
30605 '<replaceable>arg3name</replaceable>', '<replaceable>arg3value</replaceable>'::<replaceable>arg3type</replaceable>);
30606 </programlisting>
30607 </para>
30608 <para>
30609 For example, to set the <structfield>avg_width</structfield> and
30610 <structfield>null_frac</structfield> values for the attribute
30611 <structfield>col1</structfield> of the table
30612 <structname>mytable</structname>:
30613 <programlisting>
30614 SELECT pg_restore_attribute_stats(
30615 'schemaname', 'myschema',
30616 'relname', 'mytable',
30617 'attname', 'col1',
30618 'inherited', false,
30619 'avg_width', 125::integer,
30620 'null_frac', 0.5::real);
30621 </programlisting>
30622 </para>
30623 <para>
30624 The required arguments are <literal>schemaname</literal> and
30625 <literal>relname</literal> with a value of type <type>text</type>
30626 which specify the table; either <literal>attname</literal> with a
30627 value of type <type>text</type> or <literal>attnum</literal> with a
30628 value of type <type>smallint</type>, which specifies the column; and
30629 <literal>inherited</literal>, which specifies whether the statistics
30630 include values from child tables. Other arguments are the names and
30631 values of statistics corresponding to columns in <link
30632 linkend="view-pg-stats"><structname>pg_stats</structname></link>.
30633 </para>
30634 <para>
30635 Additionally, this function accepts argument name
30636 <literal>version</literal> of type <type>integer</type>, which
30637 specifies the server version from which the statistics originated.
30638 This is anticipated to be helpful in porting statistics from older
30639 versions of <productname>PostgreSQL</productname>.
30640 </para>
30641 <para>
30642 Minor errors are reported as a <literal>WARNING</literal> and
30643 ignored, and remaining statistics will still be restored. If all
30644 specified statistics are successfully restored, returns
30645 <literal>true</literal>, otherwise <literal>false</literal>.
30646 </para>
30647 <para>
30648 The caller must have the <literal>MAINTAIN</literal> privilege on the
30649 table or be the owner of the database.
30650 </para>
30651 </entry>
30652 </row>
30653
30654 <row>
30655 <entry role="func_table_entry">
30656 <para role="func_signature">
30657 <indexterm>
30658 <primary>pg_clear_attribute_stats</primary>
30659 </indexterm>
30660 <function>pg_clear_attribute_stats</function> (
30661 <parameter>schemaname</parameter> <type>text</type>,
30662 <parameter>relname</parameter> <type>text</type>,
30663 <parameter>attname</parameter> <type>text</type>,
30664 <parameter>inherited</parameter> <type>boolean</type> )
30665 <returnvalue>void</returnvalue>
30666 </para>
30667 <para>
30668 Clears column-level statistics for the given relation and
30669 attribute, as though the table was newly created.
30670 </para>
30671 <para>
30672 The caller must have the <literal>MAINTAIN</literal> privilege on
30673 the table or be the owner of the database.
30674 </para>
30675 </entry>
30676 </row>
30677 </tbody>
30678 </tgroup>
30679 </table>
30680
30681 <para>
30682 <xref linkend="functions-info-partition"/> lists functions that provide
30683 information about the structure of partitioned tables.
30684 </para>
30685
30686 <table id="functions-info-partition">
30687 <title>Partitioning Information Functions</title>
30688 <tgroup cols="1">
30689 <thead>
30690 <row>
30691 <entry role="func_table_entry"><para role="func_signature">
30692 Function
30693 </para>
30694 <para>
30695 Description
30696 </para></entry>
30697 </row>
30698 </thead>
30699
30700 <tbody>
30701 <row>
30702 <entry role="func_table_entry"><para role="func_signature">
30703 <indexterm>
30704 <primary>pg_partition_tree</primary>
30705 </indexterm>
30706 <function>pg_partition_tree</function> ( <type>regclass</type> )
30707 <returnvalue>setof record</returnvalue>
30708 ( <parameter>relid</parameter> <type>regclass</type>,
30709 <parameter>parentrelid</parameter> <type>regclass</type>,
30710 <parameter>isleaf</parameter> <type>boolean</type>,
30711 <parameter>level</parameter> <type>integer</type> )
30712 </para>
30713 <para>
30714 Lists the tables or indexes in the partition tree of the
30715 given partitioned table or partitioned index, with one row for each
30716 partition. Information provided includes the OID of the partition,
30717 the OID of its immediate parent, a boolean value telling if the
30718 partition is a leaf, and an integer telling its level in the hierarchy.
30719 The level value is 0 for the input table or index, 1 for its
30720 immediate child partitions, 2 for their partitions, and so on.
30721 Returns no rows if the relation does not exist or is not a partition
30722 or partitioned table.
30723 </para></entry>
30724 </row>
30725
30726 <row>
30727 <entry role="func_table_entry"><para role="func_signature">
30728 <indexterm>
30729 <primary>pg_partition_ancestors</primary>
30730 </indexterm>
30731 <function>pg_partition_ancestors</function> ( <type>regclass</type> )
30732 <returnvalue>setof regclass</returnvalue>
30733 </para>
30734 <para>
30735 Lists the ancestor relations of the given partition,
30736 including the relation itself. Returns no rows if the relation
30737 does not exist or is not a partition or partitioned table.
30738 </para></entry>
30739 </row>
30740
30741 <row>
30742 <entry role="func_table_entry"><para role="func_signature">
30743 <indexterm>
30744 <primary>pg_partition_root</primary>
30745 </indexterm>
30746 <function>pg_partition_root</function> ( <type>regclass</type> )
30747 <returnvalue>regclass</returnvalue>
30748 </para>
30749 <para>
30750 Returns the top-most parent of the partition tree to which the given
30751 relation belongs. Returns <literal>NULL</literal> if the relation
30752 does not exist or is not a partition or partitioned table.
30753 </para></entry>
30754 </row>
30755 </tbody>
30756 </tgroup>
30757 </table>
30758
30759 <para>
30760 For example, to check the total size of the data contained in a
30761 partitioned table <structname>measurement</structname>, one could use the
30762 following query:
30763 <programlisting>
30764 SELECT pg_size_pretty(sum(pg_relation_size(relid))) AS total_size
30765 FROM pg_partition_tree('measurement');
30766 </programlisting>
30767 </para>
30768
30769 </sect2>
30770
30771 <sect2 id="functions-admin-index">
30772 <title>Index Maintenance Functions</title>
30773
30774 <para>
30775 <xref linkend="functions-admin-index-table"/> shows the functions
30776 available for index maintenance tasks. (Note that these maintenance
30777 tasks are normally done automatically by autovacuum; use of these
30778 functions is only required in special cases.)
30779 These functions cannot be executed during recovery.
30780 Use of these functions is restricted to superusers and the owner
30781 of the given index.
30782 </para>
30783
30784 <table id="functions-admin-index-table">
30785 <title>Index Maintenance Functions</title>
30786 <tgroup cols="1">
30787 <thead>
30788 <row>
30789 <entry role="func_table_entry"><para role="func_signature">
30790 Function
30791 </para>
30792 <para>
30793 Description
30794 </para></entry>
30795 </row>
30796 </thead>
30797
30798 <tbody>
30799 <row>
30800 <entry role="func_table_entry"><para role="func_signature">
30801 <indexterm>
30802 <primary>brin_summarize_new_values</primary>
30803 </indexterm>
30804 <function>brin_summarize_new_values</function> ( <parameter>index</parameter> <type>regclass</type> )
30805 <returnvalue>integer</returnvalue>
30806 </para>
30807 <para>
30808 Scans the specified BRIN index to find page ranges in the base table
30809 that are not currently summarized by the index; for any such range it
30810 creates a new summary index tuple by scanning those table pages.
30811 Returns the number of new page range summaries that were inserted
30812 into the index.
30813 </para></entry>
30814 </row>
30815
30816 <row>
30817 <entry role="func_table_entry"><para role="func_signature">
30818 <indexterm>
30819 <primary>brin_summarize_range</primary>
30820 </indexterm>
30821 <function>brin_summarize_range</function> ( <parameter>index</parameter> <type>regclass</type>, <parameter>blockNumber</parameter> <type>bigint</type> )
30822 <returnvalue>integer</returnvalue>
30823 </para>
30824 <para>
30825 Summarizes the page range covering the given block, if not already
30826 summarized. This is
30827 like <function>brin_summarize_new_values</function> except that it
30828 only processes the page range that covers the given table block number.
30829 </para></entry>
30830 </row>
30831
30832 <row>
30833 <entry role="func_table_entry"><para role="func_signature">
30834 <indexterm>
30835 <primary>brin_desummarize_range</primary>
30836 </indexterm>
30837 <function>brin_desummarize_range</function> ( <parameter>index</parameter> <type>regclass</type>, <parameter>blockNumber</parameter> <type>bigint</type> )
30838 <returnvalue>void</returnvalue>
30839 </para>
30840 <para>
30841 Removes the BRIN index tuple that summarizes the page range covering
30842 the given table block, if there is one.
30843 </para></entry>
30844 </row>
30845
30846 <row>
30847 <entry role="func_table_entry"><para role="func_signature">
30848 <indexterm>
30849 <primary>gin_clean_pending_list</primary>
30850 </indexterm>
30851 <function>gin_clean_pending_list</function> ( <parameter>index</parameter> <type>regclass</type> )
30852 <returnvalue>bigint</returnvalue>
30853 </para>
30854 <para>
30855 Cleans up the <quote>pending</quote> list of the specified GIN index
30856 by moving entries in it, in bulk, to the main GIN data structure.
30857 Returns the number of pages removed from the pending list.
30858 If the argument is a GIN index built with
30859 the <literal>fastupdate</literal> option disabled, no cleanup happens
30860 and the result is zero, because the index doesn't have a pending list.
30861 See <xref linkend="gin-fast-update"/> and <xref linkend="gin-tips"/>
30862 for details about the pending list and <literal>fastupdate</literal>
30863 option.
30864 </para></entry>
30865 </row>
30866 </tbody>
30867 </tgroup>
30868 </table>
30869
30870 </sect2>
30871
30872 <sect2 id="functions-admin-genfile">
30873 <title>Generic File Access Functions</title>
30874
30875 <para>
30876 The functions shown in <xref
30877 linkend="functions-admin-genfile-table"/> provide native access to
30878 files on the machine hosting the server. Only files within the
30879 database cluster directory and the <varname>log_directory</varname> can be
30880 accessed, unless the user is a superuser or is granted the role
30881 <literal>pg_read_server_files</literal>. Use a relative path for files in
30882 the cluster directory, and a path matching the <varname>log_directory</varname>
30883 configuration setting for log files.
30884 </para>
30885
30886 <para>
30887 Note that granting users the EXECUTE privilege on
30888 <function>pg_read_file()</function>, or related functions, allows them the
30889 ability to read any file on the server that the database server process can
30890 read; these functions bypass all in-database privilege checks. This means
30891 that, for example, a user with such access is able to read the contents of
30892 the <structname>pg_authid</structname> table where authentication
30893 information is stored, as well as read any table data in the database.
30894 Therefore, granting access to these functions should be carefully
30895 considered.
30896 </para>
30897
30898 <para>
30899 When granting privilege on these functions, note that the table entries
30900 showing optional parameters are mostly implemented as several physical
30901 functions with different parameter lists. Privilege must be granted
30902 separately on each such function, if it is to be
30903 used. <application>psql</application>'s <command>\df</command> command
30904 can be useful to check what the actual function signatures are.
30905 </para>
30906
30907 <para>
30908 Some of these functions take an optional <parameter>missing_ok</parameter>
30909 parameter, which specifies the behavior when the file or directory does
30910 not exist. If <literal>true</literal>, the function
30911 returns <literal>NULL</literal> or an empty result set, as appropriate.
30912 If <literal>false</literal>, an error is raised. (Failure conditions
30913 other than <quote>file not found</quote> are reported as errors in any
30914 case.) The default is <literal>false</literal>.
30915 </para>
30916
30917 <table id="functions-admin-genfile-table">
30918 <title>Generic File Access Functions</title>
30919 <tgroup cols="1">
30920 <thead>
30921 <row>
30922 <entry role="func_table_entry"><para role="func_signature">
30923 Function
30924 </para>
30925 <para>
30926 Description
30927 </para></entry>
30928 </row>
30929 </thead>
30930
30931 <tbody>
30932 <row>
30933 <entry role="func_table_entry"><para role="func_signature">
30934 <indexterm>
30935 <primary>pg_ls_dir</primary>
30936 </indexterm>
30937 <function>pg_ls_dir</function> ( <parameter>dirname</parameter> <type>text</type> <optional>, <parameter>missing_ok</parameter> <type>boolean</type>, <parameter>include_dot_dirs</parameter> <type>boolean</type> </optional> )
30938 <returnvalue>setof text</returnvalue>
30939 </para>
30940 <para>
30941 Returns the names of all files (and directories and other special
30942 files) in the specified
30943 directory. The <parameter>include_dot_dirs</parameter> parameter
30944 indicates whether <quote>.</quote> and <quote>..</quote> are to be
30945 included in the result set; the default is to exclude them. Including
30946 them can be useful when <parameter>missing_ok</parameter>
30947 is <literal>true</literal>, to distinguish an empty directory from a
30948 non-existent directory.
30949 </para>
30950 <para>
30951 This function is restricted to superusers by default, but other users
30952 can be granted EXECUTE to run the function.
30953 </para></entry>
30954 </row>
30955
30956 <row>
30957 <entry role="func_table_entry"><para role="func_signature">
30958 <indexterm>
30959 <primary>pg_ls_logdir</primary>
30960 </indexterm>
30961 <function>pg_ls_logdir</function> ()
30962 <returnvalue>setof record</returnvalue>
30963 ( <parameter>name</parameter> <type>text</type>,
30964 <parameter>size</parameter> <type>bigint</type>,
30965 <parameter>modification</parameter> <type>timestamp with time zone</type> )
30966 </para>
30967 <para>
30968 Returns the name, size, and last modification time (mtime) of each
30969 ordinary file in the server's log directory. Filenames beginning with
30970 a dot, directories, and other special files are excluded.
30971 </para>
30972 <para>
30973 This function is restricted to superusers and roles with privileges of
30974 the <literal>pg_monitor</literal> role by default, but other users can
30975 be granted EXECUTE to run the function.
30976 </para></entry>
30977 </row>
30978
30979 <row>
30980 <entry role="func_table_entry"><para role="func_signature">
30981 <indexterm>
30982 <primary>pg_ls_waldir</primary>
30983 </indexterm>
30984 <function>pg_ls_waldir</function> ()
30985 <returnvalue>setof record</returnvalue>
30986 ( <parameter>name</parameter> <type>text</type>,
30987 <parameter>size</parameter> <type>bigint</type>,
30988 <parameter>modification</parameter> <type>timestamp with time zone</type> )
30989 </para>
30990 <para>
30991 Returns the name, size, and last modification time (mtime) of each
30992 ordinary file in the server's write-ahead log (WAL) directory.
30993 Filenames beginning with a dot, directories, and other special files
30994 are excluded.
30995 </para>
30996 <para>
30997 This function is restricted to superusers and roles with privileges of
30998 the <literal>pg_monitor</literal> role by default, but other users can
30999 be granted EXECUTE to run the function.
31000 </para></entry>
31001 </row>
31002
31003 <row>
31004 <entry role="func_table_entry"><para role="func_signature">
31005 <indexterm>
31006 <primary>pg_ls_logicalmapdir</primary>
31007 </indexterm>
31008 <function>pg_ls_logicalmapdir</function> ()
31009 <returnvalue>setof record</returnvalue>
31010 ( <parameter>name</parameter> <type>text</type>,
31011 <parameter>size</parameter> <type>bigint</type>,
31012 <parameter>modification</parameter> <type>timestamp with time zone</type> )
31013 </para>
31014 <para>
31015 Returns the name, size, and last modification time (mtime) of each
31016 ordinary file in the server's <filename>pg_logical/mappings</filename>
31017 directory. Filenames beginning with a dot, directories, and other
31018 special files are excluded.
31019 </para>
31020 <para>
31021 This function is restricted to superusers and members of
31022 the <literal>pg_monitor</literal> role by default, but other users can
31023 be granted EXECUTE to run the function.
31024 </para></entry>
31025 </row>
31026
31027 <row>
31028 <entry role="func_table_entry"><para role="func_signature">
31029 <indexterm>
31030 <primary>pg_ls_logicalsnapdir</primary>
31031 </indexterm>
31032 <function>pg_ls_logicalsnapdir</function> ()
31033 <returnvalue>setof record</returnvalue>
31034 ( <parameter>name</parameter> <type>text</type>,
31035 <parameter>size</parameter> <type>bigint</type>,
31036 <parameter>modification</parameter> <type>timestamp with time zone</type> )
31037 </para>
31038 <para>
31039 Returns the name, size, and last modification time (mtime) of each
31040 ordinary file in the server's <filename>pg_logical/snapshots</filename>
31041 directory. Filenames beginning with a dot, directories, and other
31042 special files are excluded.
31043 </para>
31044 <para>
31045 This function is restricted to superusers and members of
31046 the <literal>pg_monitor</literal> role by default, but other users can
31047 be granted EXECUTE to run the function.
31048 </para></entry>
31049 </row>
31050
31051 <row>
31052 <entry role="func_table_entry"><para role="func_signature">
31053 <indexterm>
31054 <primary>pg_ls_replslotdir</primary>
31055 </indexterm>
31056 <function>pg_ls_replslotdir</function> ( <parameter>slot_name</parameter> <type>text</type> )
31057 <returnvalue>setof record</returnvalue>
31058 ( <parameter>name</parameter> <type>text</type>,
31059 <parameter>size</parameter> <type>bigint</type>,
31060 <parameter>modification</parameter> <type>timestamp with time zone</type> )
31061 </para>
31062 <para>
31063 Returns the name, size, and last modification time (mtime) of each
31064 ordinary file in the server's <filename>pg_replslot/slot_name</filename>
31065 directory, where <parameter>slot_name</parameter> is the name of the
31066 replication slot provided as input of the function. Filenames beginning
31067 with a dot, directories, and other special files are excluded.
31068 </para>
31069 <para>
31070 This function is restricted to superusers and members of
31071 the <literal>pg_monitor</literal> role by default, but other users can
31072 be granted EXECUTE to run the function.
31073 </para></entry>
31074 </row>
31075
31076 <row>
31077 <entry role="func_table_entry"><para role="func_signature">
31078 <indexterm>
31079 <primary>pg_ls_summariesdir</primary>
31080 </indexterm>
31081 <function>pg_ls_summariesdir</function> ()
31082 <returnvalue>setof record</returnvalue>
31083 ( <parameter>name</parameter> <type>text</type>,
31084 <parameter>size</parameter> <type>bigint</type>,
31085 <parameter>modification</parameter> <type>timestamp with time zone</type> )
31086 </para>
31087 <para>
31088 Returns the name, size, and last modification time (mtime) of each
31089 ordinary file in the server's WAL summaries directory
31090 (<filename>pg_wal/summaries</filename>). Filenames beginning
31091 with a dot, directories, and other special files are excluded.
31092 </para>
31093 <para>
31094 This function is restricted to superusers and members of
31095 the <literal>pg_monitor</literal> role by default, but other users can
31096 be granted EXECUTE to run the function.
31097 </para></entry>
31098 </row>
31099
31100 <row>
31101 <entry role="func_table_entry"><para role="func_signature">
31102 <indexterm>
31103 <primary>pg_ls_archive_statusdir</primary>
31104 </indexterm>
31105 <function>pg_ls_archive_statusdir</function> ()
31106 <returnvalue>setof record</returnvalue>
31107 ( <parameter>name</parameter> <type>text</type>,
31108 <parameter>size</parameter> <type>bigint</type>,
31109 <parameter>modification</parameter> <type>timestamp with time zone</type> )
31110 </para>
31111 <para>
31112 Returns the name, size, and last modification time (mtime) of each
31113 ordinary file in the server's WAL archive status directory
31114 (<filename>pg_wal/archive_status</filename>). Filenames beginning
31115 with a dot, directories, and other special files are excluded.
31116 </para>
31117 <para>
31118 This function is restricted to superusers and members of
31119 the <literal>pg_monitor</literal> role by default, but other users can
31120 be granted EXECUTE to run the function.
31121 </para></entry>
31122 </row>
31123
31124 <row>
31125 <entry role="func_table_entry"><para role="func_signature">
31126
31127 <indexterm>
31128 <primary>pg_ls_tmpdir</primary>
31129 </indexterm>
31130 <function>pg_ls_tmpdir</function> ( <optional> <parameter>tablespace</parameter> <type>oid</type> </optional> )
31131 <returnvalue>setof record</returnvalue>
31132 ( <parameter>name</parameter> <type>text</type>,
31133 <parameter>size</parameter> <type>bigint</type>,
31134 <parameter>modification</parameter> <type>timestamp with time zone</type> )
31135 </para>
31136 <para>
31137 Returns the name, size, and last modification time (mtime) of each
31138 ordinary file in the temporary file directory for the
31139 specified <parameter>tablespace</parameter>.
31140 If <parameter>tablespace</parameter> is not provided,
31141 the <literal>pg_default</literal> tablespace is examined. Filenames
31142 beginning with a dot, directories, and other special files are
31143 excluded.
31144 </para>
31145 <para>
31146 This function is restricted to superusers and members of
31147 the <literal>pg_monitor</literal> role by default, but other users can
31148 be granted EXECUTE to run the function.
31149 </para></entry>
31150 </row>
31151
31152 <row>
31153 <entry role="func_table_entry"><para role="func_signature">
31154 <indexterm>
31155 <primary>pg_read_file</primary>
31156 </indexterm>
31157 <function>pg_read_file</function> ( <parameter>filename</parameter> <type>text</type> <optional>, <parameter>offset</parameter> <type>bigint</type>, <parameter>length</parameter> <type>bigint</type> </optional> <optional>, <parameter>missing_ok</parameter> <type>boolean</type> </optional> )
31158 <returnvalue>text</returnvalue>
31159 </para>
31160 <para>
31161 Returns all or part of a text file, starting at the
31162 given byte <parameter>offset</parameter>, returning at
31163 most <parameter>length</parameter> bytes (less if the end of file is
31164 reached first). If <parameter>offset</parameter> is negative, it is
31165 relative to the end of the file. If <parameter>offset</parameter>
31166 and <parameter>length</parameter> are omitted, the entire file is
31167 returned. The bytes read from the file are interpreted as a string in
31168 the database's encoding; an error is thrown if they are not valid in
31169 that encoding.
31170 </para>
31171 <para>
31172 This function is restricted to superusers by default, but other users
31173 can be granted EXECUTE to run the function.
31174 </para></entry>
31175 </row>
31176
31177 <row>
31178 <entry role="func_table_entry"><para role="func_signature">
31179 <indexterm>
31180 <primary>pg_read_binary_file</primary>
31181 </indexterm>
31182 <function>pg_read_binary_file</function> ( <parameter>filename</parameter> <type>text</type> <optional>, <parameter>offset</parameter> <type>bigint</type>, <parameter>length</parameter> <type>bigint</type> </optional> <optional>, <parameter>missing_ok</parameter> <type>boolean</type> </optional> )
31183 <returnvalue>bytea</returnvalue>
31184 </para>
31185 <para>
31186 Returns all or part of a file. This function is identical to
31187 <function>pg_read_file</function> except that it can read arbitrary
31188 binary data, returning the result as <type>bytea</type>
31189 not <type>text</type>; accordingly, no encoding checks are performed.
31190 </para>
31191 <para>
31192 This function is restricted to superusers by default, but other users
31193 can be granted EXECUTE to run the function.
31194 </para>
31195 <para>
31196 In combination with the <function>convert_from</function> function,
31197 this function can be used to read a text file in a specified encoding
31198 and convert to the database's encoding:
31199 <programlisting>
31200 SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');
31201 </programlisting>
31202 </para></entry>
31203 </row>
31204
31205 <row>
31206 <entry role="func_table_entry"><para role="func_signature">
31207 <indexterm>
31208 <primary>pg_stat_file</primary>
31209 </indexterm>
31210 <function>pg_stat_file</function> ( <parameter>filename</parameter> <type>text</type> <optional>, <parameter>missing_ok</parameter> <type>boolean</type> </optional> )
31211 <returnvalue>record</returnvalue>
31212 ( <parameter>size</parameter> <type>bigint</type>,
31213 <parameter>access</parameter> <type>timestamp with time zone</type>,
31214 <parameter>modification</parameter> <type>timestamp with time zone</type>,
31215 <parameter>change</parameter> <type>timestamp with time zone</type>,
31216 <parameter>creation</parameter> <type>timestamp with time zone</type>,
31217 <parameter>isdir</parameter> <type>boolean</type> )
31218 </para>
31219 <para>
31220 Returns a record containing the file's size, last access time stamp,
31221 last modification time stamp, last file status change time stamp (Unix
31222 platforms only), file creation time stamp (Windows only), and a flag
31223 indicating if it is a directory.
31224 </para>
31225 <para>
31226 This function is restricted to superusers by default, but other users
31227 can be granted EXECUTE to run the function.
31228 </para></entry>
31229 </row>
31230
31231 </tbody>
31232 </tgroup>
31233 </table>
31234
31235 </sect2>
31236
31237 <sect2 id="functions-advisory-locks">
31238 <title>Advisory Lock Functions</title>
31239
31240 <para>
31241 The functions shown in <xref linkend="functions-advisory-locks-table"/>
31242 manage advisory locks. For details about proper use of these functions,
31243 see <xref linkend="advisory-locks"/>.
31244 </para>
31245
31246 <para>
31247 All these functions are intended to be used to lock application-defined
31248 resources, which can be identified either by a single 64-bit key value or
31249 two 32-bit key values (note that these two key spaces do not overlap).
31250 If another session already holds a conflicting lock on the same resource
31251 identifier, the functions will either wait until the resource becomes
31252 available, or return a <literal>false</literal> result, as appropriate for
31253 the function.
31254 Locks can be either shared or exclusive: a shared lock does not conflict
31255 with other shared locks on the same resource, only with exclusive locks.
31256 Locks can be taken at session level (so that they are held until released
31257 or the session ends) or at transaction level (so that they are held until
31258 the current transaction ends; there is no provision for manual release).
31259 Multiple session-level lock requests stack, so that if the same resource
31260 identifier is locked three times there must then be three unlock requests
31261 to release the resource in advance of session end.
31262 </para>
31263
31264 <table id="functions-advisory-locks-table">
31265 <title>Advisory Lock Functions</title>
31266 <tgroup cols="1">
31267 <thead>
31268 <row>
31269 <entry role="func_table_entry"><para role="func_signature">
31270 Function
31271 </para>
31272 <para>
31273 Description
31274 </para></entry>
31275 </row>
31276 </thead>
31277
31278 <tbody>
31279 <row>
31280 <entry role="func_table_entry"><para role="func_signature">
31281 <indexterm>
31282 <primary>pg_advisory_lock</primary>
31283 </indexterm>
31284 <function>pg_advisory_lock</function> ( <parameter>key</parameter> <type>bigint</type> )
31285 <returnvalue>void</returnvalue>
31286 </para>
31287 <para role="func_signature">
31288 <function>pg_advisory_lock</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31289 <returnvalue>void</returnvalue>
31290 </para>
31291 <para>
31292 Obtains an exclusive session-level advisory lock, waiting if necessary.
31293 </para></entry>
31294 </row>
31295
31296 <row>
31297 <entry role="func_table_entry"><para role="func_signature">
31298 <indexterm>
31299 <primary>pg_advisory_lock_shared</primary>
31300 </indexterm>
31301 <function>pg_advisory_lock_shared</function> ( <parameter>key</parameter> <type>bigint</type> )
31302 <returnvalue>void</returnvalue>
31303 </para>
31304 <para role="func_signature">
31305 <function>pg_advisory_lock_shared</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31306 <returnvalue>void</returnvalue>
31307 </para>
31308 <para>
31309 Obtains a shared session-level advisory lock, waiting if necessary.
31310 </para></entry>
31311 </row>
31312
31313 <row>
31314 <entry role="func_table_entry"><para role="func_signature">
31315 <indexterm>
31316 <primary>pg_advisory_unlock</primary>
31317 </indexterm>
31318 <function>pg_advisory_unlock</function> ( <parameter>key</parameter> <type>bigint</type> )
31319 <returnvalue>boolean</returnvalue>
31320 </para>
31321 <para role="func_signature">
31322 <function>pg_advisory_unlock</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31323 <returnvalue>boolean</returnvalue>
31324 </para>
31325 <para>
31326 Releases a previously-acquired exclusive session-level advisory lock.
31327 Returns <literal>true</literal> if the lock is successfully released.
31328 If the lock was not held, <literal>false</literal> is returned, and in
31329 addition, an SQL warning will be reported by the server.
31330 </para></entry>
31331 </row>
31332
31333 <row>
31334 <entry role="func_table_entry"><para role="func_signature">
31335 <indexterm>
31336 <primary>pg_advisory_unlock_all</primary>
31337 </indexterm>
31338 <function>pg_advisory_unlock_all</function> ()
31339 <returnvalue>void</returnvalue>
31340 </para>
31341 <para>
31342 Releases all session-level advisory locks held by the current session.
31343 (This function is implicitly invoked at session end, even if the
31344 client disconnects ungracefully.)
31345 </para></entry>
31346 </row>
31347
31348 <row>
31349 <entry role="func_table_entry"><para role="func_signature">
31350 <indexterm>
31351 <primary>pg_advisory_unlock_shared</primary>
31352 </indexterm>
31353 <function>pg_advisory_unlock_shared</function> ( <parameter>key</parameter> <type>bigint</type> )
31354 <returnvalue>boolean</returnvalue>
31355 </para>
31356 <para role="func_signature">
31357 <function>pg_advisory_unlock_shared</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31358 <returnvalue>boolean</returnvalue>
31359 </para>
31360 <para>
31361 Releases a previously-acquired shared session-level advisory lock.
31362 Returns <literal>true</literal> if the lock is successfully released.
31363 If the lock was not held, <literal>false</literal> is returned, and in
31364 addition, an SQL warning will be reported by the server.
31365 </para></entry>
31366 </row>
31367
31368 <row>
31369 <entry role="func_table_entry"><para role="func_signature">
31370 <indexterm>
31371 <primary>pg_advisory_xact_lock</primary>
31372 </indexterm>
31373 <function>pg_advisory_xact_lock</function> ( <parameter>key</parameter> <type>bigint</type> )
31374 <returnvalue>void</returnvalue>
31375 </para>
31376 <para role="func_signature">
31377 <function>pg_advisory_xact_lock</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31378 <returnvalue>void</returnvalue>
31379 </para>
31380 <para>
31381 Obtains an exclusive transaction-level advisory lock, waiting if
31382 necessary.
31383 </para></entry>
31384 </row>
31385
31386 <row>
31387 <entry role="func_table_entry"><para role="func_signature">
31388 <indexterm>
31389 <primary>pg_advisory_xact_lock_shared</primary>
31390 </indexterm>
31391 <function>pg_advisory_xact_lock_shared</function> ( <parameter>key</parameter> <type>bigint</type> )
31392 <returnvalue>void</returnvalue>
31393 </para>
31394 <para role="func_signature">
31395 <function>pg_advisory_xact_lock_shared</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31396 <returnvalue>void</returnvalue>
31397 </para>
31398 <para>
31399 Obtains a shared transaction-level advisory lock, waiting if
31400 necessary.
31401 </para></entry>
31402 </row>
31403
31404 <row>
31405 <entry role="func_table_entry"><para role="func_signature">
31406 <indexterm>
31407 <primary>pg_try_advisory_lock</primary>
31408 </indexterm>
31409 <function>pg_try_advisory_lock</function> ( <parameter>key</parameter> <type>bigint</type> )
31410 <returnvalue>boolean</returnvalue>
31411 </para>
31412 <para role="func_signature">
31413 <function>pg_try_advisory_lock</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31414 <returnvalue>boolean</returnvalue>
31415 </para>
31416 <para>
31417 Obtains an exclusive session-level advisory lock if available.
31418 This will either obtain the lock immediately and
31419 return <literal>true</literal>, or return <literal>false</literal>
31420 without waiting if the lock cannot be acquired immediately.
31421 </para></entry>
31422 </row>
31423
31424 <row>
31425 <entry role="func_table_entry"><para role="func_signature">
31426 <indexterm>
31427 <primary>pg_try_advisory_lock_shared</primary>
31428 </indexterm>
31429 <function>pg_try_advisory_lock_shared</function> ( <parameter>key</parameter> <type>bigint</type> )
31430 <returnvalue>boolean</returnvalue>
31431 </para>
31432 <para role="func_signature">
31433 <function>pg_try_advisory_lock_shared</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31434 <returnvalue>boolean</returnvalue>
31435 </para>
31436 <para>
31437 Obtains a shared session-level advisory lock if available.
31438 This will either obtain the lock immediately and
31439 return <literal>true</literal>, or return <literal>false</literal>
31440 without waiting if the lock cannot be acquired immediately.
31441 </para></entry>
31442 </row>
31443
31444 <row>
31445 <entry role="func_table_entry"><para role="func_signature">
31446 <indexterm>
31447 <primary>pg_try_advisory_xact_lock</primary>
31448 </indexterm>
31449 <function>pg_try_advisory_xact_lock</function> ( <parameter>key</parameter> <type>bigint</type> )
31450 <returnvalue>boolean</returnvalue>
31451 </para>
31452 <para role="func_signature">
31453 <function>pg_try_advisory_xact_lock</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31454 <returnvalue>boolean</returnvalue>
31455 </para>
31456 <para>
31457 Obtains an exclusive transaction-level advisory lock if available.
31458 This will either obtain the lock immediately and
31459 return <literal>true</literal>, or return <literal>false</literal>
31460 without waiting if the lock cannot be acquired immediately.
31461 </para></entry>
31462 </row>
31463
31464 <row>
31465 <entry role="func_table_entry"><para role="func_signature">
31466 <indexterm>
31467 <primary>pg_try_advisory_xact_lock_shared</primary>
31468 </indexterm>
31469 <function>pg_try_advisory_xact_lock_shared</function> ( <parameter>key</parameter> <type>bigint</type> )
31470 <returnvalue>boolean</returnvalue>
31471 </para>
31472 <para role="func_signature">
31473 <function>pg_try_advisory_xact_lock_shared</function> ( <parameter>key1</parameter> <type>integer</type>, <parameter>key2</parameter> <type>integer</type> )
31474 <returnvalue>boolean</returnvalue>
31475 </para>
31476 <para>
31477 Obtains a shared transaction-level advisory lock if available.
31478 This will either obtain the lock immediately and
31479 return <literal>true</literal>, or return <literal>false</literal>
31480 without waiting if the lock cannot be acquired immediately.
31481 </para></entry>
31482 </row>
31483 </tbody>
31484 </tgroup>
31485 </table>
31486
31487 </sect2>
31488
31489 </sect1>
31490
31491 <sect1 id="functions-trigger">
31492 <title>Trigger Functions</title>
31493
31494 <para>
31495 While many uses of triggers involve user-written trigger functions,
31496 <productname>PostgreSQL</productname> provides a few built-in trigger
31497 functions that can be used directly in user-defined triggers. These
31498 are summarized in <xref linkend="builtin-triggers-table"/>.
31499 (Additional built-in trigger functions exist, which implement foreign
31500 key constraints and deferred index constraints. Those are not documented
31501 here since users need not use them directly.)
31502 </para>
31503
31504 <para>
31505 For more information about creating triggers, see
31506 <xref linkend="sql-createtrigger"/>.
31507 </para>
31508
31509 <table id="builtin-triggers-table">
31510 <title>Built-In Trigger Functions</title>
31511 <tgroup cols="1">
31512 <thead>
31513 <row>
31514 <entry role="func_table_entry"><para role="func_signature">
31515 Function
31516 </para>
31517 <para>
31518 Description
31519 </para>
31520 <para>
31521 Example Usage
31522 </para></entry>
31523 </row>
31524 </thead>
31525
31526 <tbody>
31527 <row>
31528 <entry role="func_table_entry"><para role="func_signature">
31529 <indexterm>
31530 <primary>suppress_redundant_updates_trigger</primary>
31531 </indexterm>
31532 <function>suppress_redundant_updates_trigger</function> ( )
31533 <returnvalue>trigger</returnvalue>
31534 </para>
31535 <para>
31536 Suppresses do-nothing update operations. See below for details.
31537 </para>
31538 <para>
31539 <literal>CREATE TRIGGER ... suppress_redundant_updates_trigger()</literal>
31540 </para></entry>
31541 </row>
31542
31543 <row>
31544 <entry role="func_table_entry"><para role="func_signature">
31545 <indexterm>
31546 <primary>tsvector_update_trigger</primary>
31547 </indexterm>
31548 <function>tsvector_update_trigger</function> ( )
31549 <returnvalue>trigger</returnvalue>
31550 </para>
31551 <para>
31552 Automatically updates a <type>tsvector</type> column from associated
31553 plain-text document column(s). The text search configuration to use
31554 is specified by name as a trigger argument. See
31555 <xref linkend="textsearch-update-triggers"/> for details.
31556 </para>
31557 <para>
31558 <literal>CREATE TRIGGER ... tsvector_update_trigger(tsvcol, 'pg_catalog.swedish', title, body)</literal>
31559 </para></entry>
31560 </row>
31561
31562 <row>
31563 <entry role="func_table_entry"><para role="func_signature">
31564 <indexterm>
31565 <primary>tsvector_update_trigger_column</primary>
31566 </indexterm>
31567 <function>tsvector_update_trigger_column</function> ( )
31568 <returnvalue>trigger</returnvalue>
31569 </para>
31570 <para>
31571 Automatically updates a <type>tsvector</type> column from associated
31572 plain-text document column(s). The text search configuration to use
31573 is taken from a <type>regconfig</type> column of the table. See
31574 <xref linkend="textsearch-update-triggers"/> for details.
31575 </para>
31576 <para>
31577 <literal>CREATE TRIGGER ... tsvector_update_trigger_column(tsvcol, tsconfigcol, title, body)</literal>
31578 </para></entry>
31579 </row>
31580 </tbody>
31581 </tgroup>
31582 </table>
31583
31584 <para>
31585 The <function>suppress_redundant_updates_trigger</function> function,
31586 when applied as a row-level <literal>BEFORE UPDATE</literal> trigger,
31587 will prevent any update that does not actually change the data in the
31588 row from taking place. This overrides the normal behavior which always
31589 performs a physical row update
31590 regardless of whether or not the data has changed. (This normal behavior
31591 makes updates run faster, since no checking is required, and is also
31592 useful in certain cases.)
31593 </para>
31594
31595 <para>
31596 Ideally, you should avoid running updates that don't actually
31597 change the data in the record. Redundant updates can cost considerable
31598 unnecessary time, especially if there are lots of indexes to alter,
31599 and space in dead rows that will eventually have to be vacuumed.
31600 However, detecting such situations in client code is not
31601 always easy, or even possible, and writing expressions to detect
31602 them can be error-prone. An alternative is to use
31603 <function>suppress_redundant_updates_trigger</function>, which will skip
31604 updates that don't change the data. You should use this with care,
31605 however. The trigger takes a small but non-trivial time for each record,
31606 so if most of the records affected by updates do actually change,
31607 use of this trigger will make updates run slower on average.
31608 </para>
31609
31610 <para>
31611 The <function>suppress_redundant_updates_trigger</function> function can be
31612 added to a table like this:
31613 <programlisting>
31614 CREATE TRIGGER z_min_update
31615 BEFORE UPDATE ON tablename
31616 FOR EACH ROW EXECUTE FUNCTION suppress_redundant_updates_trigger();
31617 </programlisting>
31618 In most cases, you need to fire this trigger last for each row, so that
31619 it does not override other triggers that might wish to alter the row.
31620 Bearing in mind that triggers fire in name order, you would therefore
31621 choose a trigger name that comes after the name of any other trigger
31622 you might have on the table. (Hence the <quote>z</quote> prefix in the
31623 example.)
31624 </para>
31625 </sect1>
31626
31627 <sect1 id="functions-event-triggers">
31628 <title>Event Trigger Functions</title>
31629
31630 <para>
31631 <productname>PostgreSQL</productname> provides these helper functions
31632 to retrieve information from event triggers.
31633 </para>
31634
31635 <para>
31636 For more information about event triggers,
31637 see <xref linkend="event-triggers"/>.
31638 </para>
31639
31640 <sect2 id="pg-event-trigger-ddl-command-end-functions">
31641 <title>Capturing Changes at Command End</title>
31642
31643 <indexterm>
31644 <primary>pg_event_trigger_ddl_commands</primary>
31645 </indexterm>
31646
31647 <synopsis>
31648 <function>pg_event_trigger_ddl_commands</function> () <returnvalue>setof record</returnvalue>
31649 </synopsis>
31650
31651 <para>
31652 <function>pg_event_trigger_ddl_commands</function> returns a list of
31653 <acronym>DDL</acronym> commands executed by each user action,
31654 when invoked in a function attached to a
31655 <literal>ddl_command_end</literal> event trigger. If called in any other
31656 context, an error is raised.
31657 <function>pg_event_trigger_ddl_commands</function> returns one row for each
31658 base command executed; some commands that are a single SQL sentence
31659 may return more than one row. This function returns the following
31660 columns:
31661
31662 <informaltable>
31663 <tgroup cols="3">
31664 <thead>
31665 <row>
31666 <entry>Name</entry>
31667 <entry>Type</entry>
31668 <entry>Description</entry>
31669 </row>
31670 </thead>
31671
31672 <tbody>
31673 <row>
31674 <entry><literal>classid</literal></entry>
31675 <entry><type>oid</type></entry>
31676 <entry>OID of catalog the object belongs in</entry>
31677 </row>
31678 <row>
31679 <entry><literal>objid</literal></entry>
31680 <entry><type>oid</type></entry>
31681 <entry>OID of the object itself</entry>
31682 </row>
31683 <row>
31684 <entry><literal>objsubid</literal></entry>
31685 <entry><type>integer</type></entry>
31686 <entry>Sub-object ID (e.g., attribute number for a column)</entry>
31687 </row>
31688 <row>
31689 <entry><literal>command_tag</literal></entry>
31690 <entry><type>text</type></entry>
31691 <entry>Command tag</entry>
31692 </row>
31693 <row>
31694 <entry><literal>object_type</literal></entry>
31695 <entry><type>text</type></entry>
31696 <entry>Type of the object</entry>
31697 </row>
31698 <row>
31699 <entry><literal>schema_name</literal></entry>
31700 <entry><type>text</type></entry>
31701 <entry>
31702 Name of the schema the object belongs in, if any; otherwise <literal>NULL</literal>.
31703 No quoting is applied.
31704 </entry>
31705 </row>
31706 <row>
31707 <entry><literal>object_identity</literal></entry>
31708 <entry><type>text</type></entry>
31709 <entry>
31710 Text rendering of the object identity, schema-qualified. Each
31711 identifier included in the identity is quoted if necessary.
31712 </entry>
31713 </row>
31714 <row>
31715 <entry><literal>in_extension</literal></entry>
31716 <entry><type>boolean</type></entry>
31717 <entry>True if the command is part of an extension script</entry>
31718 </row>
31719 <row>
31720 <entry><literal>command</literal></entry>
31721 <entry><type>pg_ddl_command</type></entry>
31722 <entry>
31723 A complete representation of the command, in internal format.
31724 This cannot be output directly, but it can be passed to other
31725 functions to obtain different pieces of information about the
31726 command.
31727 </entry>
31728 </row>
31729 </tbody>
31730 </tgroup>
31731 </informaltable>
31732 </para>
31733 </sect2>
31734
31735 <sect2 id="pg-event-trigger-sql-drop-functions">
31736 <title>Processing Objects Dropped by a DDL Command</title>
31737
31738 <indexterm>
31739 <primary>pg_event_trigger_dropped_objects</primary>
31740 </indexterm>
31741
31742 <synopsis>
31743 <function>pg_event_trigger_dropped_objects</function> () <returnvalue>setof record</returnvalue>
31744 </synopsis>
31745
31746 <para>
31747 <function>pg_event_trigger_dropped_objects</function> returns a list of all objects
31748 dropped by the command in whose <literal>sql_drop</literal> event it is called.
31749 If called in any other context, an error is raised.
31750 This function returns the following columns:
31751
31752 <informaltable>
31753 <tgroup cols="3">
31754 <thead>
31755 <row>
31756 <entry>Name</entry>
31757 <entry>Type</entry>
31758 <entry>Description</entry>
31759 </row>
31760 </thead>
31761
31762 <tbody>
31763 <row>
31764 <entry><literal>classid</literal></entry>
31765 <entry><type>oid</type></entry>
31766 <entry>OID of catalog the object belonged in</entry>
31767 </row>
31768 <row>
31769 <entry><literal>objid</literal></entry>
31770 <entry><type>oid</type></entry>
31771 <entry>OID of the object itself</entry>
31772 </row>
31773 <row>
31774 <entry><literal>objsubid</literal></entry>
31775 <entry><type>integer</type></entry>
31776 <entry>Sub-object ID (e.g., attribute number for a column)</entry>
31777 </row>
31778 <row>
31779 <entry><literal>original</literal></entry>
31780 <entry><type>boolean</type></entry>
31781 <entry>True if this was one of the root object(s) of the deletion</entry>
31782 </row>
31783 <row>
31784 <entry><literal>normal</literal></entry>
31785 <entry><type>boolean</type></entry>
31786 <entry>
31787 True if there was a normal dependency relationship
31788 in the dependency graph leading to this object
31789 </entry>
31790 </row>
31791 <row>
31792 <entry><literal>is_temporary</literal></entry>
31793 <entry><type>boolean</type></entry>
31794 <entry>
31795 True if this was a temporary object
31796 </entry>
31797 </row>
31798 <row>
31799 <entry><literal>object_type</literal></entry>
31800 <entry><type>text</type></entry>
31801 <entry>Type of the object</entry>
31802 </row>
31803 <row>
31804 <entry><literal>schema_name</literal></entry>
31805 <entry><type>text</type></entry>
31806 <entry>
31807 Name of the schema the object belonged in, if any; otherwise <literal>NULL</literal>.
31808 No quoting is applied.
31809 </entry>
31810 </row>
31811 <row>
31812 <entry><literal>object_name</literal></entry>
31813 <entry><type>text</type></entry>
31814 <entry>
31815 Name of the object, if the combination of schema and name can be
31816 used as a unique identifier for the object; otherwise <literal>NULL</literal>.
31817 No quoting is applied, and name is never schema-qualified.
31818 </entry>
31819 </row>
31820 <row>
31821 <entry><literal>object_identity</literal></entry>
31822 <entry><type>text</type></entry>
31823 <entry>
31824 Text rendering of the object identity, schema-qualified. Each
31825 identifier included in the identity is quoted if necessary.
31826 </entry>
31827 </row>
31828 <row>
31829 <entry><literal>address_names</literal></entry>
31830 <entry><type>text[]</type></entry>
31831 <entry>
31832 An array that, together with <literal>object_type</literal> and
31833 <literal>address_args</literal>, can be used by
31834 the <function>pg_get_object_address</function> function to
31835 recreate the object address in a remote server containing an
31836 identically named object of the same kind.
31837 </entry>
31838 </row>
31839 <row>
31840 <entry><literal>address_args</literal></entry>
31841 <entry><type>text[]</type></entry>
31842 <entry>
31843 Complement for <literal>address_names</literal>
31844 </entry>
31845 </row>
31846 </tbody>
31847 </tgroup>
31848 </informaltable>
31849 </para>
31850
31851 <para>
31852 The <function>pg_event_trigger_dropped_objects</function> function can be used
31853 in an event trigger like this:
31854 <programlisting>
31855 CREATE FUNCTION test_event_trigger_for_drops()
31856 RETURNS event_trigger LANGUAGE plpgsql AS $$
31857 DECLARE
31858 obj record;
31859 BEGIN
31860 FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects()
31861 LOOP
31862 RAISE NOTICE '% dropped object: % %.% %',
31863 tg_tag,
31864 obj.object_type,
31865 obj.schema_name,
31866 obj.object_name,
31867 obj.object_identity;
31868 END LOOP;
31869 END;
31870 $$;
31871 CREATE EVENT TRIGGER test_event_trigger_for_drops
31872 ON sql_drop
31873 EXECUTE FUNCTION test_event_trigger_for_drops();
31874 </programlisting>
31875 </para>
31876 </sect2>
31877
31878 <sect2 id="pg-event-trigger-table-rewrite-functions">
31879 <title>Handling a Table Rewrite Event</title>
31880
31881 <para>
31882 The functions shown in
31883 <xref linkend="functions-event-trigger-table-rewrite"/>
31884 provide information about a table for which a
31885 <literal>table_rewrite</literal> event has just been called.
31886 If called in any other context, an error is raised.
31887 </para>
31888
31889 <table id="functions-event-trigger-table-rewrite">
31890 <title>Table Rewrite Information Functions</title>
31891 <tgroup cols="1">
31892 <thead>
31893 <row>
31894 <entry role="func_table_entry"><para role="func_signature">
31895 Function
31896 </para>
31897 <para>
31898 Description
31899 </para></entry>
31900 </row>
31901 </thead>
31902
31903 <tbody>
31904 <row>
31905 <entry role="func_table_entry"><para role="func_signature">
31906 <indexterm>
31907 <primary>pg_event_trigger_table_rewrite_oid</primary>
31908 </indexterm>
31909 <function>pg_event_trigger_table_rewrite_oid</function> ()
31910 <returnvalue>oid</returnvalue>
31911 </para>
31912 <para>
31913 Returns the OID of the table about to be rewritten.
31914 </para></entry>
31915 </row>
31916
31917 <row>
31918 <entry role="func_table_entry"><para role="func_signature">
31919 <indexterm>
31920 <primary>pg_event_trigger_table_rewrite_reason</primary>
31921 </indexterm>
31922 <function>pg_event_trigger_table_rewrite_reason</function> ()
31923 <returnvalue>integer</returnvalue>
31924 </para>
31925 <para>
31926 Returns a code explaining the reason(s) for rewriting. The value is
31927 a bitmap built from the following values: <literal>1</literal>
31928 (the table has changed its persistence), <literal>2</literal>
31929 (default value of a column has changed), <literal>4</literal>
31930 (a column has a new data type) and <literal>8</literal>
31931 (the table access method has changed).
31932 </para></entry>
31933 </row>
31934 </tbody>
31935 </tgroup>
31936 </table>
31937
31938 <para>
31939 These functions can be used in an event trigger like this:
31940 <programlisting>
31941 CREATE FUNCTION test_event_trigger_table_rewrite_oid()
31942 RETURNS event_trigger
31943 LANGUAGE plpgsql AS
31944 $$
31945 BEGIN
31946 RAISE NOTICE 'rewriting table % for reason %',
31947 pg_event_trigger_table_rewrite_oid()::regclass,
31948 pg_event_trigger_table_rewrite_reason();
31949 END;
31950 $$;
31951
31952 CREATE EVENT TRIGGER test_table_rewrite_oid
31953 ON table_rewrite
31954 EXECUTE FUNCTION test_event_trigger_table_rewrite_oid();
31955 </programlisting>
31956 </para>
31957 </sect2>
31958 </sect1>
31959
31960 <sect1 id="functions-statistics">
31961 <title>Statistics Information Functions</title>
31962
31963 <indexterm zone="functions-statistics">
31964 <primary>function</primary>
31965 <secondary>statistics</secondary>
31966 </indexterm>
31967
31968 <para>
31969 <productname>PostgreSQL</productname> provides a function to inspect complex
31970 statistics defined using the <command>CREATE STATISTICS</command> command.
31971 </para>
31972
31973 <sect2 id="functions-statistics-mcv">
31974 <title>Inspecting MCV Lists</title>
31975
31976 <indexterm>
31977 <primary>pg_mcv_list_items</primary>
31978 </indexterm>
31979
31980 <synopsis>
31981 <function>pg_mcv_list_items</function> ( <type>pg_mcv_list</type> ) <returnvalue>setof record</returnvalue>
31982 </synopsis>
31983
31984 <para>
31985 <function>pg_mcv_list_items</function> returns a set of records describing
31986 all items stored in a multi-column <acronym>MCV</acronym> list. It
31987 returns the following columns:
31988
31989 <informaltable>
31990 <tgroup cols="3">
31991 <thead>
31992 <row>
31993 <entry>Name</entry>
31994 <entry>Type</entry>
31995 <entry>Description</entry>
31996 </row>
31997 </thead>
31998
31999 <tbody>
32000 <row>
32001 <entry><literal>index</literal></entry>
32002 <entry><type>integer</type></entry>
32003 <entry>index of the item in the <acronym>MCV</acronym> list</entry>
32004 </row>
32005 <row>
32006 <entry><literal>values</literal></entry>
32007 <entry><type>text[]</type></entry>
32008 <entry>values stored in the MCV item</entry>
32009 </row>
32010 <row>
32011 <entry><literal>nulls</literal></entry>
32012 <entry><type>boolean[]</type></entry>
32013 <entry>flags identifying <literal>NULL</literal> values</entry>
32014 </row>
32015 <row>
32016 <entry><literal>frequency</literal></entry>
32017 <entry><type>double precision</type></entry>
32018 <entry>frequency of this <acronym>MCV</acronym> item</entry>
32019 </row>
32020 <row>
32021 <entry><literal>base_frequency</literal></entry>
32022 <entry><type>double precision</type></entry>
32023 <entry>base frequency of this <acronym>MCV</acronym> item</entry>
32024 </row>
32025 </tbody>
32026 </tgroup>
32027 </informaltable>
32028 </para>
32029
32030 <para>
32031 The <function>pg_mcv_list_items</function> function can be used like this:
32032
32033 <programlisting>
32034 SELECT m.* FROM pg_statistic_ext join pg_statistic_ext_data on (oid = stxoid),
32035 pg_mcv_list_items(stxdmcv) m WHERE stxname = 'stts';
32036 </programlisting>
32037
32038 Values of the <type>pg_mcv_list</type> type can be obtained only from the
32039 <structname>pg_statistic_ext_data</structname>.<structfield>stxdmcv</structfield>
32040 column.
32041 </para>
32042 </sect2>
32043
32044 </sect1>
32045
32046 </chapter>