Skip to content
Advertisement

How to check if hotel room is booked using Oracle SQL constraints

I am an absolute beginner when it comes to SQL, and I’m trying to figure out how to do a simple integrity check. I am modelling a hotel registration system with four tables: Hotel, Room, Booking and Guest. What I’m interested in is in the booking table, which has attributes hotelNo, guestNo, dateFrom, dateTo, roomNo, where the first three are a composite primary key. Now then, the issue at hand is that under the current system, two people might have the same room booked at the same time, which would obviously be a problem in real life. I imagine that a solution might start to look something like

Bear in mind that while I am a computer engineering student, I’ve never done SQL before, so a hand-holdy walk-through would be appreciated 🙂

Edit: I think my problem would be solved by a constraint to the effect of

CASE 1 (Overlap): “If the dateFrom or dateTo attributes of the record I am trying to insert falls between the dateFrom and dateTo attributes of a given record previously in the table, reject this insertion since there is some overlap between the two bookings.”

CASE 2 (Superset): “If I am attempting to insert record X and there is a record already in the table named Y such that its Y.dateFrom > X.dateFrom and Y.dateTo < X.dateTo, then X is a superset of Y and should be rejected.”

I’m not sure of how to translate that to SQL, though.

Edit 2: The tables

Advertisement

Answer

In your model, the HOTEL and GUEST tables are okay (they may need some more columns later, but that’s not a problem). For ROOM, you have decided to use a composite PK. However, a single column as ID would suffice. In BOOKING, the foreign key referencing HOTEL is redundant. Guests are booking rooms (which have a unique ID, and are tied to a HOTEL already) at certain days.

It may help (your learning) to auto-generate the IDs, and define different “start” values for them – when querying the tables at a later stage, you will recognise the IDs immediately eg HOTELs could have 1000+, rooms could have 2000+ etc (see DDL code below).

When following the link provided by @Abra, you have seen that triggers etc can be used for solving the problem. The solution below is inspired by this answer (also mentioned as “option 4” here), and uses the idea of breaking down bookings into days (“slots”), which can then be used for unique (or PK) constraints. Please read the comments, as they contain more explanations.

DDL code

Model

enter image description here

Populate HOTELS, ROOMS, GUESTS

Data in HOTELS, ROOMS, GUESTS

Testing

You can insert more dates for testing by using PL/SQL and coding a loop: see dbfiddle.

Simple query

Query with more test data (INSERTs: see dbfiddle)

As your question was more about modelling and constraints, the queries will probably need more work.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement