sssebaaa
sssebaaa

Reputation: 75

PostgreSQL check one of two fields

I have table well with name, code, and code2 fields. How to write check to allow only rows with name and one of code present present?

WellA, null, Code2 -  OK
WellB, Code1, null - OK
WellC, Code3, Code4 - OK
WellD, null, null - NOT OK

Regards

Upvotes: 2

Views: 783

Answers (2)

Lukasz Szozda
Lukasz Szozda

Reputation: 175716

You could add CHECK constraint:

ALTER TABLE tab
ADD CONSTRAINT my_check CHECK (COALESCE(Code1,Code2) IS NOT NULL);

DBFiddle Demo

Upvotes: 3

Laurenz Albe
Laurenz Albe

Reputation: 246523

Add a check constraint:

CHECK (name IS NOT NULL AND
      (code IS NOT NULL OR code2 IS NOT NULL))

Upvotes: 0

Related Questions