#
Create a Domain
This tutorial explains to you how to create a domain in PostgreSQL. We use pgAdmin4 and a PostgreSQL 9.6.
A PostgreSQL Domain is essentially a data type with optional constraints (restrictions on the allowed set of values). The user who defines a domain becomes its owner. Domains are useful for abstracting common constraints on fields into a single location for maintenance. For example, several tables might contain email address columns, all requiring the same CHECK constraint to verify the address syntax. Define a domain rather than setting up each table's constraint individually.
CREATE DOMAIN Command is used to create a new domain.
EXAMPLES
Supposing you have to define a domain for checking if a day is Sunday or not:
CREATE DOMAIN dom_sunday
AS date
CONSTRAINT check_sunday CHECK (trim(to_char(VALUE, 'day')) = 'sunday');
If you want to define a column which allow 3 colors: red, yellow and blue:
CREATE DOMAIN color VARCHAR(20)
CHECK (VALUE IN ('red', 'yellow', 'blue'));
When you use a PostgreSQL Domain, you use it as an ordinary data type:
CREATE TABLE myTable (
id text,
myFreeDay dom_sunday
);
Using domains
in your table definition could be very useful.