Fix spelling error in docs.
[PostgreSQL.git] / doc / src / sgml / typeconv.sgml
blobf5f33a76e5135d9a2b0b5f2ef24493d4d8e9339f
1 <!-- $PostgreSQL$ -->
3 <chapter Id="typeconv">
4 <title>Type Conversion</title>
6 <indexterm zone="typeconv">
7 <primary>data type</primary>
8 <secondary>conversion</secondary>
9 </indexterm>
11 <para>
12 <acronym>SQL</acronym> statements can, intentionally or not, require
13 mixing of different data types in the same expression.
14 <productname>PostgreSQL</productname> has extensive facilities for
15 evaluating mixed-type expressions.
16 </para>
18 <para>
19 In many cases a user will not need
20 to understand the details of the type conversion mechanism.
21 However, the implicit conversions done by <productname>PostgreSQL</productname>
22 can affect the results of a query. When necessary, these results
23 can be tailored by using <emphasis>explicit</emphasis> type conversion.
24 </para>
26 <para>
27 This chapter introduces the <productname>PostgreSQL</productname>
28 type conversion mechanisms and conventions.
29 Refer to the relevant sections in <xref linkend="datatype"> and <xref linkend="functions">
30 for more information on specific data types and allowed functions and
31 operators.
32 </para>
34 <sect1 id="typeconv-overview">
35 <title>Overview</title>
37 <para>
38 <acronym>SQL</acronym> is a strongly typed language. That is, every data item
39 has an associated data type which determines its behavior and allowed usage.
40 <productname>PostgreSQL</productname> has an extensible type system that is
41 much more general and flexible than other <acronym>SQL</acronym> implementations.
42 Hence, most type conversion behavior in <productname>PostgreSQL</productname>
43 is governed by general rules rather than by <foreignphrase>ad hoc</>
44 heuristics. This allows
45 mixed-type expressions to be meaningful even with user-defined types.
46 </para>
48 <para>
49 The <productname>PostgreSQL</productname> scanner/parser divides lexical
50 elements into only five fundamental categories: integers, non-integer numbers,
51 strings, identifiers, and key words. Constants of most non-numeric types are
52 first classified as strings. The <acronym>SQL</acronym> language definition
53 allows specifying type names with strings, and this mechanism can be used in
54 <productname>PostgreSQL</productname> to start the parser down the correct
55 path. For example, the query
57 <screen>
58 SELECT text 'Origin' AS "label", point '(0,0)' AS "value";
60 label | value
61 --------+-------
62 Origin | (0,0)
63 (1 row)
64 </screen>
66 has two literal constants, of type <type>text</type> and <type>point</type>.
67 If a type is not specified for a string literal, then the placeholder type
68 <type>unknown</type> is assigned initially, to be resolved in later
69 stages as described below.
70 </para>
72 <para>
73 There are four fundamental <acronym>SQL</acronym> constructs requiring
74 distinct type conversion rules in the <productname>PostgreSQL</productname>
75 parser:
77 <variablelist>
78 <varlistentry>
79 <term>
80 Function calls
81 </term>
82 <listitem>
83 <para>
84 Much of the <productname>PostgreSQL</productname> type system is built around a
85 rich set of functions. Functions can have one or more arguments.
86 Since <productname>PostgreSQL</productname> permits function
87 overloading, the function name alone does not uniquely identify the function
88 to be called; the parser must select the right function based on the data
89 types of the supplied arguments.
90 </para>
91 </listitem>
92 </varlistentry>
93 <varlistentry>
94 <term>
95 Operators
96 </term>
97 <listitem>
98 <para>
99 <productname>PostgreSQL</productname> allows expressions with
100 prefix and postfix unary (one-argument) operators,
101 as well as binary (two-argument) operators. Like functions, operators can
102 be overloaded, and so the same problem of selecting the right operator
103 exists.
104 </para>
105 </listitem>
106 </varlistentry>
107 <varlistentry>
108 <term>
109 Value Storage
110 </term>
111 <listitem>
112 <para>
113 <acronym>SQL</acronym> <command>INSERT</command> and <command>UPDATE</command> statements place the results of
114 expressions into a table. The expressions in the statement must be matched up
115 with, and perhaps converted to, the types of the target columns.
116 </para>
117 </listitem>
118 </varlistentry>
119 <varlistentry>
120 <term>
121 <literal>UNION</literal>, <literal>CASE</literal>, and related constructs
122 </term>
123 <listitem>
124 <para>
125 Since all query results from a unionized <command>SELECT</command> statement
126 must appear in a single set of columns, the types of the results of each
127 <command>SELECT</> clause must be matched up and converted to a uniform set.
128 Similarly, the result expressions of a <literal>CASE</> construct must be
129 converted to a common type so that the <literal>CASE</> expression as a whole
130 has a known output type. The same holds for <literal>ARRAY</> constructs,
131 and for the <function>GREATEST</> and <function>LEAST</> functions.
132 </para>
133 </listitem>
134 </varlistentry>
135 </variablelist>
136 </para>
138 <para>
139 The system catalogs store information about which conversions, called
140 <firstterm>casts</firstterm>, between data types are valid, and how to
141 perform those conversions. Additional casts can be added by the user
142 with the <xref linkend="sql-createcast" endterm="sql-createcast-title">
143 command. (This is usually
144 done in conjunction with defining new data types. The set of casts
145 between the built-in types has been carefully crafted and is best not
146 altered.)
147 </para>
149 <indexterm>
150 <primary>data type</primary>
151 <secondary>category</secondary>
152 </indexterm>
154 <para>
155 An additional heuristic is provided in the parser to allow better guesses
156 at proper casting behavior among groups of types that have implicit casts.
157 Data types are divided into several basic <firstterm>type
158 categories</firstterm>, including <type>boolean</type>, <type>numeric</type>,
159 <type>string</type>, <type>bitstring</type>, <type>datetime</type>,
160 <type>timespan</type>, <type>geometric</type>, <type>network</type>, and
161 user-defined. (For a list see <xref linkend="catalog-typcategory-table">;
162 but note it is also possible to create custom type categories.) Within each
163 category there can be one or more <firstterm>preferred types</firstterm>, which
164 are preferentially selected when there is ambiguity. With careful selection
165 of preferred types and available implicit casts, it is possible to ensure that
166 ambiguous expressions (those with multiple candidate parsing solutions) can be
167 resolved in a useful way.
168 </para>
170 <para>
171 All type conversion rules are designed with several principles in mind:
173 <itemizedlist>
174 <listitem>
175 <para>
176 Implicit conversions should never have surprising or unpredictable outcomes.
177 </para>
178 </listitem>
180 <listitem>
181 <para>
182 There should be no extra overhead from the parser or executor
183 if a query does not need implicit type conversion.
184 That is, if a query is well formulated and the types already match up, then the query should proceed
185 without spending extra time in the parser and without introducing unnecessary implicit conversion
186 calls into the query.
187 </para>
189 <para>
190 Additionally, if a query usually requires an implicit conversion for a function, and
191 if then the user defines a new function with the correct argument types, the parser
192 should use this new function and will no longer do the implicit conversion using the old function.
193 </para>
194 </listitem>
195 </itemizedlist>
196 </para>
198 </sect1>
200 <sect1 id="typeconv-oper">
201 <title>Operators</title>
203 <indexterm zone="typeconv-oper">
204 <primary>operator</primary>
205 <secondary>type resolution in an invocation</secondary>
206 </indexterm>
208 <para>
209 The specific operator to be used in an operator invocation is determined
210 by following
211 the procedure below. Note that this procedure is indirectly affected
212 by the precedence of the involved operators. See <xref
213 linkend="sql-precedence"> for more information.
214 </para>
216 <procedure>
217 <title>Operator Type Resolution</title>
219 <step performance="required">
220 <para>
221 Select the operators to be considered from the
222 <classname>pg_operator</classname> system catalog. If an unqualified
223 operator name was used (the usual case), the operators
224 considered are those of the right name and argument count that are
225 visible in the current search path (see <xref linkend="ddl-schemas-path">).
226 If a qualified operator name was given, only operators in the specified
227 schema are considered.
228 </para>
230 <substeps>
231 <step performance="optional">
232 <para>
233 If the search path finds multiple operators of identical argument types,
234 only the one appearing earliest in the path is considered. But operators of
235 different argument types are considered on an equal footing regardless of
236 search path position.
237 </para>
238 </step>
239 </substeps>
240 </step>
242 <step performance="required">
243 <para>
244 Check for an operator accepting exactly the input argument types.
245 If one exists (there can be only one exact match in the set of
246 operators considered), use it.
247 </para>
249 <substeps>
250 <step performance="optional">
251 <para>
252 If one argument of a binary operator invocation is of the <type>unknown</type> type,
253 then assume it is the same type as the other argument for this check.
254 Other cases involving <type>unknown</type> will never find a match at
255 this step.
256 </para>
257 </step>
258 </substeps>
259 </step>
261 <step performance="required">
262 <para>
263 Look for the best match.
264 </para>
265 <substeps>
266 <step performance="required">
267 <para>
268 Discard candidate operators for which the input types do not match
269 and cannot be converted (using an implicit conversion) to match.
270 <type>unknown</type> literals are
271 assumed to be convertible to anything for this purpose. If only one
272 candidate remains, use it; else continue to the next step.
273 </para>
274 </step>
275 <step performance="required">
276 <para>
277 Run through all candidates and keep those with the most exact matches
278 on input types. (Domains are considered the same as their base type
279 for this purpose.) Keep all candidates if none have any exact matches.
280 If only one candidate remains, use it; else continue to the next step.
281 </para>
282 </step>
283 <step performance="required">
284 <para>
285 Run through all candidates and keep those that accept preferred types (of the
286 input data type's type category) at the most positions where type conversion
287 will be required.
288 Keep all candidates if none accept preferred types.
289 If only one candidate remains, use it; else continue to the next step.
290 </para>
291 </step>
292 <step performance="required">
293 <para>
294 If any input arguments are <type>unknown</type>, check the type
295 categories accepted at those argument positions by the remaining
296 candidates. At each position, select the <type>string</type> category
297 if any
298 candidate accepts that category. (This bias towards string is appropriate
299 since an unknown-type literal does look like a string.) Otherwise, if
300 all the remaining candidates accept the same type category, select that
301 category; otherwise fail because the correct choice cannot be deduced
302 without more clues. Now discard
303 candidates that do not accept the selected type category. Furthermore,
304 if any candidate accepts a preferred type in that category,
305 discard candidates that accept non-preferred types for that argument.
306 </para>
307 </step>
308 <step performance="required">
309 <para>
310 If only one candidate remains, use it. If no candidate or more than one
311 candidate remains,
312 then fail.
313 </para>
314 </step>
315 </substeps>
316 </step>
317 </procedure>
319 <para>
320 Some examples follow.
321 </para>
323 <example>
324 <title>Factorial Operator Type Resolution</title>
326 <para>
327 There is only one factorial operator (postfix <literal>!</>)
328 defined in the standard catalog, and it takes an argument of type
329 <type>bigint</type>.
330 The scanner assigns an initial type of <type>integer</type> to the argument
331 in this query expression:
332 <screen>
333 SELECT 40 ! AS "40 factorial";
335 40 factorial
336 --------------------------------------------------
337 815915283247897734345611269596115894272000000000
338 (1 row)
339 </screen>
341 So the parser does a type conversion on the operand and the query
342 is equivalent to
344 <screen>
345 SELECT CAST(40 AS bigint) ! AS "40 factorial";
346 </screen>
347 </para>
348 </example>
350 <example>
351 <title>String Concatenation Operator Type Resolution</title>
353 <para>
354 A string-like syntax is used for working with string types as well as for
355 working with complex extension types.
356 Strings with unspecified type are matched with likely operator candidates.
357 </para>
359 <para>
360 An example with one unspecified argument:
361 <screen>
362 SELECT text 'abc' || 'def' AS "text and unknown";
364 text and unknown
365 ------------------
366 abcdef
367 (1 row)
368 </screen>
369 </para>
371 <para>
372 In this case the parser looks to see if there is an operator taking <type>text</type>
373 for both arguments. Since there is, it assumes that the second argument should
374 be interpreted as of type <type>text</type>.
375 </para>
377 <para>
378 Here is a concatenation on unspecified types:
379 <screen>
380 SELECT 'abc' || 'def' AS "unspecified";
382 unspecified
383 -------------
384 abcdef
385 (1 row)
386 </screen>
387 </para>
389 <para>
390 In this case there is no initial hint for which type to use, since no types
391 are specified in the query. So, the parser looks for all candidate operators
392 and finds that there are candidates accepting both string-category and
393 bit-string-category inputs. Since string category is preferred when available,
394 that category is selected, and then the
395 preferred type for strings, <type>text</type>, is used as the specific
396 type to resolve the unknown literals to.
397 </para>
398 </example>
400 <example>
401 <title>Absolute-Value and Negation Operator Type Resolution</title>
403 <para>
404 The <productname>PostgreSQL</productname> operator catalog has several
405 entries for the prefix operator <literal>@</>, all of which implement
406 absolute-value operations for various numeric data types. One of these
407 entries is for type <type>float8</type>, which is the preferred type in
408 the numeric category. Therefore, <productname>PostgreSQL</productname>
409 will use that entry when faced with an <type>unknown</> input:
410 <screen>
411 SELECT @ '-4.5' AS "abs";
413 -----
415 (1 row)
416 </screen>
417 Here the system has implicitly resolved the unknown-type literal as type
418 <type>float8</type> before applying the chosen operator. We can verify that
419 <type>float8</type> and not some other type was used:
420 <screen>
421 SELECT @ '-4.5e500' AS "abs";
423 ERROR: "-4.5e500" is out of range for type double precision
424 </screen>
425 </para>
427 <para>
428 On the other hand, the prefix operator <literal>~</> (bitwise negation)
429 is defined only for integer data types, not for <type>float8</type>. So, if we
430 try a similar case with <literal>~</>, we get:
431 <screen>
432 SELECT ~ '20' AS "negation";
434 ERROR: operator is not unique: ~ "unknown"
435 HINT: Could not choose a best candidate operator. You might need to add
436 explicit type casts.
437 </screen>
438 This happens because the system cannot decide which of the several
439 possible <literal>~</> operators should be preferred. We can help
440 it out with an explicit cast:
441 <screen>
442 SELECT ~ CAST('20' AS int8) AS "negation";
444 negation
445 ----------
447 (1 row)
448 </screen>
449 </para>
450 </example>
452 </sect1>
454 <sect1 id="typeconv-func">
455 <title>Functions</title>
457 <indexterm zone="typeconv-func">
458 <primary>function</primary>
459 <secondary>type resolution in an invocation</secondary>
460 </indexterm>
462 <para>
463 The specific function to be used in a function invocation is determined
464 according to the following steps.
465 </para>
467 <procedure>
468 <title>Function Type Resolution</title>
470 <step performance="required">
471 <para>
472 Select the functions to be considered from the
473 <classname>pg_proc</classname> system catalog. If an unqualified
474 function name was used, the functions
475 considered are those of the right name and argument count that are
476 visible in the current search path (see <xref linkend="ddl-schemas-path">).
477 If a qualified function name was given, only functions in the specified
478 schema are considered.
479 </para>
481 <substeps>
482 <step performance="optional">
483 <para>
484 If the search path finds multiple functions of identical argument types,
485 only the one appearing earliest in the path is considered. But functions of
486 different argument types are considered on an equal footing regardless of
487 search path position.
488 </para>
489 </step>
490 <step performance="optional">
491 <para>
492 If a function is declared with a <literal>VARIADIC</> array parameter, and
493 the call does not use the <literal>VARIADIC</> keyword, then the function
494 is treated as if the array parameter were replaced by one or more occurrences
495 of its element type, as needed to match the call. After such expansion the
496 function might have effective argument types identical to some non-variadic
497 function. In that case the function appearing earlier in the search path is
498 used, or if the two functions are in the same schema, the non-variadic one is
499 preferred.
500 </para>
501 </step>
502 <step performance="optional">
503 <para>
504 Functions that have default values for parameters are considered to match any
505 call that omits zero or more of the defaultable parameter positions. If more
506 than one such function matches a call, the one appearing earliest in the
507 search path is used. If there are two or more such functions in the same
508 schema with identical parameter types in the non-defaulted positions (which is
509 possible if they have different sets of defaultable parameters), the system
510 will not be able to determine which to prefer, and so an <quote>ambiguous
511 function call</> error will result if no better match to the call can be
512 found.
513 </para>
514 </step>
515 </substeps>
516 </step>
518 <step performance="required">
519 <para>
520 Check for a function accepting exactly the input argument types.
521 If one exists (there can be only one exact match in the set of
522 functions considered), use it.
523 (Cases involving <type>unknown</type> will never find a match at
524 this step.)
525 </para>
526 </step>
528 <step performance="required">
529 <para>
530 If no exact match is found, see whether the function call appears
531 to be a special type conversion request. This happens if the function call
532 has just one argument and the function name is the same as the (internal)
533 name of some data type. Furthermore, the function argument must be either
534 an unknown-type literal, or a type that is binary-coercible to the named
535 data type, or a type that could be converted to the named data type by
536 applying that type's I/O functions (that is, the conversion is either to or
537 from one of the standard string types). When these conditions are met,
538 the function call is treated as a form of <literal>CAST</> specification.
539 <footnote>
540 <para>
541 The reason for this step is to support function-style cast specifications
542 in cases where there is not an actual cast function. If there is a cast
543 function, it is conventionally named after its output type, and so there
544 is no need to have a special case. See
545 <xref linkend="sql-createcast" endterm="sql-createcast-title">
546 for additional commentary.
547 </para>
548 </footnote>
549 </para>
550 </step>
551 <step performance="required">
552 <para>
553 Look for the best match.
554 </para>
555 <substeps>
556 <step performance="required">
557 <para>
558 Discard candidate functions for which the input types do not match
559 and cannot be converted (using an implicit conversion) to match.
560 <type>unknown</type> literals are
561 assumed to be convertible to anything for this purpose. If only one
562 candidate remains, use it; else continue to the next step.
563 </para>
564 </step>
565 <step performance="required">
566 <para>
567 Run through all candidates and keep those with the most exact matches
568 on input types. (Domains are considered the same as their base type
569 for this purpose.) Keep all candidates if none have any exact matches.
570 If only one candidate remains, use it; else continue to the next step.
571 </para>
572 </step>
573 <step performance="required">
574 <para>
575 Run through all candidates and keep those that accept preferred types (of the
576 input data type's type category) at the most positions where type conversion
577 will be required.
578 Keep all candidates if none accept preferred types.
579 If only one candidate remains, use it; else continue to the next step.
580 </para>
581 </step>
582 <step performance="required">
583 <para>
584 If any input arguments are <type>unknown</type>, check the type categories
585 accepted
586 at those argument positions by the remaining candidates. At each position,
587 select the <type>string</type> category if any candidate accepts that category.
588 (This bias towards string
589 is appropriate since an unknown-type literal does look like a string.)
590 Otherwise, if all the remaining candidates accept the same type category,
591 select that category; otherwise fail because
592 the correct choice cannot be deduced without more clues.
593 Now discard candidates that do not accept the selected type category.
594 Furthermore, if any candidate accepts a preferred type in that category,
595 discard candidates that accept non-preferred types for that argument.
596 </para>
597 </step>
598 <step performance="required">
599 <para>
600 If only one candidate remains, use it. If no candidate or more than one
601 candidate remains,
602 then fail.
603 </para>
604 </step>
605 </substeps>
606 </step>
607 </procedure>
609 <para>
610 Note that the <quote>best match</> rules are identical for operator and
611 function type resolution.
612 Some examples follow.
613 </para>
615 <example>
616 <title>Rounding Function Argument Type Resolution</title>
618 <para>
619 There is only one <function>round</function> function with two
620 arguments. (The first is <type>numeric</type>, the second is
621 <type>integer</type>.) So the following query automatically converts
622 the first argument of type <type>integer</type> to
623 <type>numeric</type>:
625 <screen>
626 SELECT round(4, 4);
628 round
629 --------
630 4.0000
631 (1 row)
632 </screen>
634 That query is actually transformed by the parser to
635 <screen>
636 SELECT round(CAST (4 AS numeric), 4);
637 </screen>
638 </para>
640 <para>
641 Since numeric constants with decimal points are initially assigned the
642 type <type>numeric</type>, the following query will require no type
643 conversion and might therefore be slightly more efficient:
644 <screen>
645 SELECT round(4.0, 4);
646 </screen>
647 </para>
648 </example>
650 <example>
651 <title>Substring Function Type Resolution</title>
653 <para>
654 There are several <function>substr</function> functions, one of which
655 takes types <type>text</type> and <type>integer</type>. If called
656 with a string constant of unspecified type, the system chooses the
657 candidate function that accepts an argument of the preferred category
658 <literal>string</literal> (namely of type <type>text</type>).
660 <screen>
661 SELECT substr('1234', 3);
663 substr
664 --------
666 (1 row)
667 </screen>
668 </para>
670 <para>
671 If the string is declared to be of type <type>varchar</type>, as might be the case
672 if it comes from a table, then the parser will try to convert it to become <type>text</type>:
673 <screen>
674 SELECT substr(varchar '1234', 3);
676 substr
677 --------
679 (1 row)
680 </screen>
682 This is transformed by the parser to effectively become
683 <screen>
684 SELECT substr(CAST (varchar '1234' AS text), 3);
685 </screen>
686 </para>
687 <para>
688 <note>
689 <para>
690 The parser learns from the <structname>pg_cast</> catalog that
691 <type>text</type> and <type>varchar</type>
692 are binary-compatible, meaning that one can be passed to a function that
693 accepts the other without doing any physical conversion. Therefore, no
694 type conversion call is really inserted in this case.
695 </para>
696 </note>
697 </para>
699 <para>
700 And, if the function is called with an argument of type <type>integer</type>,
701 the parser will try to convert that to <type>text</type>:
702 <screen>
703 SELECT substr(1234, 3);
704 ERROR: function substr(integer, integer) does not exist
705 HINT: No function matches the given name and argument types. You might need
706 to add explicit type casts.
707 </screen>
709 This does not work because <type>integer</> does not have an implicit cast
710 to <type>text</>. An explicit cast will work, however:
711 <screen>
712 SELECT substr(CAST (1234 AS text), 3);
714 substr
715 --------
717 (1 row)
718 </screen>
719 </para>
720 </example>
722 </sect1>
724 <sect1 id="typeconv-query">
725 <title>Value Storage</title>
727 <para>
728 Values to be inserted into a table are converted to the destination
729 column's data type according to the
730 following steps.
731 </para>
733 <procedure>
734 <title>Value Storage Type Conversion</title>
736 <step performance="required">
737 <para>
738 Check for an exact match with the target.
739 </para>
740 </step>
742 <step performance="required">
743 <para>
744 Otherwise, try to convert the expression to the target type. This will succeed
745 if there is a registered cast between the two types.
746 If the expression is an unknown-type literal, the contents of
747 the literal string will be fed to the input conversion routine for the target
748 type.
749 </para>
750 </step>
752 <step performance="required">
753 <para>
754 Check to see if there is a sizing cast for the target type. A sizing
755 cast is a cast from that type to itself. If one is found in the
756 <structname>pg_cast</> catalog, apply it to the expression before storing
757 into the destination column. The implementation function for such a cast
758 always takes an extra parameter of type <type>integer</type>, which receives
759 the destination column's declared length (actually, its
760 <structfield>atttypmod</> value; the interpretation of
761 <structfield>atttypmod</> varies for different data types). The cast function
762 is responsible for applying any length-dependent semantics such as size
763 checking or truncation.
764 </para>
765 </step>
767 </procedure>
769 <example>
770 <title><type>character</type> Storage Type Conversion</title>
772 <para>
773 For a target column declared as <type>character(20)</type> the following statement
774 ensures that the stored value is sized correctly:
776 <screen>
777 CREATE TABLE vv (v character(20));
778 INSERT INTO vv SELECT 'abc' || 'def';
779 SELECT v, length(v) FROM vv;
781 v | length
782 ----------------------+--------
783 abcdef | 20
784 (1 row)
785 </screen>
786 </para>
788 <para>
789 What has really happened here is that the two unknown literals are resolved
790 to <type>text</type> by default, allowing the <literal>||</literal> operator
791 to be resolved as <type>text</type> concatenation. Then the <type>text</type>
792 result of the operator is converted to <type>bpchar</type> (<quote>blank-padded
793 char</>, the internal name of the <type>character</type> data type) to match the target
794 column type. (Since the conversion from <type>text</type> to
795 <type>bpchar</type> is binary-coercible, this conversion does
796 not insert any real function call.) Finally, the sizing function
797 <literal>bpchar(bpchar, integer)</literal> is found in the system catalog
798 and applied to the operator's result and the stored column length. This
799 type-specific function performs the required length check and addition of
800 padding spaces.
801 </para>
802 </example>
803 </sect1>
805 <sect1 id="typeconv-union-case">
806 <title><literal>UNION</literal>, <literal>CASE</literal>, and Related Constructs</title>
808 <indexterm zone="typeconv-union-case">
809 <primary>UNION</primary>
810 <secondary>determination of result type</secondary>
811 </indexterm>
813 <indexterm zone="typeconv-union-case">
814 <primary>CASE</primary>
815 <secondary>determination of result type</secondary>
816 </indexterm>
818 <indexterm zone="typeconv-union-case">
819 <primary>ARRAY</primary>
820 <secondary>determination of result type</secondary>
821 </indexterm>
823 <indexterm zone="typeconv-union-case">
824 <primary>VALUES</primary>
825 <secondary>determination of result type</secondary>
826 </indexterm>
828 <indexterm zone="typeconv-union-case">
829 <primary>GREATEST</primary>
830 <secondary>determination of result type</secondary>
831 </indexterm>
833 <indexterm zone="typeconv-union-case">
834 <primary>LEAST</primary>
835 <secondary>determination of result type</secondary>
836 </indexterm>
838 <para>
839 SQL <literal>UNION</> constructs must match up possibly dissimilar
840 types to become a single result set. The resolution algorithm is
841 applied separately to each output column of a union query. The
842 <literal>INTERSECT</> and <literal>EXCEPT</> constructs resolve
843 dissimilar types in the same way as <literal>UNION</>. The
844 <literal>CASE</>, <literal>ARRAY</>, <literal>VALUES</>,
845 <function>GREATEST</> and <function>LEAST</> constructs use the identical
846 algorithm to match up their component expressions and select a result
847 data type.
848 </para>
850 <procedure>
851 <title>Type Resolution for <literal>UNION</literal>, <literal>CASE</literal>,
852 and Related Constructs</title>
854 <step performance="required">
855 <para>
856 If all inputs are of the same type, and it is not <type>unknown</type>,
857 resolve as that type. Otherwise, replace any domain types in the list with
858 their underlying base types.
859 </para>
860 </step>
862 <step performance="required">
863 <para>
864 If all inputs are of type <type>unknown</type>, resolve as type
865 <type>text</type> (the preferred type of the string category).
866 Otherwise, the <type>unknown</type> inputs will be ignored.
867 </para>
868 </step>
870 <step performance="required">
871 <para>
872 If the non-unknown inputs are not all of the same type category, fail.
873 </para>
874 </step>
876 <step performance="required">
877 <para>
878 Choose the first non-unknown input type which is a preferred type in
879 that category, if there is one.
880 </para>
881 </step>
883 <step performance="required">
884 <para>
885 Otherwise, choose the last non-unknown input type that allows all the
886 preceding non-unknown inputs to be implicitly converted to it. (There
887 always is such a type, since at least the first type in the list must
888 satisfy this condition.)
889 </para>
890 </step>
892 <step performance="required">
893 <para>
894 Convert all inputs to the selected type. Fail if there is not a
895 conversion from a given input to the selected type.
896 </para>
897 </step>
898 </procedure>
900 <para>
901 Some examples follow.
902 </para>
904 <example>
905 <title>Type Resolution with Underspecified Types in a Union</title>
907 <para>
908 <screen>
909 SELECT text 'a' AS "text" UNION SELECT 'b';
911 text
912 ------
915 (2 rows)
916 </screen>
917 Here, the unknown-type literal <literal>'b'</literal> will be resolved as type <type>text</type>.
918 </para>
919 </example>
921 <example>
922 <title>Type Resolution in a Simple Union</title>
924 <para>
925 <screen>
926 SELECT 1.2 AS "numeric" UNION SELECT 1;
928 numeric
929 ---------
932 (2 rows)
933 </screen>
934 The literal <literal>1.2</> is of type <type>numeric</>,
935 and the <type>integer</type> value <literal>1</> can be cast implicitly to
936 <type>numeric</>, so that type is used.
937 </para>
938 </example>
940 <example>
941 <title>Type Resolution in a Transposed Union</title>
943 <para>
944 <screen>
945 SELECT 1 AS "real" UNION SELECT CAST('2.2' AS REAL);
947 real
948 ------
951 (2 rows)
952 </screen>
953 Here, since type <type>real</> cannot be implicitly cast to <type>integer</>,
954 but <type>integer</> can be implicitly cast to <type>real</>, the union
955 result type is resolved as <type>real</>.
956 </para>
957 </example>
959 </sect1>
960 </chapter>