Databases · Senior · Question 64 of 75

How can PostgreSQL prevent two overlapping bookings of the same room at the database level?

ALTER TABLE bookings ADD CONSTRAINT no_overlap
  EXCLUDE USING gist (room_id WITH =, during WITH &&);

Explanation

It's race-free, unlike checking for overlaps before insert. It needs the btree_gist extension for the equality part on room_id.

Further reading

Problem with a question

Databases · Senior · question 64

Test yourself

Take the Databases · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz