AI Hints
Home›PostgreSQL Tutorial›Enums, UUIDs and Ranges
PostgreSQL · Lesson 46 of 120

Enums and Domains

Custom types.

⏱ 2 min read▶ Video at 39:58🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

An order's status should only be pending, shipped, delivered or returned. Not delivred, with a typo. Postgres lets you create your own types for rules like this.

  • Only 4 statuses
  • No typos
  • Custom types

An enum and a domain

Create type as enum lists the allowed values, in order. Create domain makes a reusable type with a check, here a positive price. Then we use both, and try a typo. Run it. The typo is rejected.

query.sqlsql
CREATE TYPE ship_status AS ENUM ('pending', 'shipped', 'delivered');
CREATE DOMAIN price AS numeric(8,2) CHECK (VALUE > 0);

CREATE TABLE shipments (id int, status ship_status, cost price);
INSERT INTO shipments VALUES (1, 'shipped', 4.99);
INSERT INTO shipments VALUES (2, 'delivred', 4.99);
Output
CREATE TYPE
CREATE DOMAIN
CREATE TABLE
INSERT 0 1
ERROR:  invalid input value for enum ship_status: "delivred"
LINE 1: INSERT INTO shipments VALUES (2, 'delivred', 4.99);
                                         ^
Also uses _empty
1

Enum or lookup table?

Enums are compact and sort in their listed order. Adding a value is easy, but removing one is hard. If the list changes often, or needs extra columns, use a lookup table with a foreign key instead.

keyvalue
ENUMfixed small lists
Sortinglisted order
Removinghard
Changes often?lookup table

Summary

Enums limit a column to a list, and domains reuse a type with a rule. Next, UUIDs.

Key takeaways
  • ENUM
  • DOMAIN
  • Typos rejected
Next up: UUIDs — IDs safe to share