0

How would you write a query to select the rooms which are booked between 2012-05-1 and 2012-11-01 from a booking database?

1
  • 1
    What are your ideas? Show me your attempt, please. Commented Apr 28, 2012 at 7:39

3 Answers 3

3
select r.* from rooms r 
left outer join bookings b on b.roomno = r.roomno
where b.dateto not between '2012-05-01' and '2012-11-01'
and b.datefrom not between '2012-05-01' and '2012-11-01'
or b.roomno is null

SQLFiddle Example

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

3 Comments

And what happens if the booking period is in the middle of the start of the end date ? You don't get who have a room booked in the middle of start or end date ...
@juergend May not work with rooms that have no bookings so far.
@AmitBhargava: Thanks for the hint. I forgot to put the left outer join in it. It has been in the SQLFiddle example though.
2

This should include all rooms that aren't booked between the two given dates :

SELECT * FROM Room r
JOIN Booking b ON b.hotelNo = r.hotelNo AND r.roomNo = b.roomNo
WHERE NOT ('2012-05-01' BETWEEN (b.dateFrom AND b.dateTo)
OR '2012-11-01' BETWEEN (b.dateFrom AND b.dateTo))

Comments

1

Please try the following

SELECT * from room
WHERE (roomNo, hotelNo) not in
( select roomNo, hotelNo
  from booking
  where datefrom between '2012-05-01' and '2012-11-01'
  or dateto between '2012-05-01' and '2012-11-01'
)

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.