patternsqlMinor
Postgres custom type with constraints
Viewed 0 times
constraintspostgreswithtypecustom
Problem
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:
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!
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!
Solution
You can create a domain based on your type.
Note the parentheses around the keyword
Then use the 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 typeCode Snippets
create domain checked_dimensions
as dimensions
constraint check_size check ( (value).w <= 10 );Context
StackExchange Database Administrators Q#301009, answer score: 5
Revisions (0)
No revisions yet.