Sub topic 16
Casting enums and domains
This chapter assumes you know the cast syntaxes (CAST, ::, typed literals), the implicit, assignment and explicit cast contexts, and how unknown-type literals resolve. It also assumes you can read pg_cast. Enums and domains are user-defined types, so they have fewer built-in conversions than the standard types. The rules for them follow from the contexts you already know.
Enums convert through their text form
An enum is an ordered set of labels. PostgreSQL has no pg_cast row between an enum and anything else. Conversions use the automatic I/O conversion path, which passes the value through the type's text input and output functions.
CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
SELECT 'happy'::mood AS from_literal,
'happy'::mood::text AS to_text,
mood 'ok' AS typed_literal;An unknown label fails at conversion time:
SELECT 'meh'::mood;
-- ERROR: invalid input value for enum mood: "meh"The I/O conversion rules set the cast context:
| Direction | Context | Consequence |
|---|---|---|
| enum to text, varchar, char | assignment | Storing an enum in a text column works without a cast. |
| text, varchar, char to enum | explicit only | A text-typed expression needs `::mood` before it can be stored or compared. |
The second row catches people. An untyped literal such as 'ok' is not yet text, so PostgreSQL resolves it as mood. A value that already has type text does not get that treatment.
CREATE TABLE diary (day date, felt mood);
INSERT INTO diary VALUES ('2026-11-27', 'ok'); -- works: unknown literal
INSERT INTO diary SELECT DATE '2026-11-26', 'ok'::text; -- fails
-- ERROR: column "felt" is of type mood but expression is of type text
INSERT INTO diary SELECT DATE '2026-11-26', 'ok'::text::mood; -- worksComparisons and function calls follow the same rule, because operator resolution only uses implicit casts:
SELECT count(*) FROM diary WHERE felt = 'ok'; -- works
SELECT count(*) FROM diary WHERE felt = 'ok'::text; -- operator does not exist: mood = text
SELECT count(*) FROM diary WHERE felt = 'ok'::text::mood; -- works
SELECT upper(felt) FROM diary; -- function upper(mood) does not exist
SELECT upper(felt::text) FROM diary; -- worksWhen you must compare an enum with a text value, cast the text side to the enum. If you cast the enum column to text instead, a plain B-tree index on that column cannot be used for the predicate. The wrong label then raises an error rather than quietly matching nothing, and that is usually what you want.
Enum order and numeric positions
There is no cast from an enum to an integer. Enum values sort in declaration order, not alphabetical order, so comparison operators already work on them. For the position itself, use the enum support functions.
SELECT 'happy'::mood > 'sad'::mood AS happier,
enum_range(NULL::mood) AS all_labels,
array_position(enum_range(NULL::mood), 'ok'::mood) AS position_of_ok;This returns true, {sad,ok,happy} and 2. enum_range(NULL::mood) uses the null only to name the type. If you need the position often, store it in a lookup table instead of recomputing it.
Domains apply their constraints during conversion
A domain is a base type plus optional NOT NULL, DEFAULT and CHECK rules. Converting a value to a domain first converts it to the base type, then checks the constraints.
CREATE DOMAIN positive_int AS integer CHECK (VALUE > 0);
SELECT '5'::positive_int AS ok,
pg_typeof('5'::positive_int) AS type_of_value,
pg_typeof('5'::positive_int + 1) AS type_after_math;type_of_value is positive_int. type_after_math is integer, because operator and function resolution treats a domain as its base type, so the result of arithmetic is the base type. A failing value raises an error that names the constraint:
SELECT '-1'::positive_int;
-- ERROR: value for domain positive_int violates check constraint "positive_int_check"The check also runs whenever a value is assigned to a domain-typed column, including a plain integer:
CREATE TABLE items (qty positive_int);
INSERT INTO items VALUES (3); -- works
INSERT INTO items SELECT 0; -- fails: violates check constraint "positive_int_check"
SELECT qty::bigint FROM items; -- works: domain is read as integer, then convertedGoing the other way, from a domain to its base type or onward to any type the base type reaches, needs no special handling.
Domains over other types
A domain can wrap any type, including an enum or varchar(n). Casting to it converts to the underlying type first. For varchar(n), that follows the length rules from the text conversion chapter, so an explicit cast truncates and an assignment raises an error. Then the domain's checks run.
CREATE CAST does not help with domains. The PostgreSQL documentation states that casts to or from a domain have no effect and that PostgreSQL uses the casts of the underlying type. To customize conversion for a domain, put the cast on the base type, or write a function.
Defining a cast for an enum
Since no built-in cast links an enum to boolean, the conversion fails until you create one:
CREATE TYPE yesno AS ENUM ('yes', 'no');
SELECT 'yes'::yesno::boolean;
-- ERROR: cannot cast type yesno to boolean
CREATE FUNCTION yesno_to_bool(yesno) RETURNS boolean
LANGUAGE sql IMMUTABLE AS $$ SELECT $1 = 'yes' $$;
CREATE CAST (yesno AS boolean) WITH FUNCTION yesno_to_bool(yesno);
SELECT 'yes'::yesno::boolean AS result; -- trueYou must own the source or the target type to create a cast, and here you own yesno. Without a context clause the cast is explicit only. AS ASSIGNMENT or AS IMPLICIT widen it, and implicit casts can change how existing expressions resolve, so they are rarely worth it. After the cast exists, this query finds one row for the type:
SELECT castsource::regtype, casttarget::regtype, castcontext
FROM pg_cast
WHERE castsource = 'yesno'::regtype;The castcontext column shows e, which means explicit.
Common errors
column "x" is of type mood but expression is of type text: add a::moodcast to the text-typed expression.operator does not exist: mood = text: cast the text side to the enum, not the enum to text, to keep index use.invalid input value for enum: the label is not in the type. Check for case and trailing spaces.value for domain ... violates check constraint: the value converted fine but failed the domain's rule, so fix the data or the rule.cannot cast type X to Y: nopg_castentry or I/O path exists, and you need a function orCREATE CAST.
Exercise
A table has a column status of an enum type order_status. A query does WHERE status = $1, and the driver sends the parameter with type text. It fails with "operator does not exist: order_status = text". Give a fix that still allows an index on status to be used, and say why the other obvious fix is worse.
Show answer
Cast the parameter to the enum: WHERE status = $1::order_status. The column stays bare, so a B-tree index on status can be used. The other fix, WHERE status::text = $1, applies a cast to the indexed column, which hides it from a plain index.
Exercise
Given CREATE DOMAIN positive_int AS integer CHECK (VALUE > 0);, what does pg_typeof('5'::positive_int + 1) return, and does '0'::positive_int + 1 raise an error?
Show answer
The first returns integer, because arithmetic on a domain uses the base type. The second does raise an error, because '0'::positive_int is evaluated first and 0 violates the check constraint before the addition happens.