Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unique constraint for certain value

I have a table in a PostgreSQL DB like this to represent a booking system for office desks. Employees can book one desk (seat_id) per day.

ID Booked_Date Seat_ID Employee_ID Status
1 2022-07-08 10C id1 booked
2 2022-07-08 20C id2 cancelled

How to make a unique constraint with multiple column (booked_date, seat_id, and status with value ‘booked’) to guarantee that no more than one employee can book the same seat for the same day?

Note: employees can cancel the seat that they have booked and the row stays in the table with changed status.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a partial UNIQUE index:

CREATE UNIQUE INDEX ON booking_tbl (booked_date, seat_id)
WHERE status = 'booked';

Related:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading