capypad
0 day streak
sql / expert
Snippet

User-Defined Type Constraints via CREATE DOMAIN

A DOMAIN is a global schema object that allows you to define a data type with localized constraints. Unlike simple column checks, domains promote reusability and centralize validation logic across multiple tables within the same database schema.

snippet.sql
sql
1
2
3
4
5
6
7
CREATE DOMAIN valid_email AS VARCHAR(255)
CHECK (VALUE LIKE '%@%.%');
 
CREATE TABLE subscribers (
id INTEGER PRIMARY KEY,
email valid_email
);
Breakdown
1
CREATE DOMAIN valid_email AS VARCHAR(255)
Initializes a custom domain based on the VARCHAR type.
2
CHECK (VALUE LIKE '%@%.%')
Applies a constraint that every instance of this domain must contain an '@' and a dot.
3
email valid_email
Uses the custom domain as the type for a table column, enforcing the pattern check automatically.