CREATE CAST
Defines a new cast.
Synopsis
CREATE CAST (<sourcetype> AS <targettype>)
WITH FUNCTION <funcname> (<argtype> [, ...])
[AS ASSIGNMENT | AS IMPLICIT]
CREATE CAST (<sourcetype> AS <targettype>)
WITHOUT FUNCTION
[AS ASSIGNMENT | AS IMPLICIT]
CREATE CAST (<sourcetype> AS <targettype>)
WITH INOUT
[AS ASSIGNMENT | AS IMPLICIT]
Description
CREATE CAST
defines a new cast. A cast specifies how to perform a conversion between two data types. For example,
SELECT CAST(42 AS float8);
converts the integer constant 42
to type float8
by invoking a previously specified function, in this case float8(int4)
. If no suitable cast has been defined, the conversion fails.
Two types may be binary coercible, which means that the types can be converted into one another without invoking any function. This requires that corresponding values use the same internal representation. For instance, the types text
and varchar
are binary coercible in both directions. Binary coercibility is not necessarily a symmetric relationship. For example, the cast from xml
to text
can be performed for free in the present implementation, but the reverse direction requires a function that performs at least a syntax check. (Two types that are binary coercible both ways are also referred to as binary compatible.)
You can define a cast as an I/O conversion cast by using the WITH INOUT
syntax. An I/O conversion cast is performed by invoking the output function of the source data type, and passing the resulting string to the input function of the target data type. In many common cases, this feature avoids the need to write a separate cast function for conversion. An I/O conversion cast acts the same as a regular function-based cast; only the implementation is different.
By default, a cast can be invoked only by an explicit cast request, that is an explicit CAST(x AS
typename)
or x:: typename
construct.
If the cast is marked AS ASSIGNMENT
then it can be invoked implicitly when assigning a value to a column of the target data type. For example, supposing that foo.f1
is a column of type text
, then:
INSERT INTO foo (f1) VALUES (42);