In this lesson, you will learn how to go beyond standard data types by creating custom, reusable structures and enforcing business rules at the schema level using composite types and domains.
Composite Types: Structuring Your Data
A composite type allows you to group multiple data types under a single name, effectively creating a "row-type" that can be used as a column definition, a function parameter, or a return type. Think of it as a custom object structure within your database.
For example, if you frequently store mailing addresses, instead of creating separate columns for street, city, and zip in every table, you can define a reusable type:
CREATE TYPE address AS (
street TEXT,
city TEXT,
zip INTEGER
);
-- Now use it as a standard data type
CREATE TABLE users (
id SERIAL PRIMARY KEY,
home_address address
);
You can access the individual fields of an address using dot notation, such as home_address.city.
Custom Domains: Constraining Your Types
While composite types group fields, domains are user-defined types that extend an existing base type with specific constraints. A domain acts as a wrapper that ensures data integrity before it ever hits your table constraints.
If you have a requirement that a postal_code must always be a positive integer and satisfy a specific range, a domain is the perfect tool:
CREATE DOMAIN us_zip AS INTEGER
CHECK (VALUE > 10000 AND VALUE < 99999);
-- Usage:
CREATE TABLE shipping_info (
destination us_zip
);
If a user tries to insert a value outside that range, PostgreSQL will reject the entry immediately, providing a cleaner way to centralize your business logic than repeating CHECK constraints across multiple tables.
Why use these?
By combining these tools, you transform your schema from a collection of raw scalars into a semantic model that reflects your domain logic. Composite types improve code reusability and clarity, while domains act as a "first line of defense" for data quality.
Key Takeaway: Use composite types to bundle related attributes into structured units, and use custom domains to bake business-rule validation directly into the data type itself.