Sub topic 2
Enum storage size and label limits
This chapter assumes you can run CREATE TABLE, INSERT, and SELECT, you have created an enum with CREATE TYPE, and you understand CHECK and NOT NULL constraints.
Enum storage size and label limits
PostgreSQL does not store enum labels inside each row. It stores a 4-byte internal identifier (an OID) for each value and looks up the label when you read the row. Each enum column therefore costs 4 bytes per row, which is usually less than a text label such as 'shipped'.
Labels are names, so PostgreSQL applies its 63-byte name limit to them. Keep labels short and plain.
Removing a value by replacing the type
PostgreSQL cannot drop one enum value with ALTER TYPE. Instead, create a new type without the value, convert the column, and swap the names:
CREATE TYPE order_status AS ENUM ('pending', 'paid', 'cancelled');
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status order_status NOT NULL DEFAULT 'pending'
);
CREATE TYPE order_status_new AS ENUM ('pending', 'paid');
ALTER TABLE orders ALTER COLUMN status DROP DEFAULT;
ALTER TABLE orders
ALTER COLUMN status TYPE order_status_new
USING status::text::order_status_new;
ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'pending';
DROP TYPE order_status;
ALTER TYPE order_status_new RENAME TO order_status;If any row still holds 'cancelled', the USING conversion fails. Fix those rows first.
Creating and using domains
A domain is a named base type with its own rules. A domain can carry a DEFAULT, a NOT NULL, and named CHECK constraints. Every column that uses the domain inherits those rules:
CREATE DOMAIN email_address AS text
CONSTRAINT email_address_format
CHECK (VALUE ~* '^[^@[:space:]]+@[^@[:space:]]+$');
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email email_address NOT NULL
);
INSERT INTO customers (email) VALUES ('[email protected]');
INSERT INTO customers (email) VALUES ('not-an-email'); -- fails the CHECKExercise
A column uses the domain short_code, which is defined as text with CHECK (length(VALUE) = 4). Does the statement INSERT INTO t (code) VALUES (NULL) succeed?
Show answer
Yes. The CHECK evaluates to NULL, which PostgreSQL treats as passing. Add NOT NULL to the domain to reject it.