In PostgreSQL, I want a check constraint if column "Art" (this never is NULL) is == 'Typ 3' and three other columns either all NULL or all NOT NULL. My code fails for the first record having 'Type 2', NULL, NULL, NULL, NULL.
ALTER TABLE "SandBox"."T Test"
ADD CONSTRAINT "T Test_Serie_check" CHECK (
"Art" = 'Type 3'
AND (
("ID-Serie_fkey" IS NULL
AND "Type" IS NULL
AND "Nr" IS NULL
AND "NrTotal" IS NULL)
OR
("ID-Serie_fkey" IS NOT NULL
AND "Type" IS NOT NULL
AND "Nr" IS NOT NULL
AND "NrTotal" IS NOT NULL)
)
);
How to solve this?
'Type 3'forArt. If you want to be able to insert'Type 2', then that is not the constraint you want. What do you actually want?Art='Type 3'; if so, the other three columns need to be either all NULL or all NOT NULL. IfArt='Type 1'orArt='Type 2'there should be no check.IF(an implication), not anANDALTER TABLE "SandBox"."T Test" ADD CONSTRAINT "T Test_Serie_check" CHECK ( IF "Art" = 'Type 3' THEN ( ("ID-Serie_fkey" IS NULL AND "Type" IS NULL AND "Nr" IS NULL AND "NrTotal" IS NULL) OR ("ID-Serie_fkey" IS NOT NULL AND "Type" IS NOT NULL AND "Nr" IS NOT NULL AND "NrTotal" IS NOT NULL) ) );NO: SyntaxError at »IF«