I want to set a check constraint on the following postgres table:
CREATE TABLE foo
(
id int Primary Key,
names varchar(40)[]
);
Since names is an array, I have trouble defining a check on each element of the array. The following constraint is my best guess (not working) :
ALTER TABLE foo
ADD CONSTRAINT check_names
CHECK (ALL(names[]) ~* '^[A-Z]')
;
Basically each element of names[] should be made of only capital letters.
Its doable even without a separate Trigger Function:
CREATE TABLE foo(
id int Primary Key,
names varchar(40)[]
);
ALTER TABLE foo
ADD CONSTRAINT check_names
CHECK (length(regexp_replace(array_to_string(names, ''),'[A-Z]*',''))=0);
INSERT INTO foo (id, names) VALUES (4, array ['','3']);
ERROR: new row for relation "foo" violates check constraint "check_names"
DETAIL: Failing row contains (4, {"",3}).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With