Postgres custom type with constraints

datatypespostgresqlpostgresql-12

I was wondering if it were possible (and/or desirable) to create custom types with constraints on the values. Say I have a custom type for height/width/length:

CREATE TYPE dimensions AS (w float, h float, l float);

I'd like to ensure that none of my widths are greater than 10 (for example).

Is such a thing possible, or would I be better served creating check constraints on every table that uses this type? I'd like to be able to add/edit the constraint in a single place (ie, on the type itself).

Thanks!

Best Answer

You can create a domain based on your type.

create domain checked_dimensions 
   as dimensions
   constraint check_size check ( (value).w <= 10 );

Note the parentheses around the keyword value. They look redundant but are required in this case.

Then use the type checked_dimensions as your column type