2

I want to add a NOT NULL contstraint to one of my table fields but only when another field has a certain value.

So I have a services table:

services:
 - id
 - professional_id
 - is_master

I want to write a SQL constraint that whenever is_master is false professional_id cannot be null. I've tried things like:

CREATE TABLE "services" (
    "id" text NOT NULL,
    "professional_id" text REFERENCES professionals ON DELETE CASCADE ON UPDATE CASCADE,
    EXCLUDE USING gist (
        professional_id WITH =,
    ) WHERE (NOT is_master),
    "is_master" boolean NOT NULL DEFAULT false,
    PRIMARY KEY ("id")
);

What is the correct way to write this SQL?

2
  • Create a trigger to achieve that postgresql.org/docs/9.1/static/sql-createtrigger.html Commented Nov 9, 2017 at 15:52
  • 1
    check (not is_master and professional_id is not null)? Commented Nov 9, 2017 at 15:54

3 Answers 3

2

You can do this with a check constraint. A simple one is:

constraint chk_services_master_professions
    check (is_master or professional_id is not null)

Note: This version assumes that is_master is never NULL -- or that NULL is equivalent to "false".

Sign up to request clarification or add additional context in comments.

2 Comments

This is def the cleanest one but I had already accepted the other answer before seeing this.
@Rodrigo: Are you aware that you can switch the chosen answer?
2
check (not is_master and professional_id is not null or is_master)

Comments

0

You could use CHECK constraint:

CREATE TABLE "services" (
    "id" text NOT NULL,
    "professional_id" text 
       CHECK (CASE WHEN "is_master" IS FALSE AND "professional_id" IS NULL 
              THEN FALSE ELSE TRUE END), -- and rest of FK
    "is_master" boolean NOT NULL DEFAULT false,
    PRIMARY KEY ("id")
);

Rextester Demo

INSERT INTO services
VALUES (1,1, FALSE);

INSERT INTO services
VALUES (2,1, true);

INSERT INTO services
VALUES (3, null, true);

INSERT INTO services
VALUES (4, null, false);

23514: new row for relation "services" violates check constraint "services_check"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.