Sub topic 1
Creating and using enum types
Prerequisites
This chapter assumes you know basic SQL: CREATE TABLE, INSERT, SELECT, and WHERE. You should also know common PostgreSQL types such as text and integer, and what a CHECK constraint does.
Creating an enum type
An enum type is a named, fixed set of text labels. A column of that type accepts only those labels. You create one with CREATE TYPE ... AS ENUM, then use it like any other column type.
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'), ('shipped');The DEFAULT 'pending' clause fills the column when an insert omits it. An insert with any label outside the list fails.
How enum values are ordered and compared
Enum values sort by the order in which their labels were declared, not alphabetically. In order_status, pending sorts before paid because it was declared first.
SELECT id, status FROM orders ORDER BY status;
SELECT id FROM orders WHERE status >= 'paid' AND status < 'delivered';Listing enum values with enum_range, enum_first, and enum_last
The functions enum_range, enum_first, and enum_last read the labels of a type. Pass NULL::type to read the whole type, or pass two values to read a range.
SELECT enum_range(NULL::order_status);
SELECT enum_range('paid'::order_status, 'delivered'::order_status);
SELECT enum_first(NULL::order_status), enum_last(NULL::order_status);Adding and renaming enum values
ALTER TYPE changes a type after it exists. ADD VALUE inserts a new label at a chosen position. RENAME VALUE changes a label, and stored rows update to the new name without being rewritten.
ALTER TYPE order_status ADD VALUE IF NOT EXISTS 'refunded' AFTER 'delivered';
ALTER TYPE order_status RENAME VALUE 'cancelled' TO 'canceled';Exercise
Exercise
Which statement returns the labels from 'paid' through 'delivered' in declared order?
Show answer
SELECT enumrange('paid'::orderstatus, 'delivered'::order_status); This returns the array {paid,shipped,delivered}.