patternsqlMinor
CHECK constraint for array column to verify length > 0
Viewed 0 times
columnarraylengthverifyforconstraintcheck
Problem
I'm playing with postgres table validation rules and trying to set a
Here is how I want to implement it:
But looks like it doesn't work. O_o
How to implement such a constraint?
CHECK constraint for an array column. An idea is to allow only arrays with length > 0.Here is how I want to implement it:
create table words_table (
id serial primary key,
words varchar(20)[] CHECK (array_length(words, 1) > 0)
);But looks like it doesn't work. O_o
insert into words_table (words) values ('{}');
//INSERT 0 1How to implement such a constraint?
Solution
The crucial point you may not be aware of, quoting the manual:
It should be noted that a check constraint is satisfied if the check
expression evaluates to true or the null value.
Bold emphasis mine.
Just rule out empty arrays:
This still allows
Or catch
It should be noted that a check constraint is satisfied if the check
expression evaluates to true or the null value.
Bold emphasis mine.
Just rule out empty arrays:
CHECK (words <> '{}')This still allows
words to be null. You may want to add a NOT NULL constraint.Or catch
nullin the CHECK constraint, tooCHECK ((words <> '{}') IS TRUE)Code Snippets
CHECK (words <> '{}')CHECK ((words <> '{}') IS TRUE)Context
StackExchange Database Administrators Q#183891, answer score: 9
Revisions (0)
No revisions yet.