<chapter Id="typeconv">
<title>Type Conversion</title>

<para>
<acronym>SQL</acronym> queries can, intentionally or not, require
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
to understand the details of the type conversion mechanism.
However, the 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 coercion.
</para>

<para>
This chapter introduces the <productname>PostgreSQL</productname>
type conversion mechanisms and conventions.
Refer to the relevant sections in <xref linkend="datatype"> and <xref linkend="functions">
for more information on specific data types and allowed functions and
operators.
</para>

<para>
The &cite-programmer; has more details on the exact algorithms used for
implicit type conversion and coercion.
</para>

<sect1 id="typeconv-overview">
<title>Overview</title>

<para>
<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.
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.
</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.  Most extended types are first tokenized into
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

<screen>
tgl=> SELECT text 'Origin' AS "Label", point '(0,0)' AS "Value";
 Label  | Value
--------+-------
 Origin | (0,0)
(1 row)
</screen>

has two literal constants, of type <type>text</type> and <type>point</type>.
If a type is not specified for a string literal, then the placeholder type
<firstterm>unknown</firstterm> is assigned initially, to be resolved in later
stages as described below.
</para>

<para>
There are four fundamental <acronym>SQL</acronym> constructs requiring
distinct type conversion rules in the <productname>PostgreSQL</productname>
parser:
</para>

<variablelist>
<varlistentry>
<term>
Operators
</term>
<listitem>
<para>
<productname>PostgreSQL</productname> allows expressions with
prefix and postfix unary (one-argument) operators,
as well as binary (two-argument) operators.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
Function calls
</term>
<listitem>
<para>
Much of the <productname>PostgreSQL</productname> type system is built around a
rich set of functions. Function calls have one or more arguments which, for
any specific query, must be matched to the functions available in the system
catalog.  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>
Query targets
</term>
<listitem>
<para>
<acronym>SQL</acronym> <command>INSERT</command> and <command>UPDATE</command> statements place the results of
expressions into a table. The expressions in the query must be matched up
with, and perhaps converted to, the types of the target columns.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<literal>UNION</literal> and <literal>CASE</literal> constructs
</term>
<listitem>
<para>
Since all select results from a unionized <literal>SELECT</literal> 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 result expressions of a <literal>CASE</> construct must be coerced to
a common type so that the <literal>CASE</> expression as a whole has a known output type.
</para>
</listitem>
</varlistentry>
</variablelist>

<para>
Many of the general type conversion rules use simple conventions built on
the <productname>PostgreSQL</productname> function and operator system tables.
There are some heuristics included in the conversion rules to better support
conventions for the <acronym>SQL</acronym> standard native types such as
<type>smallint</type>, <type>integer</type>, and <type>real</type>.
</para>

<para>
The system catalogs store information about which conversions, called
<firstterm>casts</firstterm>, between data types are valid, and how to
perform those conversions.  Additional casts can be added by the user
with the <command>CREATE CAST</command> 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 should not
be altered.)
</para>

<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
a <firstterm>preferred type</firstterm> which is 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 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.
</para>

<para>
All type conversion rules are designed with several principles in mind:

<itemizedlist>
<listitem>
<para>
Implicit conversions should never have surprising or unpredictable outcomes.
</para>
</listitem>

<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
in the catalog.
</para>
</listitem>

<listitem>
<para>
There should be no extra overhead from 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
without spending extra time in the parser and without introducing unnecessary implicit conversion
functions into the query.
</para>

<para>
Additionally, if a query usually requires an implicit conversion for a function, and
if then the user defines an explicit 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.
</para>
</listitem>
</itemizedlist>
</para>

</sect1>

<sect1 id="typeconv-oper">
<title>Operators</title>

  <para>
   The operand types of an operator invocation are resolved 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.
  </para>

<procedure>
<title>Operand Type Resolution</title>

<step performance="required">
<para>
Select the operators to be considered from the
<classname>pg_operator</classname> system catalog.  If an unqualified
operator name is used (the usual case), the operators
considered are those of the right 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.
</para>

<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
different argument types are considered on an equal footing regardless of
search path position.
</para>
</step>
</substeps>
</step>

<step 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
operators considered), use it.
</para>

<substeps>
<step performance="optional">
<para>
If one argument of a binary operator is <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.
</para>
</step>
</substeps>
</step>

<step performance="required">
<para>
Look for the best match.
</para>
<substeps>
<step performance="required">
<para>
Discard candidate operators for which the input types do not match
and cannot be coerced (using an implicit coercion function) to match.
<type>unknown</type> literals are
assumed to be coercible to anything for this purpose.  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 with the most exact matches
on input types.  Keep all candidates if none have any 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 with the most exact or
binary-compatible matches on input types.  Keep all candidates if none have
any exact or binary-compatible 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 at
the most positions where type coercion will be required.
Keep all candidates if none accept preferred types.
If only one candidate remains, use it; else continue to the next step.
</para>
</step>
<step performance="required">
<para>
If any input arguments are <quote>unknown</quote>, check the type
categories accepted at those argument positions by the remaining
candidates.  At each position, select the "string" 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
all the remaining candidates accept the same type category, select that
category; otherwise fail because the correct choice cannot be deduced
without more clues.  Also note whether any of the candidates accept a
preferred data type within the selected category. Now discard operator
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.
</para>
</step>
<step performance="required">
<para>
If only one candidate remains, use it.  If no candidate or more than one
candidate remains,
then fail.
</para>
</step>
</substeps>
</step>
</procedure>

<bridgehead renderas="sect2">Examples</bridgehead>

<example>
<title>Exponentiation 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:
<screen>
tgl=> SELECT 2 ^ 3 AS "Exp";
 Exp
-----
   8
(1 row)
</screen>

So the parser does a type conversion on both operands and the query
is equivalent to

<screen>
tgl=> SELECT CAST(2 AS double precision) ^ CAST(3 AS double precision) AS "Exp";
 Exp
-----
   8
(1 row)
</screen>

or

<screen>
tgl=> SELECT 2.0 ^ 3.0 AS "Exp";
 Exp
-----
   8
(1 row)
</screen>

<note>
<para>
This last form has the least overhead, since no functions are called to do
implicit type conversion. This is not an issue for small queries, but may
have an impact on the performance of queries involving large tables.
</para>
</note>
</para>
</example>

<example>
<title>String Concatenation Operator Type Resolution</title>

<para>
A string-like syntax is used for working with string types as well as for
working with complex extended types.
Strings with unspecified type are matched with likely operator candidates.
</para>

<para>
An example with one unspecified argument:
<screen>
tgl=> SELECT text 'abc' || 'def' AS "Text and Unknown";
 Text and Unknown
------------------
 abcdef
(1 row)
</screen>
</para>

<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>.
</para>

<para>
Concatenation on unspecified types:
<screen>
tgl=> SELECT 'abc' || 'def' AS "Unspecified";
 Unspecified
-------------
 abcdef
(1 row)
</screen>
</para>

<para>
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 
<quote>preferred type</quote> for strings, <type>text</type>, is used as the specific
type to resolve the unknown literals to.
</para>
</example>

<example>
<title>Absolute-Value and Factorial Operator Type Resolution</title>

<para>
The <productname>PostgreSQL</productname> operator catalog has several
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:
<screen>
tgl=> select @ text '-4.5' as "abs";
 abs
-----
 4.5
(1 row)
</screen>
Here the system has performed an implicit text-to-float8 conversion
before applying the chosen operator.  We can verify that float8 and
not some other type was used:
<screen>
tgl=> select @ text '-4.5e500' as "abs";
ERROR:  Input '-4.5e500' is out of range for float8
</screen>
</para>

<para>
On the other hand, the postfix operator <literal>!</> (factorial)
is defined only for integer data types, not for float8.  So, if we
try a similar case with <literal>!</>, we get:
<screen>
tgl=> select text '20' ! as "factorial";
ERROR:  Unable to identify a postfix operator '!' for type 'text'
        You may need to add parentheses or an explicit cast
</screen>
This happens because the system can't decide which of the several
possible <literal>!</> operators should be preferred.  We can help
it out with an explicit cast:
<screen>
tgl=> select cast(text '20' as int8) ! as "factorial";
      factorial
---------------------
 2432902008176640000
(1 row)
</screen>
</para>
</example>

</sect1>

<sect1 id="typeconv-func">
<title>Functions</title>

  <para>
   The argument types of function calls are resolved according to the
   following steps.
  </para>

<procedure>
<title>Function Argument Type Resolution</title>

<step performance="required">
<para>
Select the functions to be considered from the
<classname>pg_proc</classname> system catalog.  If an unqualified
function name is used, the functions
considered are those of the right 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.
</para>

<substeps>
<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
different argument types are considered on an equal footing regardless of
search path position.
</para>
</step>
</substeps>
</step>

<step performance="required">
<para>
Check for a function accepting exactly the input argument types.
If one exists (there can be only one exact match in the set of
functions considered), use it.
(Cases involving <type>unknown</type> will never find a match at
this step.)
</para></step>
<step performance="required">
<para>
If no exact match is found, see whether the function call appears
to be a trivial type coercion 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 coerced
to the named data type without any explicit function call.
</para>
</step>
<step performance="required">
<para>
Look for the best match.
</para>
<substeps>
<step performance="required">
<para>
Discard candidate functions for which the input types do not match
and cannot be coerced (using an implicit coercion function) to match.
<type>unknown</type> literals are
assumed to be coercible to anything for this purpose.  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 with the most exact matches
on input types.  Keep all candidates if none have any 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 with the most exact or
binary-compatible matches on input types.  Keep all candidates if none have
any exact or binary-compatible 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 at
the most positions where type coercion will be required.
Keep all candidates if none accept preferred types.
If only one candidate remains, use it; else continue to the next step.
</para>
</step>
<step performance="required">
<para>
If any input arguments are <type>unknown</type>, check the type 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 all the remaining candidates accept the same type category,
select that category; otherwise fail because
the correct choice cannot be deduced without more clues.  Also note whether
any of the candidates accept a preferred data type within the selected category.
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.
</para>
</step>
<step performance="required">
<para>
If only one candidate remains, use it.  If no candidate or more than one
candidate remains,
then fail.
</para>
</step>
</substeps>
</step>
</procedure>

<bridgehead renderas="sect2">Examples</bridgehead>

<example>
<title>Factorial Function Argument Type Resolution</title>

<para>
There is only one <function>int4fac</function> function defined in the
<classname>pg_proc</classname> catalog.
So the following query automatically converts the <type>int2</type> argument
to <type>int4</type>:

<screen>
tgl=> SELECT int4fac(int2 '4');
 int4fac
---------
      24
(1 row)
</screen>

and is actually transformed by the parser to
<screen>
tgl=> SELECT int4fac(int4(int2 '4'));
 int4fac
---------
      24
(1 row)
</screen>
</para>
</example>

<example>
<title>Substring Function Type Resolution</title>

<para>
There are two <function>substr</function> functions declared in <classname>pg_proc</classname>. However,
only one takes two arguments, of types <type>text</type> and <type>int4</type>.
</para>

<para>
If called with a string constant of unspecified type, the type is matched up
directly with the only candidate function type:
<screen>
tgl=> SELECT substr('1234', 3);
 substr
--------
     34
(1 row)
</screen>
</para>

<para>
If the string is declared to be of type <type>varchar</type>, as might be the case
if it comes from a table, then the parser will try to coerce it to become <type>text</type>:
<screen>
tgl=> SELECT substr(varchar '1234', 3);
 substr
--------
     34
(1 row)
</screen>
which is transformed by the parser to become
<screen>
tgl=> SELECT substr(text(varchar '1234'), 3);
 substr
--------
     34
(1 row)
</screen>
</para>
<para>
<note>
<para>
Actually, the parser is aware that <type>text</type> and <type>varchar</type>
are <firstterm>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.
</para>
</note>
</para>

<para>
And, if the function is called with an <type>int4</type>, the parser will
try to convert that to <type>text</type>:
<screen>
tgl=> SELECT substr(1234, 3);
 substr
--------
     34
(1 row)
</screen>
which actually executes as
<screen>
tgl=> SELECT substr(text(1234), 3);
 substr
--------
     34
(1 row)
</screen>
This succeeds because there is a conversion function text(int4) in the
system catalog.
</para>
</example>

</sect1>

<sect1 id="typeconv-query">
<title>Query Targets</title>

  <para>
   Values to be inserted into a table are coerced to the destination
   column's data type according to the
   following steps.
  </para>

<procedure>
<title>Query Target Type Resolution</title>

<step performance="required">
<para>
Check for an exact match with the target.
</para></step>
<step performance="required">
<para>
Otherwise, try to coerce the expression to the target type.  This will succeed
if the two types are known binary-compatible, or if there is a conversion
function.  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></step>

<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 an
integer, and returning the same type.  If one is found, it is applied,
passing the column's declared length as the second parameter.
</para></step>

</procedure>

<example>
<title><type>character</type> Storage Type Conversion</title>

<para>
For a target column declared as <type>character(20)</type> the following query
ensures that the target is sized correctly:

<screen>
tgl=> CREATE TABLE vv (v character(20));
CREATE
tgl=> INSERT INTO vv SELECT 'abc' || 'def';
INSERT 392905 1
tgl=> SELECT v, length(v) FROM vv;
          v           | length
----------------------+--------
 abcdef               |     20
(1 row)
</screen>

What has really happened here is that the two unknown literals are resolved
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 coerced to <type>bpchar</type> (<quote>blank-padded
char</>, the internal name of the character data type) to match the target
column type.  (Since the parser knows that <type>text</type> and
<type>bpchar</type> are binary-compatible, this coercion is implicit and does
not insert any real function call.)  Finally, the sizing function
<literal>bpchar(bpchar, integer)</literal> is found in the system catalogs
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.
</para>
</example>
</sect1>

<sect1 id="typeconv-union-case">
<title><literal>UNION</> and <literal>CASE</> Constructs</title>

<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 also uses the identical algorithm to match up its
component expressions and select a result data type.
</para>
<procedure>
<title><literal>UNION</> and <literal>CASE</> Type Resolution</title>

<step performance="required">
<para>
If all inputs are of type <type>unknown</type>, resolve as type
<type>text</type> (the preferred type for string category).
Otherwise, ignore the <type>unknown</type> inputs while choosing the type.
</para></step>

<step performance="required">
<para>
If the non-unknown inputs are not all of the same type category, fail.
</para></step>

<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
coerced to it.
</para></step>

<step performance="required">
<para>
Coerce all inputs to the selected type.
</para></step>
</procedure>

<bridgehead renderas="sect2">Examples</bridgehead>

<example>
<title>Underspecified Types in a Union</title>

<para>
<screen>
tgl=> SELECT text 'a' AS "Text" UNION SELECT 'b';
 Text
------
 a
 b
(2 rows)
</screen>
Here, the unknown-type literal <literal>'b'</literal> will be resolved as type text.
</para>
</example>

<example>
<title>Type Conversion in a Simple Union</title>

<para>
<screen>
tgl=> SELECT 1.2 AS "Numeric" UNION SELECT 1;
 Numeric
---------
       1
     1.2
(2 rows)
</screen>
The literal <literal>1.2</> is of type <type>numeric</>,
and the integer value <literal>1</> can be cast implicitly to
<type>numeric</>, so that type is used.
</para>
</example>

<example>
<title>Type Conversion in a Transposed Union</title>

<para>
<screen>
tgl=> SELECT 1 AS "Real"
tgl-> UNION SELECT CAST('2.2' AS REAL);
 Real
------
    1
  2.2
(2 rows)
</screen>
Here, since type <type>real</> cannot be implicitly cast to <type>integer</>,
but <type>integer</> can be implicitly cast to <type>real</>, the union
result type is resolved as <type>real</>.
</para>
</example>

</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:
-->
