]> granicus.if.org Git - postgresql/blobdiff - doc/src/sgml/typeconv.sgml
Trim trailing whitespace
[postgresql] / doc / src / sgml / typeconv.sgml
index 18bad527ff7e25fa1fa1485395a805d33d47a341..63d41f03f3f8ed44fb7b57a407ff916a398ca0be 100644 (file)
@@ -1,24 +1,26 @@
-<!--
-$Header: /cvsroot/pgsql/doc/src/sgml/typeconv.sgml,v 1.32 2003/08/14 23:13:27 tgl Exp $
--->
+<!-- doc/src/sgml/typeconv.sgml -->
 
-<chapter Id="typeconv">
+<chapter id="typeconv">
 <title>Type Conversion</title>
 
+<indexterm zone="typeconv">
+ <primary>data type</primary>
+ <secondary>conversion</secondary>
+</indexterm>
+
 <para>
 <acronym>SQL</acronym> statements can, intentionally or not, require
-mixing of different data types in the same expression. 
+the mixing of different data types in the same expression.
 <productname>PostgreSQL</productname> has extensive facilities for
 evaluating mixed-type expressions.
 </para>
 
 <para>
-In many cases a user will not need
+In many cases a user does not need
 to understand the details of the type conversion mechanism.
-However, the implicit conversions done by <productname>PostgreSQL</productname>
+However, implicit conversions done by <productname>PostgreSQL</productname>
 can affect the results of a query.  When necessary, these results
-can be tailored by a user or programmer
-using <emphasis>explicit</emphasis> type conversion.
+can be tailored by using <emphasis>explicit</emphasis> type conversion.
 </para>
 
 <para>
@@ -36,20 +38,21 @@ operators.
 <acronym>SQL</acronym> is a strongly typed language. That is, every data item
 has an associated data type which determines its behavior and allowed usage.
 <productname>PostgreSQL</productname> has an extensible type system that is
-much more general and flexible than other <acronym>SQL</acronym> implementations.
+more general and flexible than other <acronym>SQL</acronym> implementations.
 Hence, most type conversion behavior in <productname>PostgreSQL</productname>
-should be governed by general rules rather than by <foreignphrase>ad hoc</> heuristics, to allow
-mixed-type expressions to be meaningful even with user-defined types.
+is governed by general rules rather than by <foreignphrase>ad hoc</>
+heuristics.  This allows the use of mixed-type expressions even with
+user-defined types.
 </para>
 
 <para>
-The <productname>PostgreSQL</productname> scanner/parser decodes lexical
-elements into only five fundamental categories: integers, floating-point numbers, strings,
-names, and key words.  Constants of most non-numeric types are first classified as
-strings. The <acronym>SQL</acronym> language definition allows specifying type
-names with strings, and this mechanism can be used in
+The <productname>PostgreSQL</productname> scanner/parser divides lexical
+elements into five fundamental categories: integers, non-integer numbers,
+strings, identifiers, and key words.  Constants of most non-numeric types are
+first classified as strings. The <acronym>SQL</acronym> language definition
+allows specifying type names with strings, and this mechanism can be used in
 <productname>PostgreSQL</productname> to start the parser down the correct
-path. For example, the query
+path. For example, the query:
 
 <screen>
 SELECT text 'Origin' AS "label", point '(0,0)' AS "value";
@@ -74,28 +77,30 @@ parser:
 <variablelist>
 <varlistentry>
 <term>
-Operators
+Function calls
 </term>
 <listitem>
 <para>
-<productname>PostgreSQL</productname> allows expressions with
-prefix and postfix unary (one-argument) operators,
-as well as binary (two-argument) operators.
+Much of the <productname>PostgreSQL</productname> type system is built around a
+rich set of functions. Functions can have one or more arguments.
+Since <productname>PostgreSQL</productname> permits function
+overloading, the function name alone does not uniquely identify the function
+to be called; the parser must select the right function based on the data
+types of the supplied arguments.
 </para>
 </listitem>
 </varlistentry>
 <varlistentry>
 <term>
-Function calls
+Operators
 </term>
 <listitem>
 <para>
-Much of the <productname>PostgreSQL</productname> type system is built around a
-rich set of functions. Function calls can have one or more arguments.
-Since <productname>PostgreSQL</productname> permits function
-overloading, the function name alone does not uniquely identify the function
-to be called; the parser must select the right function based on the data
-types of the supplied arguments.
+<productname>PostgreSQL</productname> allows expressions with
+prefix and postfix unary (one-argument) operators,
+as well as binary (two-argument) operators.  Like functions, operators can
+be overloaded, so the same problem of selecting the right operator
+exists.
 </para>
 </listitem>
 </varlistentry>
@@ -113,16 +118,17 @@ with, and perhaps converted to, the types of the target columns.
 </varlistentry>
 <varlistentry>
 <term>
-<literal>UNION</literal>, <literal>CASE</literal>, and <literal>ARRAY</literal> constructs
+<literal>UNION</literal>, <literal>CASE</literal>, and related constructs
 </term>
 <listitem>
 <para>
-Since all query results from a unionized <literal>SELECT</literal> statement
+Since all query results from a unionized <command>SELECT</command> statement
 must appear in a single set of columns, the types of the results of each
-<literal>SELECT</> clause must be matched up and converted to a uniform set.
-Similarly, the branch expressions of a <literal>CASE</> construct must be
+<command>SELECT</> clause must be matched up and converted to a uniform set.
+Similarly, the result expressions of a <literal>CASE</> construct must be
 converted to a common type so that the <literal>CASE</> expression as a whole
-has a known output type.  The same holds for <literal>ARRAY</> constructs.
+has a known output type.  The same holds for <literal>ARRAY</> constructs,
+and for the <function>GREATEST</> and <function>LEAST</> functions.
 </para>
 </listitem>
 </varlistentry>
@@ -130,28 +136,35 @@ has a known output type.  The same holds for <literal>ARRAY</> constructs.
 </para>
 
 <para>
-The system catalogs store information about which conversions, called
-<firstterm>casts</firstterm>, between data types are valid, and how to
+The system catalogs store information about which conversions, or
+<firstterm>casts</firstterm>, exist between which data types, and how to
 perform those conversions.  Additional casts can be added by the user
-with the <command>CREATE CAST</command> command.  (This is usually
+with the <xref linkend="sql-createcast">
+command.  (This is usually
 done in conjunction with defining new data types.  The set of casts
-between the built-in types has been carefully crafted and is best not
+between built-in types has been carefully crafted and is best not
 altered.)
 </para>
 
+<indexterm>
+ <primary>data type</primary>
+ <secondary>category</secondary>
+</indexterm>
+
 <para>
-An additional heuristic is provided in the parser to allow better guesses
-at proper behavior for <acronym>SQL</acronym> standard types. There are
-several basic <firstterm>type categories</firstterm> defined: <type>boolean</type>,
-<type>numeric</type>, <type>string</type>, <type>bitstring</type>, <type>datetime</type>, <type>timespan</type>, <type>geometric</type>, <type>network</type>,
-and user-defined. Each category, with the exception of user-defined, has
-one or more <firstterm>preferred types</firstterm> which are preferentially
-selected when there is ambiguity.
-In the user-defined category, each type is its own preferred type.
-Ambiguous expressions (those with multiple candidate parsing solutions)
-can therefore often be resolved when there are multiple possible built-in types, but
-they will raise an error when there are multiple choices for user-defined
-types.
+An additional heuristic provided by the parser allows improved determination
+of the proper casting behavior among groups of types that have implicit casts.
+Data types are divided into several basic <firstterm>type
+categories</firstterm>, including <type>boolean</type>, <type>numeric</type>,
+<type>string</type>, <type>bitstring</type>, <type>datetime</type>,
+<type>timespan</type>, <type>geometric</type>, <type>network</type>, and
+user-defined.  (For a list see <xref linkend="catalog-typcategory-table">;
+but note it is also possible to create custom type categories.)  Within each
+category there can be one or more <firstterm>preferred types</firstterm>, which
+are preferred when there is a choice of possible types.  With careful selection
+of preferred types and available implicit casts, it is possible to ensure that
+ambiguous expressions (those with multiple candidate parsing solutions) can be
+resolved in a useful way.
 </para>
 
 <para>
@@ -166,34 +179,19 @@ Implicit conversions should never have surprising or unpredictable outcomes.
 
 <listitem>
 <para>
-User-defined types, of which the parser has no <foreignphrase>a priori</> knowledge, should be
-<quote>higher</quote> in the type hierarchy. In mixed-type expressions, native types shall always
-be converted to a user-defined type (of course, only if conversion is necessary).
-</para>
-</listitem>
-
-<listitem>
-<para>
-User-defined types are not related. Currently, <productname>PostgreSQL</productname>
-does not have information available to it on relationships between types, other than
-hardcoded heuristics for built-in types and implicit relationships based on
-available functions and casts.
-</para>
-</listitem>
-
-<listitem>
-<para>
-There should be no extra overhead from the parser or executor
+There should be no extra overhead in the parser or executor
 if a query does not need implicit type conversion.
-That is, if a query is well formulated and the types already match up, then the query should proceed
+That is, if a query is well-formed and the types already match, then the query should execute
 without spending extra time in the parser and without introducing unnecessary implicit conversion
-calls into the query.
+calls in the query.
 </para>
+</listitem>
 
+<listitem>
 <para>
 Additionally, if a query usually requires an implicit conversion for a function, and
 if then the user defines a new function with the correct argument types, the parser
-should use this new function and will no longer do the implicit conversion using the old function.
+should use this new function and no longer do implicit conversion to use the old function.
 </para>
 </listitem>
 </itemizedlist>
@@ -204,23 +202,29 @@ should use this new function and will no longer do the implicit conversion using
 <sect1 id="typeconv-oper">
 <title>Operators</title>
 
+<indexterm zone="typeconv-oper">
+ <primary>operator</primary>
+ <secondary>type resolution in an invocation</secondary>
+</indexterm>
+
   <para>
-   The specific operator to be used in an operator invocation is determined
-   by following
-   the procedure below.  Note that this procedure is indirectly affected
-   by the precedence of the involved operators.  See <xref
-   linkend="sql-precedence"> for more information.
+   The specific operator that is referenced by an operator expression
+   is determined using the following procedure.
+   Note that this procedure is indirectly affected
+   by the precedence of the operators involved, since that will determine
+   which sub-expressions are taken to be the inputs of which operators.
+   See <xref linkend="sql-precedence"> for more information.
   </para>
 
 <procedure>
 <title>Operator Type Resolution</title>
 
-<step performance="required">
+<step id="op-resol-select" performance="required">
 <para>
 Select the operators to be considered from the
-<classname>pg_operator</classname> system catalog.  If an unqualified
+<classname>pg_operator</classname> system catalog.  If a non-schema-qualified
 operator name was used (the usual case), the operators
-considered are those of the right name and argument count that are
+considered are those with the matching name and argument count that are
 visible in the current search path (see <xref linkend="ddl-schemas-path">).
 If a qualified operator name was given, only operators in the specified
 schema are considered.
@@ -229,8 +233,8 @@ schema are considered.
 <substeps>
 <step performance="optional">
 <para>
-If the search path finds multiple operators of identical argument types,
-only the one appearing earliest in the path is considered.  But operators of
+If the search path finds multiple operators with identical argument types,
+only the one appearing earliest in the path is considered.  Operators with
 different argument types are considered on an equal footing regardless of
 search path position.
 </para>
@@ -238,7 +242,7 @@ search path position.
 </substeps>
 </step>
 
-<step performance="required">
+<step id="op-resol-exact-match" performance="required">
 <para>
 Check for an operator accepting exactly the input argument types.
 If one exists (there can be only one exact match in the set of
@@ -246,18 +250,25 @@ operators considered), use it.
 </para>
 
 <substeps>
-<step performance="optional">
+<step id="op-resol-exact-unknown" performance="optional">
 <para>
 If one argument of a binary operator invocation is of the <type>unknown</type> type,
 then assume it is the same type as the other argument for this check.
-Other cases involving <type>unknown</type> will never find a match at
-this step.
+Invocations involving two <type>unknown</type> inputs, or a unary operator
+with an <type>unknown</type> input, will never find a match at this step.
+</para>
+</step>
+<step id="op-resol-exact-domain" performance="optional">
+<para>
+If one argument of a binary operator invocation is of the <type>unknown</type>
+type and the other is of a domain type, next check to see if there is an
+operator accepting exactly the domain's base type on both sides; if so, use it.
 </para>
 </step>
 </substeps>
 </step>
 
-<step performance="required">
+<step id="op-resol-best-match" performance="required">
 <para>
 Look for the best match.
 </para>
@@ -273,16 +284,22 @@ candidate remains, use it; else continue to the next step.
 </step>
 <step performance="required">
 <para>
+If any input argument is of a domain type, treat it as being of the
+domain's base type for all subsequent steps.  This ensures that domains
+act like their base types for purposes of ambiguous-operator resolution.
+</para>
+</step>
+<step performance="required">
+<para>
 Run through all candidates and keep those with the most exact matches
-on input types.  (Domain types are considered the same as their base type
-for this purpose.)  Keep all candidates if none have any exact matches.
+on input types.  Keep all candidates if none have exact matches.
 If only one candidate remains, use it; else continue to the next step.
 </para>
 </step>
 <step performance="required">
 <para>
 Run through all candidates and keep those that accept preferred types (of the
-input datatype's type category) at the most positions where type conversion
+input data type's type category) at the most positions where type conversion
 will be required.
 Keep all candidates if none accept preferred types.
 If only one candidate remains, use it; else continue to the next step.
@@ -295,20 +312,25 @@ categories accepted at those argument positions by the remaining
 candidates.  At each position, select the <type>string</type> category
 if any
 candidate accepts that category.  (This bias towards string is appropriate
-since an unknown-type literal does look like a string.) Otherwise, if
+since an unknown-type literal looks like a string.) Otherwise, if
 all the remaining candidates accept the same type category, select that
 category; otherwise fail because the correct choice cannot be deduced
 without more clues.  Now discard
 candidates that do not accept the selected type category.  Furthermore,
-if any candidate accepts a preferred type at a given argument position,
+if any candidate accepts a preferred type in that category,
 discard candidates that accept non-preferred types for that argument.
+Keep all candidates if none survive these tests.
+If only one candidate remains, use it; else continue to the next step.
 </para>
 </step>
-<step performance="required">
+<step id="op-resol-last-unknown" performance="required">
 <para>
-If only one candidate remains, use it.  If no candidate or more than one
-candidate remains,
-then fail.
+If there are both <type>unknown</type> and known-type arguments, and all
+the known-type arguments have the same type, assume that the
+<type>unknown</type> arguments are also of that type, and check which
+candidates can accept that type at the <type>unknown</type>-argument
+positions.  If exactly one candidate passes this test, use it.
+Otherwise, fail.
 </para>
 </step>
 </substeps>
@@ -320,28 +342,28 @@ Some examples follow.
 </para>
 
 <example>
-<title>Exponentiation Operator Type Resolution</title>
+<title>Factorial Operator Type Resolution</title>
 
 <para>
-There is only one exponentiation
-operator defined in the catalog, and it takes arguments of type 
-<type>double precision</type>.
-The scanner assigns an initial type of <type>integer</type> to both arguments
-of this query expression:
+There is only one factorial operator (postfix <literal>!</>)
+defined in the standard catalog, and it takes an argument of type
+<type>bigint</type>.
+The scanner assigns an initial type of <type>integer</type> to the argument
+in this query expression:
 <screen>
-SELECT 2 ^ 3 AS "exp";
+SELECT 40 ! AS "40 factorial";
 
- exp
------
-   8
+                   40 factorial
+--------------------------------------------------
+ 815915283247897734345611269596115894272000000000
 (1 row)
 </screen>
 
-So the parser does a type conversion on both operands and the query
-is equivalent to
+So the parser does a type conversion on the operand and the query
+is equivalent to:
 
 <screen>
-SELECT CAST(2 AS double precision) ^ CAST(3 AS double precision) AS "exp";
+SELECT CAST(40 AS bigint) ! AS "40 factorial";
 </screen>
 </para>
 </example>
@@ -350,7 +372,7 @@ SELECT CAST(2 AS double precision) ^ CAST(3 AS double precision) AS "exp";
 <title>String Concatenation Operator Type Resolution</title>
 
 <para>
-A string-like syntax is used for working with string types as well as for
+A string-like syntax is used for working with string types and for
 working with complex extension types.
 Strings with unspecified type are matched with likely operator candidates.
 </para>
@@ -370,11 +392,11 @@ SELECT text 'abc' || 'def' AS "text and unknown";
 <para>
 In this case the parser looks to see if there is an operator taking <type>text</type>
 for both arguments. Since there is, it assumes that the second argument should
-be interpreted as of type <type>text</type>.
+be interpreted as type <type>text</type>.
 </para>
 
 <para>
-Here is a concatenation on unspecified types:
+Here is a concatenation of two values of unspecified types:
 <screen>
 SELECT 'abc' || 'def' AS "unspecified";
 
@@ -390,14 +412,14 @@ In this case there is no initial hint for which type to use, since no types
 are specified in the query. So, the parser looks for all candidate operators
 and finds that there are candidates accepting both string-category and
 bit-string-category inputs.  Since string category is preferred when available,
-that category is selected, and then the 
+that category is selected, and then the
 preferred type for strings, <type>text</type>, is used as the specific
-type to resolve the unknown literals to.
+type to resolve the unknown-type literals as.
 </para>
 </example>
 
 <example>
-<title>Absolute-Value and Factorial Operator Type Resolution</title>
+<title>Absolute-Value and Negation Operator Type Resolution</title>
 
 <para>
 The <productname>PostgreSQL</productname> operator catalog has several
@@ -405,7 +427,7 @@ entries for the prefix operator <literal>@</>, all of which implement
 absolute-value operations for various numeric data types.  One of these
 entries is for type <type>float8</type>, which is the preferred type in
 the numeric category.  Therefore, <productname>PostgreSQL</productname>
-will use that entry when faced with a non-numeric input:
+will use that entry when faced with an <type>unknown</> input:
 <screen>
 SELECT @ '-4.5' AS "abs";
  abs
@@ -413,37 +435,108 @@ SELECT @ '-4.5' AS "abs";
  4.5
 (1 row)
 </screen>
-Here the system has performed an implicit conversion from <type>text</type> to <type>float8</type>
-before applying the chosen operator.  We can verify that <type>float8</type> and
-not some other type was used:
+Here the system has implicitly resolved the unknown-type literal as type
+<type>float8</type> before applying the chosen operator.  We can verify that
+<type>float8</type> and not some other type was used:
 <screen>
 SELECT @ '-4.5e500' AS "abs";
 
-ERROR:  Input '-4.5e500' is out of range for float8
+ERROR:  "-4.5e500" is out of range for type double precision
 </screen>
 </para>
 
 <para>
-On the other hand, the postfix operator <literal>!</> (factorial)
+On the other hand, the prefix operator <literal>~</> (bitwise negation)
 is defined only for integer data types, not for <type>float8</type>.  So, if we
-try a similar case with <literal>!</>, we get:
+try a similar case with <literal>~</>, we get:
 <screen>
-SELECT '20' ! AS "factorial";
+SELECT ~ '20' AS "negation";
 
-ERROR:  Unable to identify a postfix operator '!' for type 'text'
-        You may need to add parentheses or an explicit cast
+ERROR:  operator is not unique: ~ "unknown"
+HINT:  Could not choose a best candidate operator. You might need to add
+explicit type casts.
 </screen>
-This happens because the system can't decide which of the several
-possible <literal>!</> operators should be preferred.  We can help
+This happens because the system cannot decide which of the several
+possible <literal>~</> operators should be preferred.  We can help
 it out with an explicit cast:
 <screen>
-SELECT CAST('20' AS int8) ! AS "factorial";
+SELECT ~ CAST('20' AS int8) AS "negation";
+
+ negation
+----------
+      -21
+(1 row)
+</screen>
+</para>
+</example>
+
+<example>
+<title>Array Inclusion Operator Type Resolution</title>
+
+<para>
+Here is another example of resolving an operator with one known and one
+unknown input:
+<screen>
+SELECT array[1,2] &lt;@ '{1,2,3}' as "is subset";
 
-      factorial
----------------------
- 2432902008176640000
+ is subset
+-----------
+ t
 (1 row)
 </screen>
+The <productname>PostgreSQL</productname> operator catalog has several
+entries for the infix operator <literal>&lt;@</>, but the only two that
+could possibly accept an integer array on the left-hand side are
+array inclusion (<type>anyarray</> <literal>&lt;@</> <type>anyarray</>)
+and range inclusion (<type>anyelement</> <literal>&lt;@</> <type>anyrange</>).
+Since none of these polymorphic pseudo-types (see <xref
+linkend="datatype-pseudo">) are considered preferred, the parser cannot
+resolve the ambiguity on that basis.
+However, <xref linkend="op-resol-last-unknown"> tells
+it to assume that the unknown-type literal is of the same type as the other
+input, that is, integer array.  Now only one of the two operators can match,
+so array inclusion is selected.  (Had range inclusion been selected, we would
+have gotten an error, because the string does not have the right format to be
+a range literal.)
+</para>
+</example>
+
+<example>
+<title>Custom Operator on a Domain Type</title>
+
+<para>
+Users sometimes try to declare operators applying just to a domain type.
+This is possible but is not nearly as useful as it might seem, because the
+operator resolution rules are designed to select operators applying to the
+domain's base type.  As an example consider
+<screen>
+CREATE DOMAIN mytext AS text CHECK(...);
+CREATE FUNCTION mytext_eq_text (mytext, text) RETURNS boolean AS ...;
+CREATE OPERATOR = (procedure=mytext_eq_text, leftarg=mytext, rightarg=text);
+CREATE TABLE mytable (val mytext);
+
+SELECT * FROM mytable WHERE val = 'foo';
+</screen>
+This query will not use the custom operator.  The parser will first see if
+there is a <type>mytext</> <literal>=</> <type>mytext</> operator
+(<xref linkend="op-resol-exact-unknown">), which there is not;
+then it will consider the domain's base type <type>text</>, and see if
+there is a <type>text</> <literal>=</> <type>text</> operator
+(<xref linkend="op-resol-exact-domain">), which there is;
+so it resolves the <type>unknown</>-type literal as <type>text</> and
+uses the <type>text</> <literal>=</> <type>text</> operator.
+The only way to get the custom operator to be used is to explicitly cast
+the literal:
+<screen>
+SELECT * FROM mytable WHERE val = text 'foo';
+</screen>
+so that the <type>mytext</> <literal>=</> <type>text</> operator is found
+immediately according to the exact-match rule.  If the best-match rules
+are reached, they actively discriminate against operators on domain types.
+If they did not, such an operator would create too many ambiguous-operator
+failures, because the casting rules always consider a domain as castable
+to or from its base type, and so the domain operator would be considered
+usable in all the same cases as a similarly-named operator on the base type.
 </para>
 </example>
 
@@ -452,9 +545,14 @@ SELECT CAST('20' AS int8) ! AS "factorial";
 <sect1 id="typeconv-func">
 <title>Functions</title>
 
+<indexterm zone="typeconv-func">
+ <primary>function</primary>
+ <secondary>type resolution in an invocation</secondary>
+</indexterm>
+
   <para>
-   The specific function to be used in a function invocation is determined
-   according to the following steps.
+   The specific function that is referenced by a function call
+   is determined using the following procedure.
   </para>
 
 <procedure>
@@ -463,9 +561,9 @@ SELECT CAST('20' AS int8) ! AS "factorial";
 <step performance="required">
 <para>
 Select the functions to be considered from the
-<classname>pg_proc</classname> system catalog.  If an unqualified
+<classname>pg_proc</classname> system catalog.  If a non-schema-qualified
 function name was used, the functions
-considered are those of the right name and argument count that are
+considered are those with the matching name and argument count that are
 visible in the current search path (see <xref linkend="ddl-schemas-path">).
 If a qualified function name was given, only functions in the specified
 schema are considered.
@@ -475,11 +573,36 @@ schema are considered.
 <step performance="optional">
 <para>
 If the search path finds multiple functions of identical argument types,
-only the one appearing earliest in the path is considered.  But functions of
+only the one appearing earliest in the path is considered.  Functions of
 different argument types are considered on an equal footing regardless of
 search path position.
 </para>
 </step>
+<step performance="optional">
+<para>
+If a function is declared with a <literal>VARIADIC</> array parameter, and
+the call does not use the <literal>VARIADIC</> keyword, then the function
+is treated as if the array parameter were replaced by one or more occurrences
+of its element type, as needed to match the call.  After such expansion the
+function might have effective argument types identical to some non-variadic
+function.  In that case the function appearing earlier in the search path is
+used, or if the two functions are in the same schema, the non-variadic one is
+preferred.
+</para>
+</step>
+<step performance="optional">
+<para>
+Functions that have default values for parameters are considered to match any
+call that omits zero or more of the defaultable parameter positions.  If more
+than one such function matches a call, the one appearing earliest in the
+search path is used.  If there are two or more such functions in the same
+schema with identical parameter types in the non-defaulted positions (which is
+possible if they have different sets of defaultable parameters), the system
+will not be able to determine which to prefer, and so an <quote>ambiguous
+function call</> error will result if no better match to the call can be
+found.
+</para>
+</step>
 </substeps>
 </step>
 
@@ -495,13 +618,25 @@ this step.)
 
 <step performance="required">
 <para>
-If no exact match is found, see whether the function call appears
-to be a trivial type conversion request.  This happens if the function call
+If no exact match is found, see if the function call appears
+to be a special type conversion request.  This happens if the function call
 has just one argument and the function name is the same as the (internal)
 name of some data type.  Furthermore, the function argument must be either
-an unknown-type literal or a type that is binary-compatible with the named
-data type.  When these conditions are met, the function argument is converted
-to the named data type without any actual function call.
+an unknown-type literal, or a type that is binary-coercible to the named
+data type, or a type that could be converted to the named data type by
+applying that type's I/O functions (that is, the conversion is either to or
+from one of the standard string types).  When these conditions are met,
+the function call is treated as a form of <literal>CAST</> specification.
+  <footnote>
+   <para>
+    The reason for this step is to support function-style cast specifications
+    in cases where there is not an actual cast function.  If there is a cast
+    function, it is conventionally named after its output type, and so there
+    is no need to have a special case.  See
+    <xref linkend="sql-createcast">
+    for additional commentary.
+   </para>
+  </footnote>
 </para>
 </step>
 <step performance="required">
@@ -520,16 +655,22 @@ candidate remains, use it; else continue to the next step.
 </step>
 <step performance="required">
 <para>
+If any input argument is of a domain type, treat it as being of the
+domain's base type for all subsequent steps.  This ensures that domains
+act like their base types for purposes of ambiguous-function resolution.
+</para>
+</step>
+<step performance="required">
+<para>
 Run through all candidates and keep those with the most exact matches
-on input types.  (Domain types are considered the same as their base type
-for this purpose.)  Keep all candidates if none have any exact matches.
+on input types.  Keep all candidates if none have exact matches.
 If only one candidate remains, use it; else continue to the next step.
 </para>
 </step>
 <step performance="required">
 <para>
 Run through all candidates and keep those that accept preferred types (of the
-input datatype's type category) at the most positions where type conversion
+input data type's type category) at the most positions where type conversion
 will be required.
 Keep all candidates if none accept preferred types.
 If only one candidate remains, use it; else continue to the next step.
@@ -538,25 +679,29 @@ If only one candidate remains, use it; else continue to the next step.
 <step performance="required">
 <para>
 If any input arguments are <type>unknown</type>, check the type categories
-accepted 
+accepted
 at those argument positions by the remaining candidates.  At each position,
 select the <type>string</type> category if any candidate accepts that category.
 (This bias towards string
-is appropriate since an unknown-type literal does look like a string.)
+is appropriate since an unknown-type literal looks like a string.)
 Otherwise, if all the remaining candidates accept the same type category,
 select that category; otherwise fail because
 the correct choice cannot be deduced without more clues.
 Now discard candidates that do not accept the selected type category.
-Furthermore, if any candidate accepts a preferred type at a given argument
-position, discard candidates that accept non-preferred types for that
-argument.
+Furthermore, if any candidate accepts a preferred type in that category,
+discard candidates that accept non-preferred types for that argument.
+Keep all candidates if none survive these tests.
+If only one candidate remains, use it; else continue to the next step.
 </para>
 </step>
 <step performance="required">
 <para>
-If only one candidate remains, use it.  If no candidate or more than one
-candidate remains,
-then fail.
+If there are both <type>unknown</type> and known-type arguments, and all
+the known-type arguments have the same type, assume that the
+<type>unknown</type> arguments are also of that type, and check which
+candidates can accept that type at the <type>unknown</type>-argument
+positions.  If exactly one candidate passes this test, use it.
+Otherwise, fail.
 </para>
 </step>
 </substeps>
@@ -573,9 +718,10 @@ Some examples follow.
 <title>Rounding Function Argument Type Resolution</title>
 
 <para>
-There is only one <function>round</function> function with two
-arguments.  (The first is <type>numeric</type>, the second is
-<type>integer</type>.)  So the following query automatically converts
+There is only one <function>round</function> function that takes two
+arguments; it takes a first argument of type <type>numeric</type> and
+a second argument of type <type>integer</type>.
+So the following query automatically converts
 the first argument of type <type>integer</type> to
 <type>numeric</type>:
 
@@ -588,7 +734,7 @@ SELECT round(4, 4);
 (1 row)
 </screen>
 
-That query is actually transformed by the parser to
+That query is actually transformed by the parser to:
 <screen>
 SELECT round(CAST (4 AS numeric), 4);
 </screen>
@@ -597,7 +743,7 @@ SELECT round(CAST (4 AS numeric), 4);
 <para>
 Since numeric constants with decimal points are initially assigned the
 type <type>numeric</type>, the following query will require no type
-conversion and may therefore be slightly more efficient:
+conversion and therefore might be slightly more efficient:
 <screen>
 SELECT round(4.0, 4);
 </screen>
@@ -636,7 +782,7 @@ SELECT substr(varchar '1234', 3);
 (1 row)
 </screen>
 
-This is transformed by the parser to effectively become
+This is transformed by the parser to effectively become:
 <screen>
 SELECT substr(CAST (varchar '1234' AS text), 3);
 </screen>
@@ -648,30 +794,31 @@ The parser learns from the <structname>pg_cast</> catalog that
 <type>text</type> and <type>varchar</type>
 are binary-compatible, meaning that one can be passed to a function that
 accepts the other without doing any physical conversion.  Therefore, no
-explicit type conversion call is really inserted in this case.
+type conversion call is really inserted in this case.
 </para>
 </note>
 </para>
 
 <para>
-And, if the function is called with an argument of type <type>integer</type>, the parser will
-try to convert that to <type>text</type>:
+And, if the function is called with an argument of type <type>integer</type>,
+the parser will try to convert that to <type>text</type>:
 <screen>
 SELECT substr(1234, 3);
+ERROR:  function substr(integer, integer) does not exist
+HINT:  No function matches the given name and argument types. You might need
+to add explicit type casts.
+</screen>
+
+This does not work because <type>integer</> does not have an implicit cast
+to <type>text</>.  An explicit cast will work, however:
+<screen>
+SELECT substr(CAST (1234 AS text), 3);
 
  substr
 --------
      34
 (1 row)
 </screen>
-
-This actually executes as
-<screen>
-SELECT substr(CAST (1234 AS text), 3);
-</screen>
-This automatic transformation can succeed because there is an
-implicitly invocable cast from <type>integer</type> to
-<type>text</type>.
 </para>
 </example>
 
@@ -697,9 +844,10 @@ Check for an exact match with the target.
 
 <step performance="required">
 <para>
-Otherwise, try to convert the expression to the target type.  This will succeed
-if there is a registered cast between the two types.
-If the expression is an unknown-type literal, the contents of
+Otherwise, try to convert the expression to the target type.  This is possible
+if an <firstterm>assignment cast</> between the two types is registered in the
+<structname>pg_cast</> catalog (see <xref linkend="sql-createcast">).
+Alternatively, if the expression is an unknown-type literal, the contents of
 the literal string will be fed to the input conversion routine for the target
 type.
 </para>
@@ -707,12 +855,18 @@ type.
 
 <step performance="required">
 <para>
-If the target is a fixed-length type (e.g., <type>char</type> or <type>varchar</type>
-declared with a length) then try to find a sizing function for the target
-type.  A sizing function is a function of the same name as the type,
-taking two arguments of which the first is that type and the second is of type
-<type>integer</type>, and returning the same type.  If one is found, it is applied,
-passing the column's declared length as the second parameter.
+Check to see if there is a sizing cast for the target type.  A sizing
+cast is a cast from that type to itself.  If one is found in the
+<structname>pg_cast</> catalog, apply it to the expression before storing
+into the destination column.  The implementation function for such a cast
+always takes an extra parameter of type <type>integer</type>, which receives
+the destination column's <structfield>atttypmod</> value (typically its
+declared length, although the interpretation of <structfield>atttypmod</>
+varies for different data types), and it may take a third <type>boolean</>
+parameter that says whether the cast is explicit or implicit.  The cast
+function
+is responsible for applying any length-dependent semantics such as size
+checking or truncation.
 </para>
 </step>
 
@@ -722,17 +876,17 @@ passing the column's declared length as the second parameter.
 <title><type>character</type> Storage Type Conversion</title>
 
 <para>
-For a target column declared as <type>character(20)</type> the following statement
-ensures that the stored value is sized correctly:
+For a target column declared as <type>character(20)</type> the following
+statement shows that the stored value is sized correctly:
 
 <screen>
 CREATE TABLE vv (v character(20));
 INSERT INTO vv SELECT 'abc' || 'def';
-SELECT v, length(v) FROM vv;
+SELECT v, octet_length(v) FROM vv;
 
-          v           | length
-----------------------+--------
- abcdef               |     20
+          v           | octet_length
+----------------------+--------------
+ abcdef               |           20
 (1 row)
 </screen>
 </para>
@@ -743,10 +897,10 @@ to <type>text</type> by default, allowing the <literal>||</literal> operator
 to be resolved as <type>text</type> concatenation.  Then the <type>text</type>
 result of the operator is converted to <type>bpchar</type> (<quote>blank-padded
 char</>, the internal name of the <type>character</type> data type) to match the target
-column type.  (Since the types <type>text</type> and
-<type>bpchar</type> are binary-compatible, this conversion does
+column type.  (Since the conversion from <type>text</type> to
+<type>bpchar</type> is binary-coercible, this conversion does
 not insert any real function call.)  Finally, the sizing function
-<literal>bpchar(bpchar, integer)</literal> is found in the system catalog
+<literal>bpchar(bpchar, integer, boolean)</> is found in the system catalog
 and applied to the operator's result and the stored column length.  This
 type-specific function performs the required length check and addition of
 padding spaces.
@@ -755,28 +909,83 @@ padding spaces.
 </sect1>
 
 <sect1 id="typeconv-union-case">
-<title><literal>UNION</literal>, <literal>CASE</literal>, and
-<literal>ARRAY</literal> Constructs</title>
+<title><literal>UNION</literal>, <literal>CASE</literal>, and Related Constructs</title>
+
+<indexterm zone="typeconv-union-case">
+ <primary>UNION</primary>
+ <secondary>determination of result type</secondary>
+</indexterm>
+
+<indexterm zone="typeconv-union-case">
+ <primary>CASE</primary>
+ <secondary>determination of result type</secondary>
+</indexterm>
+
+<indexterm zone="typeconv-union-case">
+ <primary>ARRAY</primary>
+ <secondary>determination of result type</secondary>
+</indexterm>
+
+<indexterm zone="typeconv-union-case">
+ <primary>VALUES</primary>
+ <secondary>determination of result type</secondary>
+</indexterm>
+
+<indexterm zone="typeconv-union-case">
+ <primary>GREATEST</primary>
+ <secondary>determination of result type</secondary>
+</indexterm>
+
+<indexterm zone="typeconv-union-case">
+ <primary>LEAST</primary>
+ <secondary>determination of result type</secondary>
+</indexterm>
+
+<para>
+SQL <literal>UNION</> constructs must match up possibly dissimilar
+types to become a single result set.  The resolution algorithm is
+applied separately to each output column of a union query.  The
+<literal>INTERSECT</> and <literal>EXCEPT</> constructs resolve
+dissimilar types in the same way as <literal>UNION</>.  The
+<literal>CASE</>, <literal>ARRAY</>, <literal>VALUES</>,
+<function>GREATEST</> and <function>LEAST</> constructs use the identical
+algorithm to match up their component expressions and select a result
+data type.
+</para>
+
+<procedure>
+<title>Type Resolution for <literal>UNION</literal>, <literal>CASE</literal>,
+and Related Constructs</title>
 
+<step performance="required">
 <para>
-SQL <literal>UNION</> constructs must match up possibly dissimilar types to
-become a single result set.  The resolution algorithm is applied separately
-to each output column of a union query.  The <literal>INTERSECT</> and
-<literal>EXCEPT</> constructs resolve dissimilar types in the same way as
-<literal>UNION</>.
-A <literal>CASE</> construct uses the identical algorithm to match up its
-component expressions and select a result data type, as does <literal>ARRAY</>.
+If all inputs are of the same type, and it is not <type>unknown</type>,
+resolve as that type.
 </para>
+</step>
 
-<procedure>
-<title><literal>UNION</literal>, <literal>CASE</literal>, and
-<literal>ARRAY</literal> Type Resolution</title>
+<step performance="required">
+<para>
+If any input is of a domain type, treat it as being of the
+domain's base type for all subsequent steps.
+  <footnote>
+   <para>
+    Somewhat like the treatment of domain inputs for operators and
+    functions, this behavior allows a domain type to be preserved through
+    a <literal>UNION</> or similar construct, so long as the user is
+    careful to ensure that all inputs are implicitly or explicitly of that
+    exact type.  Otherwise the domain's base type will be preferred.
+   </para>
+  </footnote>
+</para>
+</step>
 
 <step performance="required">
 <para>
 If all inputs are of type <type>unknown</type>, resolve as type
 <type>text</type> (the preferred type of the string category).
-Otherwise, ignore the <type>unknown</type> inputs while choosing the result type.
+Otherwise, <type>unknown</type> inputs are ignored for the purposes
+of the remaining rules.
 </para>
 </step>
 
@@ -789,14 +998,23 @@ If the non-unknown inputs are not all of the same type category, fail.
 <step performance="required">
 <para>
 Choose the first non-unknown input type which is a preferred type in
-that category or allows all the non-unknown inputs to be implicitly
-converted to it.
+that category, if there is one.
+</para>
+</step>
+
+<step performance="required">
+<para>
+Otherwise, choose the last non-unknown input type that allows all the
+preceding non-unknown inputs to be implicitly converted to it.  (There
+always is such a type, since at least the first type in the list must
+satisfy this condition.)
 </para>
 </step>
 
 <step performance="required">
 <para>
-Convert all inputs to the selected type.
+Convert all inputs to the selected type.  Fail if there is not a
+conversion from a given input to the selected type.
 </para>
 </step>
 </procedure>
@@ -818,7 +1036,7 @@ SELECT text 'a' AS "text" UNION SELECT 'b';
  b
 (2 rows)
 </screen>
-Here, the unknown-type literal <literal>'b'</literal> will be resolved as type <type>text</type>.
+Here, the unknown-type literal <literal>'b'</literal> will be resolved to type <type>text</type>.
 </para>
 </example>
 
@@ -859,23 +1077,53 @@ but <type>integer</> can be implicitly cast to <type>real</>, the union
 result type is resolved as <type>real</>.
 </para>
 </example>
+</sect1>
+
+<sect1 id="typeconv-select">
+<title><literal>SELECT</literal> Output Columns</title>
+
+<indexterm zone="typeconv-select">
+ <primary>SELECT</primary>
+ <secondary>determination of result type</secondary>
+</indexterm>
+
+<para>
+The rules given in the preceding sections will result in assignment
+of non-<type>unknown</> data types to all expressions in a SQL query,
+except for unspecified-type literals that appear as simple output
+columns of a <command>SELECT</> command.  For example, in
+
+<screen>
+SELECT 'Hello World';
+</screen>
+
+there is nothing to identify what type the string literal should be
+taken as.  In this situation <productname>PostgreSQL</> will fall back
+to resolving the literal's type as <type>text</>.
+</para>
+
+<para>
+When the <command>SELECT</> is one arm of a <literal>UNION</>
+(or <literal>INTERSECT</> or <literal>EXCEPT</>) construct, or when it
+appears within <command>INSERT ... SELECT</>, this rule is not applied
+since rules given in preceding sections take precedence.  The type of an
+unspecified-type literal can be taken from the other <literal>UNION</> arm
+in the first case, or from the destination column in the second case.
+</para>
+
+<para>
+<literal>RETURNING</> lists are treated the same as <command>SELECT</>
+output lists for this purpose.
+</para>
+
+<note>
+ <para>
+  Prior to <productname>PostgreSQL</> 10, this rule did not exist, and
+  unspecified-type literals in a <command>SELECT</> output list were
+  left as type <type>unknown</>.  That had assorted bad consequences,
+  so it's been changed.
+ </para>
+</note>
 
 </sect1>
 </chapter>
-
-<!-- Keep this comment at the end of the file
-Local variables:
-mode:sgml
-sgml-omittag:t
-sgml-shorttag:t
-sgml-minimize-attributes:nil
-sgml-always-quote-attributes:t
-sgml-indent-step:1
-sgml-indent-data:t
-sgml-parent-document:nil
-sgml-default-dtd-file:"./reference.ced"
-sgml-exposed-tags:nil
-sgml-local-catalogs:("/usr/lib/sgml/catalog")
-sgml-local-ecat-files:nil
-End:
--->