Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query available rooms for booking

I have been attempting to create a query for checking available rooms between two dates but have been thus far unsuccessful. Please find the sql code for creating the tables below. I really really need your help. this is done because the system wants me to add more details

CREATE TABLE rooms (
    id   NUMERIC(3) NOT NULL,
    type VARCHAR2(11) NOT NULL,
    CONSTRAINT pk_rooms PRIMARY KEY (id),
    CONSTRAINT fk_type
    );

INSERT INTO rooms VALUES (101, 'Excellent');
INSERT INTO rooms VALUES (102, 'Excellent');
INSERT INTO rooms VALUES (103, 'Excellent');
INSERT INTO rooms VALUES (104, 'Excellent');
INSERT INTO rooms VALUES (105, 'Excellent');
INSERT INTO rooms VALUES (106, 'Excellent');
INSERT INTO rooms VALUES (107, 'Excellent');
INSERT INTO rooms VALUES (108, 'Excellent');
INSERT INTO rooms VALUES (109, 'Excellent');
INSERT INTO rooms VALUES (110, 'Excellent');
INSERT INTO rooms VALUES (111, 'Excellent');
INSERT INTO rooms VALUES (112, 'Excellent');

CREATE TABLE bookings_roombookings (
book_id  VARCHAR(20) NOT NULL, 
room_id  NUMBER NOT NULL,  
fromdate DATE NOT NULL, 
todate   DATE NOT NULL, 
guest1   VARCHAR(40) NOT NULL, 
guest2   VARCHAR(40), 
guest3   VARCHAR(40), 
CONSTRAINT cpk PRIMARY KEY (book_id, room_id),  
CONSTRAINT fk_rid FOREIGN KEY (room_id) REFERENCES rooms(id));

INSERT INTO bookings_roombookings VALUES ( 
'DTR5000000', 320, 
'01-JUN-2020', '01-SEP-2020', 
'D.Trump', 'H.Clinton', 'S.Daniels');

INSERT INTO bookings_roombookings VALUES ( 
'DRI0000002', 102, 
'11-DEC-19', '01-SEP-20', 
'D.Ridley', NULL, NULL);

my query is as follows:

select r.id from rooms r
where  r.id not in
       ( select bkr.room_id from bookings_roombookings bkr
         where  (fromdate > '15-JUN-20') and (todate < '18-JUN-20') );

but this will return both rows of the bkr table. I would appreciate any help.

like image 812
J.Doe Avatar asked Feb 12 '26 17:02

J.Doe


1 Answers

You can start from the room table, and use a not exists condition with a correlated subquery to eliminate rooms that have a reservation period which overlaps the target date range:

select r.* 
from rooms r 
where not exists (
    select 1
    from bookings_roombookings bkr
    where 
        bkr.room_id = r.id
        and bkr.fromdate <= date'2020-06-15'
        and bkr.todate >= date'2020-06-18'
)

Note: do not rely on implicit conversions from strings to date (as in fromdate > '15-JUN-20'), that depends on the nls settings of your database and session; instead, you can use date litterals, that are part of the ANSI SQL standard and which Oracle supports, like date'yyyy-mm-dd'.

like image 109
GMB Avatar answered Feb 14 '26 05:02

GMB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!