User-defined types
Overview
PostgreSQL CREATE TYPE supports enum, composite, range and custom base types. An enum is an ordered vocabulary with type identity. Use it for genuinely stable categories; a relational lookup table may be preferable for frequently edited values, translated labels or metadata. SQLite uses a lookup table with a foreign key and explicit rank in this lesson, not a native enum.
First example
SELECT t.id,t.status FROM ct_task t JOIN ct_status s ON t.status=s.code ORDER BY s.rank,t.id;Observed SQLite result (rows in JSON):
[ [ 2, "queued" ], [ 3, "active" ], [ 1, "done" ]]How it works
PostgreSQL enum order follows its declaration, not alphabetic label order. Distinct enum types cannot be directly compared even if they share labels. Adding values is possible, while removing or reordering existing values generally requires recreating the type and planning dependencies. A lookup table makes rank explicit and can be joined for labels. Neither representation enforces a workflow transition rule by itself; use suitable application logic or database constraints. Custom base types require specialist implementation, input/output functions and privileges; do not use them just to name a column.
Practical example
SELECT s.code,COUNT(t.id) FROM ct_status s LEFT JOIN ct_task t ON t.status=s.code GROUP BY s.code,s.rank ORDER BY s.rank;Observed SQLite result (rows in JSON):
[ [ "queued", 1 ], [ "active", 1 ], [ "done", 1 ], [ "cancelled", 0 ]]Practice and mistakes
Practice: count tasks by status, including unused statuses, in business order. Hint 1: LEFT JOIN from ct_status to ct_task. Hint 2: count task IDs rather than COUNT(*). Expected counts for queued, active, done, cancelled: 1, 1, 1, 0. Verify that an unknown status fails the foreign key check. Plan migrations before changing a native enum used in multiple tables.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TYPE ct_demo_state AS ENUM ('queued','active','done','cancelled');SELECT 'queued'::ct_demo_state < 'active'::ct_demo_state, 'done'::ct_demo_state < 'cancelled'::ct_demo_state;ROLLBACK;Expected result, not executed: [[true, true]]