Sub topic 17
Defining Your Own Casts with `CREATE CAST`
Assume you know basic SQL and common PostgreSQL types. This chapter shows how to add an explicit conversion when PostgreSQL does not already provide one.
Why create a custom cast?
PostgreSQL already knows many conversions, such as integer to numeric and text to date. A custom cast connects two types with a conversion function that you define.
For example, an application might store the values yes and no in an enum but need to use them as a Boolean:
A cast has three parts:
- A source type.
- A target type.
- A function that accepts the source type and returns the target type.
Define a cast function
First, create the source type and a conversion function:
CREATE TYPE yesno AS ENUM ('yes', 'no');
CREATE FUNCTION yesno_to_bool(yesno)
RETURNS boolean
LANGUAGE sql
IMMUTABLE
STRICT
AS $$
SELECT $1 = 'yes'::yesno
$$;IMMUTABLE tells PostgreSQL that the same input always produces the same output. This lets PostgreSQL use the function in indexes and other optimizations. STRICT means that a null input produces a null result without calling the function.
Now register the conversion:
CREATE CAST (yesno AS boolean)
WITH FUNCTION yesno_to_bool(yesno);The cast is explicit by default. You can use it like this:
SELECT 'yes'::yesno::boolean AS result;The result is true.
You can also use standard CAST syntax:
SELECT CAST('no'::yesno AS boolean) AS result;Choose the cast context carefully
A cast can have one of three contexts:
| Context | Meaning | Typical use |
|---|---|---|
| Explicit | The query must request the conversion | Safe, unusual conversions |
| Assignment | PostgreSQL may convert while storing a value | Compatible column assignments |
| Implicit | PostgreSQL may insert the conversion during expression resolution | Nearly interchangeable types |
Omitting the context creates an explicit-only cast. This is usually the safest choice. Adding AS ASSIGNMENT or AS IMPLICIT can make inserts, operators, and function calls behave differently throughout the database.
Function requirements and limitations
The conversion function must accept exactly one argument of the source type and return exactly the target type. It can be a SQL, PL/pgSQL, or compiled-language function.
A custom cast does not automatically validate business rules. The function must reject or handle invalid states itself. Also consider whether the conversion loses information. Converting a detailed type to a Boolean, for example, cannot preserve every original value.
To inspect registered casts, query pg_cast:
SELECT castsource::regtype,
casttarget::regtype,
castcontext
FROM pg_cast
WHERE castsource = 'yesno'::regtype;Exercise
Why is an explicit-only custom cast usually safer than an implicit cast?
Show answer
It requires the query author to request the conversion, so PostgreSQL is less likely to choose the custom conversion unexpectedly during operator or function resolution.