Question

I have the following table,

-- Booking Table
CREATE TABLE Bookings (
booking_id      INTEGER GENERATED ALWAYS AS IDENTITY,
hotel           INTEGER, 
check_in        DATE NOT NULL,
check_out       DATE NOT NULL,
size            VARCHAR(20) NOT NULL,
quantity        INTEGER NOT NULL,
pin             INTEGER NOT NULL,
url             VARCHAR(30) NOT NULL,
extra_bed       INTEGER DEFAULT 0,
assigned        VARCHAR(5) NOT NULL,
assignedroom    INTEGER,


-- Constraints  
CONSTRAINT assigned_ck CHECK (assigned IN ('Yes', 'No')),

-- If we have assigned a room to the booking ("assigned" = 'Yes') then "assignedroom" CANNOT be NULL
CONSTRAINT assignedroom_ck CHECK (assigned = 'Yes' AND assignedroom NOT NULL),

-- If we have NOT assigned a room, then "assignedroom" = NULL
CONSTRAINT assignedroom_ck1 CHECK (assigned = 'No' AND assignedroom NULL),

CONSTRAINT booking_size_ck CHECK (size IN ('Single', 'Twin', 'Queen', 'Executive', 'Suite')),
CONSTRAINT extra_bed_ck CHECK (extra_bed IN (0,1)), 
CONSTRAINT pin_ck CHECK (pin > 999 AND pin <= 9999),
-- because the single rooms are numbered 1 - 15, can check that single room
-- cannot have extra bed
--CONSTRAINT single_extra_ck CHECK(room_num < 16 AND extra_bed NOT IN (1));
-- Keys
FOREIGN KEY (hotel) REFERENCES Hotels(id),
PRIMARY KEY(booking_id)

);

I'm getting an error at the CONSTRAINT assignedroom_ck part. The error is Syntax error: Encountered "NOT".

With CONSTRAINT assignedroom_ck and CONSTRAINT assignedroom_ck1, I'm trying to achieve: 1) If assigned = 'Yes', then assignedroom CANNOT be NULL. 2) If assigned = 'No' then assignedroom MUST be NULL

Could someone please help me with the correct syntax?

Thank you.

Was it helpful?

Solution

You are missing IS:

CONSTRAINT assignedroom_ck CHECK (assigned = 'Yes' AND assignedroom IS NOT NULL),
CONSTRAINT assignedroom_ck1 CHECK (assigned = 'No' AND assignedroom IS NULL),

EDIT: As obviously both constraints can never be met, so you cannot insert anything, you need to combine the constraints:

CONSTRAINT assignedroom_ck CHECK
(
  (assigned = 'Yes' AND assignedroom IS NOT NULL) 
  OR
  (assigned = 'No' AND assignedroom IS NULL)
),

OTHER TIPS

You need to combine both of your checks for assigned room because you don't want any check constraint to return false:

CONSTRAINT assignedroom_ck CHECK (
    (assigned = 'Yes' AND assignedroom IS NOT NULL) or
    (assigned = 'No' and assignedroom IS NULL)
)

With it as two separate constraints, one of them will always be FALSE and so no row can ever be inserted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top