In this lesson, you will learn how to shift business logic from your application code directly into your schema by mapping domain types to specific constraints.
The Concept
While standard data types like INTEGER or TEXT define the physical structure of your data, Domains allow you to create specialized types that inherit these base characteristics while bundling custom validation rules. By attaching CHECK constraints to a domain, you ensure that the database rejects invalid data at the type level, regardless of which application or service performs the insert.
Consider a system managing international shipping. Instead of repeating a CHECK constraint across five different tables, you can define a domain that encapsulates the business logic for a standardized weight:
CREATE DOMAIN shipping_weight AS NUMERIC(10, 2)
CHECK (VALUE > 0 AND VALUE <= 5000);
Why Use Domains for Constraints?
When you define a domain with a CHECK constraint, PostgreSQL automatically applies that validation whenever you cast a value or insert data into a column defined with that type. This provides three major benefits:
- Centralized Business Logic: If the maximum weight limit changes from 5000 to 7500, you update the domain definition in one place rather than hunting through dozens of
ALTER TABLEstatements. - Schema Self-Documentation: A column named
total_weight shipping_weightis more descriptive to a developer thantotal_weight NUMERIC(10, 2). It explicitly signals that this data is subject to specific business rules. - Consistency: By reusing the domain across multiple tables, you guarantee that every module in your system treats the data with the same strict validation, preventing "drift" where one table might accidentally allow negative values while another doesn't.
Practical Implementation
Beyond simple bounds, you can use more complex logic, such as ensuring a text domain follows a specific format using regular expressions:
CREATE DOMAIN email_address AS TEXT
CHECK (VALUE ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');
By mapping your business rules to domain types, you transform your schema from a passive storage container into a robust, active enforcer of domain integrity.
Key Takeaway: Domains allow you to encapsulate reusable business constraints into custom types, ensuring data integrity is enforced consistently across your entire schema without redundant code.