SQL Exercises
SQL Exercises
SQL Exercises
This material comes form the recommended book by T. Connoly, C. Begg, A. Strachan
The Database
Hotel (Hotel_No, Name, Address) Room (Room_No, Hotel_No, Type, Price) Booking (Hotel_No, Guest_No, Date_From, Date_To, Room_No) Guest (Guest_No, Name, Address)
CREATE TABLE hotel ( hotel_no CHAR(4) NOT NULL, name VARCHAR(20) NOT NULL, address VARCHAR(50) NOT NULL);
CREATE TABLE room ( room_no VARCHAR(4) NOT NULL, hotel_no CHAR(4) NOT NULL, type CHAR(1) NOT NULL, price DECIMAL(5,2) NOT NULL);
CREATE TABLE booking (hotel_no CHAR(4) NOT NULL, guest_no CHAR(4) NOT NULL, date_from DATETIME NOT NULL, date_to DATETIME NULL, room_no CHAR(4) NOT NULL); Dates: YYYY-MM-DD
CREATE TABLE guest ( guest_no CHAR(4) NOT NULL, name VARCHAR(20) NOT NULL, address VARCHAR(50) NOT NULL);
Create a separate table with the same structure as the Booking table to hold archive records. Using the INSERT statement, copy the records from the Booking table to the archive table relating to bookings before 1st January 2000. Delete all bookings before 1st January 2000 from the Booking table.
CREATE TABLE booking_old ( hotel_no CHAR(4) NOT NULL, guest_no CHAR(4) NOT NULL, date_from DATETIME NOT NULL, date_to DATETIME NULL, room_no VARCHAR(4) NOT NULL);
INSERT INTO booking_old (SELECT * FROM booking WHERE date_to < DATE2000-01-01'); DELETE FROM booking WHERE date_to < DATE2000-01-01';
Simple Queries
1. List full details of all hotels. 2. List full details of all hotels in London. 3. List the names and addresses of all guests in London, alphabetically ordered by name. 4. List all double or family rooms with a price below 40.00 per night, in ascending order of price. 5. List the bookings for which no date_to has been specified.
Aggregate Functions
1. How many hotels are there? 2. What is the average price of a room? 3. What is the total revenue per night from all double rooms? 4. How many different guests have made bookings for August?
Grouping
1. List the number of rooms in each hotel. 2. List the number of rooms in each hotel in London. 3. What is the average number of bookings for each hotel in August? 4. What is the most commonly booked room type for each hotel in London? 5. What is the lost income from unoccupied rooms at each hotel today?