Composite and domain types
Overview
A composite type groups named, typed fields into a record value. A domain adds reusable restrictions to a base type. They solve different problems: structure versus allowed values. SQLite models this example with separate columns, STRICT tables, NOT NULL and CHECK constraints; these do not create reusable native domain types.
First example
SELECT id,json_object('width',width,'height',height) FROM ct_package ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, "{\"width\":3,\"height\":4}" ], [ 2, "{\"width\":2,\"height\":5}" ]]How it works
In PostgreSQL CREATE TYPE ... AS defines a composite; ROW(...)::type constructs a value and (value).field accesses a field. Table constraints do not automatically apply to a composite value outside that table. CREATE DOMAIN ... CHECK (VALUE >= 0) constrains a base integer; CHECK can accept unknown, so require NOT NULL at the destination column when necessary. In SQLite STRICT permits lossless coercion; it is not a no-conversion rule.
Practical example
SELECT id,width*height AS area FROM ct_package ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 12 ], [ 2, 10 ]]Practice and mistakes
Practice: calculate the rectangular area of each package from its width and height; return IDs and areas in ID order. Hint 1: multiply the two fields. Hint 2: keep the dimensions as separate columns so their checks remain explicit. Expected areas: 12 and 10. Avoid assuming composite records automatically inherit all table constraints.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE DOMAIN ct_demo_positive AS integer CHECK (VALUE > 0);CREATE TYPE ct_demo_dimensions AS (width ct_demo_positive,height ct_demo_positive);SELECT (ROW(3,4)::ct_demo_dimensions).width * (ROW(3,4)::ct_demo_dimensions).height;ROLLBACK;Expected result, not executed: [[12]]