← Back to PostgreSQL, page 3

postgresql-0045 · Medium mid

Create a DOMAIN to reuse a validated type such as an Indian PIN code or a positive amount.

CREATE DOMAIN name AS base_type CHECK (...) defines a reusable type with constraints, so every column of that type gets the same validation. Changing the rule in one place applies everywhere, and errors name the domain. Domains suit formats used across many tables, such as PIN codes, email addresses or non-negative money.

Full answer

Sample schema and data:

sql
CREATE DOMAIN pincode AS text CHECK (VALUE ~ '^[1-9][0-9]{5}$');
CREATE DOMAIN money_inr AS numeric(12,2) CHECK (VALUE >= 0);
CREATE TABLE shops (name text, pin pincode NOT NULL, deposit money_inr DEFAULT 0);
CREATE TABLE warehouses (code text, pin pincode);
INSERT INTO shops (name, pin) VALUES ('Koramangala', '560034');
sql
INSERT INTO warehouses VALUES ('W1', '056003');

Output:

text
ERROR:  value for domain pincode violates check constraint "pincode_check"
sql
INSERT INTO shops VALUES ('Indiranagar', '560038', -100);

PostgreSQL returns:

text
ERROR:  value for domain money_inr violates check constraint "money_inr_check"
sql
SELECT name, pin, deposit, pg_typeof(pin)::text AS pin_type FROM shops;

Result on PostgreSQL 17:

text
     name    |  pin   | deposit | pin_type
-------------+--------+---------+----------
 Koramangala | 560034 | 0.00    | pincode
(1 row)

A PIN cannot start with 0, so the warehouse insert fails with an error naming the pincode domain, and the same rule applies in both tables without repeating it. A negative deposit violates the money_inr domain. Columns keep their domain type, as pg_typeof shows. Changing a domain's check later uses ALTER DOMAIN ... ADD CONSTRAINT, optionally NOT VALID to skip checking existing data. Domains over arrays or composite types are possible but less common.

sql
CREATE DOMAIN pincode AS text CHECK (VALUE ~ '^[1-9][0-9]{5}$');
CREATE DOMAIN money_inr AS numeric(12,2) CHECK (VALUE >= 0);
CREATE TABLE shops (name text, pin pincode NOT NULL, deposit money_inr DEFAULT 0);
CREATE TABLE warehouses (code text, pin pincode);
INSERT INTO shops (name, pin) VALUES ('Koramangala', '560034');

INSERT INTO warehouses VALUES ('W1', '056003');

INSERT INTO shops VALUES ('Indiranagar', '560038', -100);

SELECT name, pin, deposit, pg_typeof(pin)::text AS pin_type FROM shops;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Domains are reusable constrained types
  • One rule applies to every column
  • Errors name the domain
  • ALTER DOMAIN changes rules centrally
  • Good for formats used across tables

Common mistakes

  • Copying the same CHECK into many tables
  • Validating formats only in application code

Follow-ups

  • How do domains interact with ORMs?
  • Can a domain constraint reference other tables?

Tips

  • Name the domain in the error