Make GROUP BY work properly for datatypes that only support hashing and not
[PostgreSQL.git] / doc / src / sgml / typeconv.sgml
blob5ab99cb3e1efeb56f10f1ce05d77b468fb9e2744
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 selected.
500 </para>
501 </step>
502 </substeps>
503 </step>
505 <step performance="required">
506 <para>
507 Check for a function accepting exactly the input argument types.
508 If one exists (there can be only one exact match in the set of
509 functions considered), use it.
510 (Cases involving <type>unknown</type> will never find a match at
511 this step.)
512 </para>
513 </step>
515 <step performance="required">
516 <para>
517 If no exact match is found, see whether the function call appears
518 to be a special type conversion request. This happens if the function call
519 has just one argument and the function name is the same as the (internal)
520 name of some data type. Furthermore, the function argument must be either
521 an unknown-type literal, or a type that is binary-coercible to the named
522 data type, or a type that could be converted to the named data type by
523 applying that type's I/O functions (that is, the conversion is either to or
524 from one of the standard string types). When these conditions are met,
525 the function call is treated as a form of <literal>CAST</> specification.
526 <footnote>
527 <para>
528 The reason for this step is to support function-style cast specifications
529 in cases where there is not an actual cast function. If there is a cast
530 function, it is conventionally named after its output type, and so there
531 is no need to have a special case. See
532 <xref linkend="sql-createcast" endterm="sql-createcast-title">
533 for additional commentary.
534 </para>
535 </footnote>
536 </para>
537 </step>
538 <step performance="required">
539 <para>
540 Look for the best match.
541 </para>
542 <substeps>
543 <step performance="required">
544 <para>
545 Discard candidate functions for which the input types do not match
546 and cannot be converted (using an implicit conversion) to match.
547 <type>unknown</type> literals are
548 assumed to be convertible to anything for this purpose. If only one
549 candidate remains, use it; else continue to the next step.
550 </para>
551 </step>
552 <step performance="required">
553 <para>
554 Run through all candidates and keep those with the most exact matches
555 on input types. (Domains are considered the same as their base type
556 for this purpose.) Keep all candidates if none have any exact matches.
557 If only one candidate remains, use it; else continue to the next step.
558 </para>
559 </step>
560 <step performance="required">
561 <para>
562 Run through all candidates and keep those that accept preferred types (of the
563 input data type's type category) at the most positions where type conversion
564 will be required.
565 Keep all candidates if none accept preferred types.
566 If only one candidate remains, use it; else continue to the next step.
567 </para>
568 </step>
569 <step performance="required">
570 <para>
571 If any input arguments are <type>unknown</type>, check the type categories
572 accepted
573 at those argument positions by the remaining candidates. At each position,
574 select the <type>string</type> category if any candidate accepts that category.
575 (This bias towards string
576 is appropriate since an unknown-type literal does look like a string.)
577 Otherwise, if all the remaining candidates accept the same type category,
578 select that category; otherwise fail because
579 the correct choice cannot be deduced without more clues.
580 Now discard candidates that do not accept the selected type category.
581 Furthermore, if any candidate accepts a preferred type in that category,
582 discard candidates that accept non-preferred types for that argument.
583 </para>
584 </step>
585 <step performance="required">
586 <para>
587 If only one candidate remains, use it. If no candidate or more than one
588 candidate remains,
589 then fail.
590 </para>
591 </step>
592 </substeps>
593 </step>
594 </procedure>
596 <para>
597 Note that the <quote>best match</> rules are identical for operator and
598 function type resolution.
599 Some examples follow.
600 </para>
602 <example>
603 <title>Rounding Function Argument Type Resolution</title>
605 <para>
606 There is only one <function>round</function> function with two
607 arguments. (The first is <type>numeric</type>, the second is
608 <type>integer</type>.) So the following query automatically converts
609 the first argument of type <type>integer</type> to
610 <type>numeric</type>:
612 <screen>
613 SELECT round(4, 4);
615 round
616 --------
617 4.0000
618 (1 row)
619 </screen>
621 That query is actually transformed by the parser to
622 <screen>
623 SELECT round(CAST (4 AS numeric), 4);
624 </screen>
625 </para>
627 <para>
628 Since numeric constants with decimal points are initially assigned the
629 type <type>numeric</type>, the following query will require no type
630 conversion and might therefore be slightly more efficient:
631 <screen>
632 SELECT round(4.0, 4);
633 </screen>
634 </para>
635 </example>
637 <example>
638 <title>Substring Function Type Resolution</title>
640 <para>
641 There are several <function>substr</function> functions, one of which
642 takes types <type>text</type> and <type>integer</type>. If called
643 with a string constant of unspecified type, the system chooses the
644 candidate function that accepts an argument of the preferred category
645 <literal>string</literal> (namely of type <type>text</type>).
647 <screen>
648 SELECT substr('1234', 3);
650 substr
651 --------
653 (1 row)
654 </screen>
655 </para>
657 <para>
658 If the string is declared to be of type <type>varchar</type>, as might be the case
659 if it comes from a table, then the parser will try to convert it to become <type>text</type>:
660 <screen>
661 SELECT substr(varchar '1234', 3);
663 substr
664 --------
666 (1 row)
667 </screen>
669 This is transformed by the parser to effectively become
670 <screen>
671 SELECT substr(CAST (varchar '1234' AS text), 3);
672 </screen>
673 </para>
674 <para>
675 <note>
676 <para>
677 The parser learns from the <structname>pg_cast</> catalog that
678 <type>text</type> and <type>varchar</type>
679 are binary-compatible, meaning that one can be passed to a function that
680 accepts the other without doing any physical conversion. Therefore, no
681 type conversion call is really inserted in this case.
682 </para>
683 </note>
684 </para>
686 <para>
687 And, if the function is called with an argument of type <type>integer</type>,
688 the parser will try to convert that to <type>text</type>:
689 <screen>
690 SELECT substr(1234, 3);
691 ERROR: function substr(integer, integer) does not exist
692 HINT: No function matches the given name and argument types. You might need
693 to add explicit type casts.
694 </screen>
696 This does not work because <type>integer</> does not have an implicit cast
697 to <type>text</>. An explicit cast will work, however:
698 <screen>
699 SELECT substr(CAST (1234 AS text), 3);
701 substr
702 --------
704 (1 row)
705 </screen>
706 </para>
707 </example>
709 </sect1>
711 <sect1 id="typeconv-query">
712 <title>Value Storage</title>
714 <para>
715 Values to be inserted into a table are converted to the destination
716 column's data type according to the
717 following steps.
718 </para>
720 <procedure>
721 <title>Value Storage Type Conversion</title>
723 <step performance="required">
724 <para>
725 Check for an exact match with the target.
726 </para>
727 </step>
729 <step performance="required">
730 <para>
731 Otherwise, try to convert the expression to the target type. This will succeed
732 if there is a registered cast between the two types.
733 If the expression is an unknown-type literal, the contents of
734 the literal string will be fed to the input conversion routine for the target
735 type.
736 </para>
737 </step>
739 <step performance="required">
740 <para>
741 Check to see if there is a sizing cast for the target type. A sizing
742 cast is a cast from that type to itself. If one is found in the
743 <structname>pg_cast</> catalog, apply it to the expression before storing
744 into the destination column. The implementation function for such a cast
745 always takes an extra parameter of type <type>integer</type>, which receives
746 the destination column's declared length (actually, its
747 <structfield>atttypmod</> value; the interpretation of
748 <structfield>atttypmod</> varies for different data types). The cast function
749 is responsible for applying any length-dependent semantics such as size
750 checking or truncation.
751 </para>
752 </step>
754 </procedure>
756 <example>
757 <title><type>character</type> Storage Type Conversion</title>
759 <para>
760 For a target column declared as <type>character(20)</type> the following statement
761 ensures that the stored value is sized correctly:
763 <screen>
764 CREATE TABLE vv (v character(20));
765 INSERT INTO vv SELECT 'abc' || 'def';
766 SELECT v, length(v) FROM vv;
768 v | length
769 ----------------------+--------
770 abcdef | 20
771 (1 row)
772 </screen>
773 </para>
775 <para>
776 What has really happened here is that the two unknown literals are resolved
777 to <type>text</type> by default, allowing the <literal>||</literal> operator
778 to be resolved as <type>text</type> concatenation. Then the <type>text</type>
779 result of the operator is converted to <type>bpchar</type> (<quote>blank-padded
780 char</>, the internal name of the <type>character</type> data type) to match the target
781 column type. (Since the conversion from <type>text</type> to
782 <type>bpchar</type> is binary-coercible, this conversion does
783 not insert any real function call.) Finally, the sizing function
784 <literal>bpchar(bpchar, integer)</literal> is found in the system catalog
785 and applied to the operator's result and the stored column length. This
786 type-specific function performs the required length check and addition of
787 padding spaces.
788 </para>
789 </example>
790 </sect1>
792 <sect1 id="typeconv-union-case">
793 <title><literal>UNION</literal>, <literal>CASE</literal>, and Related Constructs</title>
795 <indexterm zone="typeconv-union-case">
796 <primary>UNION</primary>
797 <secondary>determination of result type</secondary>
798 </indexterm>
800 <indexterm zone="typeconv-union-case">
801 <primary>CASE</primary>
802 <secondary>determination of result type</secondary>
803 </indexterm>
805 <indexterm zone="typeconv-union-case">
806 <primary>ARRAY</primary>
807 <secondary>determination of result type</secondary>
808 </indexterm>
810 <indexterm zone="typeconv-union-case">
811 <primary>VALUES</primary>
812 <secondary>determination of result type</secondary>
813 </indexterm>
815 <indexterm zone="typeconv-union-case">
816 <primary>GREATEST</primary>
817 <secondary>determination of result type</secondary>
818 </indexterm>
820 <indexterm zone="typeconv-union-case">
821 <primary>LEAST</primary>
822 <secondary>determination of result type</secondary>
823 </indexterm>
825 <para>
826 SQL <literal>UNION</> constructs must match up possibly dissimilar
827 types to become a single result set. The resolution algorithm is
828 applied separately to each output column of a union query. The
829 <literal>INTERSECT</> and <literal>EXCEPT</> constructs resolve
830 dissimilar types in the same way as <literal>UNION</>. The
831 <literal>CASE</>, <literal>ARRAY</>, <literal>VALUES</>,
832 <function>GREATEST</> and <function>LEAST</> constructs use the identical
833 algorithm to match up their component expressions and select a result
834 data type.
835 </para>
837 <procedure>
838 <title>Type Resolution for <literal>UNION</literal>, <literal>CASE</literal>,
839 and Related Constructs</title>
841 <step performance="required">
842 <para>
843 If all inputs are of the same type, and it is not <type>unknown</type>,
844 resolve as that type. Otherwise, replace any domain types in the list with
845 their underlying base types.
846 </para>
847 </step>
849 <step performance="required">
850 <para>
851 If all inputs are of type <type>unknown</type>, resolve as type
852 <type>text</type> (the preferred type of the string category).
853 Otherwise, the <type>unknown</type> inputs will be ignored.
854 </para>
855 </step>
857 <step performance="required">
858 <para>
859 If the non-unknown inputs are not all of the same type category, fail.
860 </para>
861 </step>
863 <step performance="required">
864 <para>
865 Choose the first non-unknown input type which is a preferred type in
866 that category, if there is one.
867 </para>
868 </step>
870 <step performance="required">
871 <para>
872 Otherwise, choose the last non-unknown input type that allows all the
873 preceding non-unknown inputs to be implicitly converted to it. (There
874 always is such a type, since at least the first type in the list must
875 satisfy this condition.)
876 </para>
877 </step>
879 <step performance="required">
880 <para>
881 Convert all inputs to the selected type. Fail if there is not a
882 conversion from a given input to the selected type.
883 </para>
884 </step>
885 </procedure>
887 <para>
888 Some examples follow.
889 </para>
891 <example>
892 <title>Type Resolution with Underspecified Types in a Union</title>
894 <para>
895 <screen>
896 SELECT text 'a' AS "text" UNION SELECT 'b';
898 text
899 ------
902 (2 rows)
903 </screen>
904 Here, the unknown-type literal <literal>'b'</literal> will be resolved as type <type>text</type>.
905 </para>
906 </example>
908 <example>
909 <title>Type Resolution in a Simple Union</title>
911 <para>
912 <screen>
913 SELECT 1.2 AS "numeric" UNION SELECT 1;
915 numeric
916 ---------
919 (2 rows)
920 </screen>
921 The literal <literal>1.2</> is of type <type>numeric</>,
922 and the <type>integer</type> value <literal>1</> can be cast implicitly to
923 <type>numeric</>, so that type is used.
924 </para>
925 </example>
927 <example>
928 <title>Type Resolution in a Transposed Union</title>
930 <para>
931 <screen>
932 SELECT 1 AS "real" UNION SELECT CAST('2.2' AS REAL);
934 real
935 ------
938 (2 rows)
939 </screen>
940 Here, since type <type>real</> cannot be implicitly cast to <type>integer</>,
941 but <type>integer</> can be implicitly cast to <type>real</>, the union
942 result type is resolved as <type>real</>.
943 </para>
944 </example>
946 </sect1>
947 </chapter>