Sub topic 3
Listing enum values with enum_range, enum_first, and enum_last
This chapter assumes you can create an enum type and use it as a column type, as covered earlier in this tutorial. You should also know basic SELECT, JOIN, and GROUP BY syntax. Familiarity with PostgreSQL arrays helps but is not required, because the chapter introduces the few array features it needs.
By the end you will be able to:
- Ask PostgreSQL for the labels of an enum type from inside a query.
- Take a sub-range of labels, and an open-ended range, with two-argument
enum_range. - Turn the array result into rows, for reports and for test data.
- Read the same information from the system catalog.
- Avoid the errors people hit most often with these functions.
Why you need to list enum labels
An enum type is a fixed, ordered list of labels. Sooner or later a query, an application, or a script needs that list. Typical cases are:
- Filling a dropdown in a user interface.
- Building a report with one row per status, including statuses that no row currently uses.
- Generating random test data.
- Checking in a migration script that a label exists.
You could hard-code the labels in each place. The copies then drift out of date when someone adds a label. PostgreSQL ships three built-in functions that read the list from the type itself.
| Function | Arguments | Returns |
|---|---|---|
| `enum_first(anyenum)` | a value of the enum type | the first label in sort order |
| `enum_last(anyenum)` | a value of the enum type | the last label in sort order |
| `enum_range(anyenum)` | a value of the enum type | an array of all labels, in sort order |
| `enum_range(anyenum, anyenum)` | two values of the same enum type | an array of the labels from the first value to the second, inclusive |
All four return values of the enum type itself (or an array of it). They do not return plain text. That detail matters later.
Set up a table to experiment with
The examples use the order_status type from the first chapter. Run this in a scratch database. If the type and table already exist from earlier work, skip the first two statements and empty the table with TRUNCATE orders; before the insert.
CREATE TYPE order_status AS ENUM ('pending', 'paid', 'shipped', 'delivered', 'cancelled');
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status order_status NOT NULL DEFAULT 'pending'
);
INSERT INTO orders (status)
VALUES ('paid'), ('paid'), ('shipped'), ('cancelled');The table now holds four orders. No order is pending and none is delivered. That gap is useful in the reporting example below.
The NULL::type idiom
Every one of these functions takes an argument, yet usually you want the labels of the type and have no particular value in mind. The convention is to pass a NULL cast to the type:
SELECT enum_range(NULL::order_status);Result:
{pending,paid,shipped,delivered,cancelled}The function does not look at the value. It uses only the argument's data type to find which enum you mean. That is why NULL::order_status works: it carries the type and nothing else. It also works on an empty table and needs no row to exist.
You can pass a real value instead, such as a column. enum_range(status) works too, because status has the type order_status. Used in a SELECT over orders, though, it returns the same full array once per row, which is rarely what you want.
These functions do not return NULL for a NULL input. They are written to accept NULL, because the type is all they need.
enum_first and enum_last
These two return a single label:
SELECT enum_first(NULL::order_status) AS first_label,
enum_last(NULL::order_status) AS last_label;Result:
first_label | last_label
-------------+------------
pending | cancelled"First" and "last" refer to declaration order, the order in which the labels appear in CREATE TYPE (adjusted by any BEFORE or AFTER placement of later additions). They do not refer to alphabetical order. Alphabetically, cancelled would come first. Here it is last because it was declared last.
A practical use is a default or a boundary check. For example, a query can ask for every order that has moved past the first stage:
SELECT id, status
FROM orders
WHERE status > enum_first(NULL::order_status);Because the comparison uses declaration order, this returns every order whose status is not pending. The query keeps working if someone later adds a new first label, whereas a hard-coded 'pending' would not.
enum_range with one argument
With one argument, enum_range returns every label in order, as an array of the enum type. The result type is order_status[].
Because it is a real array, the usual array tools work on it:
SELECT cardinality(enum_range(NULL::order_status)) AS label_count,
(enum_range(NULL::order_status))[2] AS second_label,
array_position(enum_range(NULL::order_status), 'paid'::order_status) AS paid_position;Result:
label_count | second_label | paid_position
-------------+--------------+---------------
5 | paid | 2PostgreSQL arrays are numbered from 1 by default, so the second label is at index 2. The cast 'paid'::order_status in array_position keeps the types explicit.
Labels that contain spaces or other special characters appear in double quotes when the array is printed, for example {pending,"in progress",done}. The quotes belong to the array's text format. They are not part of the labels.
enum_range with two arguments
With two arguments, enum_range returns the labels from the first value through the second, both ends included, in sort order:
SELECT enum_range('paid'::order_status, 'delivered'::order_status);Result:
{paid,shipped,delivered}You can leave either end open by passing NULL. A NULL first argument starts at the first label of the type. A NULL second argument runs to the last label:
SELECT enum_range(NULL, 'paid'::order_status) AS up_to_paid,
enum_range('shipped'::order_status, NULL) AS from_shipped;Result:
up_to_paid | from_shipped
--------------------------+------------------------
{pending,paid} | {shipped,delivered,cancelled}PostgreSQL works out the enum type from the argument that is not NULL, so one end must carry a type.
If the first value sorts after the second, the result is an empty array, not an error:
SELECT enum_range('delivered'::order_status, 'paid'::order_status);Result:
{}An empty array can hide a mistake. If you build the two ends from variables or columns, check the order of the arguments when you get {} unexpectedly.
The diagram shows how the functions relate to the stored order of labels.
Using ranges in a query
A range array pairs well with the = ANY operator, which tests whether a value appears in an array:
SELECT id, status
FROM orders
WHERE status = ANY (enum_range('paid'::order_status, 'shipped'::order_status));This returns the three orders that are paid or shipped. The range is written in terms of workflow stages. It follows the type's order if a label is later inserted between paid and shipped, which a hand-written IN ('paid', 'shipped') list would not.
The earlier chapter on ordering showed that status >= 'paid' AND status < 'delivered' also works. Both forms are fine. Use the range form when you want the labels as a value, for example to pass them to another function. Use comparison operators when the filter is all you need, since they can use a normal index on the column.
Turning the array into rows
An array is awkward in a report. unnest converts it into one row per element:
SELECT unnest(enum_range(NULL::order_status)) AS status;Result:
status
-----------
pending
paid
shipped
delivered
cancelledThe column keeps the type order_status, so sorting it uses declaration order. If you need the position as well, add WITH ORDINALITY:
SELECT s.position, s.status
FROM unnest(enum_range(NULL::order_status)) WITH ORDINALITY AS s(status, position)
ORDER BY s.position;The column list s(status, position) names the value column first and the counter second. This is the reverse of the order in which a person might say it, so check it if the columns look swapped.
A report that includes unused labels
A plain GROUP BY status on orders omits any status with no rows. To list every status, including zero counts, use the enum list as the left side of an outer join:
SELECT s.status, count(o.id) AS orders
FROM unnest(enum_range(NULL::order_status)) AS s(status)
LEFT JOIN orders o ON o.status = s.status
GROUP BY s.status
ORDER BY s.status;Result:
status | orders
-----------+--------
pending | 0
paid | 2
shipped | 1
delivered | 0
cancelled | 1count(o.id) counts only non-NULL ids, so a status with no matching orders yields 0. Counting count(*) would report 1 for those rows, because the left join still produces one row for them. This is a frequent bug in this kind of query.
Random test data
You can pick a random label by indexing into the array:
INSERT INTO orders (status)
SELECT (enum_range(NULL::order_status))[1 + floor(random() * 5)::int]
FROM generate_series(1, 10);The literal 5 ties the query to the current label count. A version that tracks the type reads the length from the array:
INSERT INTO orders (status)
SELECT labels[1 + floor(random() * cardinality(labels))::int]
FROM (SELECT enum_range(NULL::order_status) AS labels) AS l,
generate_series(1, 10);Getting text instead of enum values
Some tools and drivers expect plain text. Cast the array or the unnested values:
SELECT enum_range(NULL::order_status)::text[];
SELECT unnest(enum_range(NULL::order_status))::text AS label;The cast to text[] is allowed as an explicit cast. Casting to text also removes the enum ordering from the result column. Sorting the text column sorts alphabetically. If you need declaration order, sort before you cast, or sort on the enum column.
Reading the system catalog
The functions are convenient, but PostgreSQL stores the labels in the system catalog table pg_enum. Querying it directly gives extra information, such as the internal sort position:
SELECT enumsortorder, enumlabel
FROM pg_enum
WHERE enumtypid = 'order_status'::regtype
ORDER BY enumsortorder;Each row is one label. enumtypid identifies the type, and 'order_status'::regtype converts the type name to that identifier, respecting the current search_path. enumsortorder is a real number, not an integer. When a label is inserted between two others, PostgreSQL picks a value between their numbers, so you will see fractions such as 2.5. Treat the values as a sort key only. Do not rely on them as positions, and use enum_range or WITH ORDINALITY when you need a count or position.
In psql, the command \dT+ order_status prints the same labels without writing any SQL.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `could not determine polymorphic type because input has type unknown` | You passed an untyped literal, such as `enum_range('paid', 'delivered')`. | Cast at least one argument: `'paid'::order_status`. |
| `invalid input value for enum order_status: "..."` | The label you cast does not exist in the type. | Check the spelling against `enum_range(NULL::order_status)`. |
| An empty array `{}` from a two-argument call | The first value sorts after the second. | Swap the arguments, or check the order with a comparison. |
| Zero-count rows show 1 in a report | `count(*)` counts the outer-join row. | Use `count(o.id)`. |
| Text sort differs from enum sort | The column was cast to text before sorting. | Sort on the enum column, or sort before the cast. |
| `enum_range` returns the list for the wrong schema | The type name resolved through `search_path` to another schema. | Schema-qualify the type, for example `NULL::shop.order_status`. |
Exercises
Exercise
Write a query that returns the labels of order_status from 'shipped' to the end of the type, one label per row, without naming 'delivered' or 'cancelled'. What does it return for the type defined in this chapter?
Show answer
SELECT unnest(enumrange('shipped'::orderstatus, NULL)) AS status; The NULL second argument runs the range to the last label, so the result has three rows in declaration order: shipped, delivered, cancelled.
Exercise
A colleague wants one row per orderstatus label with the number of orders in that status, including labels with no orders. Their query joins orders to unnest(enumrange(NULL::order_status)) with a LEFT JOIN but uses count(*), and the empty statuses show 1 instead of 0. Explain why and give the fix.
Show answer
The LEFT JOIN produces one row for a label with no matching orders, with NULLs in the orders columns, and count(*) counts that row. Use count(o.id), which counts only non-NULL ids, so unmatched labels give 0.
Exercise
What does SELECT enumrange('delivered'::orderstatus, 'paid'::order_status); return, and why does this matter when the two arguments come from variables?
Show answer
It returns the empty array {}, because 'delivered' sorts after 'paid' in declaration order. No error is raised, so a swapped argument order can silently produce an empty result and a filter that matches nothing.