Sub topic 12
Result types in UNION, CASE and ARRAY
This chapter assumes you know the implicit, assignment and explicit cast contexts, and that an untyped literal such as '2' has type unknown until PostgreSQL resolves it. You should also be comfortable with pg_typeof().
One result type from many inputs
Some constructs take several expressions and must produce one value type:
UNION,INTERSECTandEXCEPT, one type per output columnCASECOALESCE,GREATESTandLEASTVALUESlistsARRAY[...]constructors
PostgreSQL does not pick a type from the first input alone. It applies one set of rules to all of these constructs. The rules differ from operator resolution, which looks for a matching operator signature. Here the server looks for a common type that every input can reach through implicit casts.
The resolution rules
PostgreSQL works through these steps in order.
- If all inputs have the same type and it is not
unknown, that type is the result. - If an input is a domain, it is treated as its base type.
- If every input is
unknown, the result istext. Otherwiseunknowninputs are set aside for the remaining steps. - If the remaining inputs belong to different type categories (numeric, string, date/time, boolean and so on), resolution fails.
- The first remaining input type becomes the candidate. For each later type, if the candidate converts implicitly to it but not the other way, that type becomes the new candidate. Resolution stops early if the candidate is a preferred type of its category, such as
float8for numerics ortimestamptzfor date/time. - Every input is converted to the final candidate. If any input has no implicit cast to it, resolution fails.
Seeing the rules work
Use pg_typeof to check what the server chose.
SELECT pg_typeof(CASE WHEN true THEN 1 ELSE 2.5 END) AS case_type,
pg_typeof(COALESCE(1, 2.5::float8)) AS coalesce_type,
pg_typeof(GREATEST(1::int, 2::bigint)) AS greatest_type,
pg_typeof(ARRAY[1, 2.5]) AS array_type;The results are numeric, double precision, bigint and numeric[].
integerconverts implicitly tonumeric, butnumericconverts tointegeronly on assignment. Sonumericwins.integerandfloat8resolve tofloat8.integerandbigintresolve tobigint.
The order of inputs does not change the outcome when one type is clearly reachable from all the others. It can matter when two types have no implicit cast between them. In that case step 6 fails instead of picking one.
Unknown literals
SELECT pg_typeof(CASE WHEN true THEN 'a' ELSE 'b' END) AS all_unknown;
SELECT pg_typeof(ARRAY['a', 'b']) AS array_unknown;
SELECT pg_typeof(CASE WHEN true THEN 1 ELSE '2' END) AS mixed;The first two return text and text[], because all inputs are unknown. The third returns integer. The literal '2' is set aside, the result becomes integer, and '2' is then parsed as an integer.
That last behavior causes a common error:
SELECT CASE WHEN true THEN 1 ELSE 'n/a' END;
-- ERROR: invalid input syntax for type integer: "n/a"The error comes from parsing 'n/a' as an integer, not from a failed type match. The fix is to make the intended type explicit:
SELECT CASE WHEN true THEN 1::text ELSE 'n/a' END AS label;UNION
Each output column of a UNION is resolved separately. The first branch does not decide the column type.
SELECT 1 AS v
UNION ALL
SELECT 2.5
UNION ALL
SELECT 3::bigint;The column is numeric. A chain of set operations is resolved pairwise from left to right unless parentheses say otherwise. Here integer and numeric give numeric, and then numeric and bigint give numeric.
Pairwise resolution can produce surprises with many branches. Check the final type with pg_typeof on a wrapped subquery:
SELECT pg_typeof(v) AS t
FROM (SELECT 1 AS v UNION ALL SELECT 2.5) AS s
LIMIT 1;Mismatched categories fail with a message that names the construct:
SELECT 1 AS v
UNION
SELECT 'x'::text;
-- ERROR: UNION types integer and text cannot be matchedCASE and ARRAY produce equivalent messages: CASE types integer and text cannot be matched and ARRAY types integer and text cannot be matched.
Typed text column versus literal
A typed column and an untyped literal resolve to the column's type. If you union a date column with 'not known', PostgreSQL tries to parse the literal as a date and raises an error. When the literal is meant as text, cast it, and cast the column to text too.
ARRAY constructors
ARRAY[...] uses the same rules for its elements.
SELECT pg_typeof(ARRAY[1, 2, 3]) AS ints,
pg_typeof(ARRAY[1, 2.5]) AS nums,
pg_typeof(ARRAY[ARRAY[1, 2], ARRAY[3, 4.5]]) AS nested;The results are integer[], numeric[] and numeric[].
An empty constructor has no elements to resolve, so you must supply the type:
SELECT ARRAY[]::integer[] AS empty_ints;
-- SELECT ARRAY[] fails: cannot determine type of empty arrayLengths and modifiers
When the inputs are varchar or numeric with modifiers, such as varchar(2) and varchar(5), the result keeps a modifier only if all inputs agree. Otherwise it becomes plain varchar or numeric. No truncation happens in a UNION, so long values pass through.
| Inputs | Result type | Why |
|---|---|---|
| `integer`, `numeric` | `numeric` | integer converts implicitly to numeric |
| `integer`, `float8` | `float8` | float8 is the preferred numeric type |
| `date`, `timestamp` | `timestamp` | date converts implicitly to timestamp |
| `text`, `unknown` | `text` | unknown literal is parsed as text |
| `integer`, `unknown` | `integer` | unknown literal is parsed as integer |
| `integer`, `text` | error | different type categories |
| `integer`, `boolean` | error | different type categories |
Common mistakes
- Assuming the first branch sets the type. Branches are compared, and a later
numericbranch can widen an earlierinteger. - Mixing a string literal with a number in
CASE. The literal is parsed as the number. Cast the number totextif you want a label. - Using a bare
ARRAY[]. Always cast it. - Using
UNIONwhenUNION ALLis enough. This is not a casting error, butUNIONalso sorts or hashes to remove duplicates. That adds cost, and it needs an equality operator for the resolved type.
Exercise
What are the types of SELECT CASE WHEN true THEN 1 ELSE 2.5 END and SELECT CASE WHEN true THEN 1 ELSE 'two' END, and why does the second one fail?
Show answer
The first is numeric, because integer converts implicitly to numeric but not the reverse. The second resolves to integer, since the literal 'two' is unknown and set aside. PostgreSQL then tries to parse 'two' as an integer and raises "invalid input syntax for type integer". Writing 1::text makes the result text.
Exercise
A query unions a date column with a timestamptz column. What type does the result column have, and does the order of the branches matter?
Show answer
The result is timestamptz. date converts implicitly to timestamp and timestamptz, and timestamp converts implicitly to timestamptz, so timestamptz is the type all inputs can reach. Because timestamptz is the preferred type of the date/time category, the order of the branches does not change the result.
Exercise
Why does SELECT ARRAY[] fail, and how do you fix it?
Show answer
An empty constructor has no elements from which to infer an element type. Cast it, for example ARRAY[]::integer[].