Docsity

SQL exercises, based on dreamhome database, Study notes of Database Management Systems (DBMS)

Toggle sidebar
bg1
SQL exercises, based on dreamhome database
Datatbase system:
1. Login to mysql database server imc.kean.edu using xxx account
ANS:
mysql -u xxx -p -h imc.kean.edu
2. Switch to database dreamhome
ANS:
use dreamhome;
3. Show all tables in dreamhome database
ANS:
show tables;
4. Show the table structure (column name, datatype, keys, etc) of Staff table
ANS:
desc Staff;
SELECT:
5. Show all the rows and all the columns of Staff table
ANS:
SELECT * FROM Staff;
6. Produce a list of salaries for all staff, showing only the staff number, the first and last names, and
the salary details.
ANS:
SELECT staffNo, fName, IName, salary FROM Staff;
7. List full details of all hotels in London.
ANS:
SELECT * FROM Hotel WHERE city = 'London';
8. List the unique property numbers of all properties that have been viewed.
ANS:
SELECT DISTINCT propertyNo FROM Viewing;
9. Write a SQL query to list the staff who work in London. Please show their first name, last name and
branchno.
ANS:
SELECT fname,lname,b.branchno FROM Staff s, Branch b
WHERE s.branchno=b.branchno and b.city='London';
10. Produce a list of monthly salaries for all staff, showing the staff number, the first and last names,
and the salary details.
ANS:
SELECT staffNo, fName, IName, salary/12 FROM Staff;
11. List all staff with a salary greater than $10,000.
ANS:
SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary > 10000;
12. Write a SQL query to display the name for vendor lives in New York with zipcode 07811.
(refer to A_Vendors)
ANS:
SELECT name from A_Vendors where State = 'NY' and Zipcode='07811';
13. Write a SQL query to list the unique position for female staff with salary less than 10000.
ANS:
SELECT distinct position FROM Staff WHERE sex='F' and salary < 10000;
14. List the addresses of all branch offices in London or Glasgow.
ANS:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download SQL exercises, based on dreamhome database and more Study notes Database Management Systems (DBMS) in PDF only on Docsity!

SQL exercises, based on dreamhome database Datatbase system:

  1. Login to mysql database server imc.kean.edu using xxx account ANS: mysql -u xxx -p -h imc.kean.edu
  2. Switch to database dreamhome ANS: use dreamhome;
  3. Show all tables in dreamhome database ANS: show tables;
  4. Show the table structure (column name, datatype, keys, etc) of Staff table ANS: desc Staff;

SELECT:

  1. Show all the rows and all the columns of Staff table ANS: SELECT * FROM Staff;
  2. Produce a list of salaries for all staff, showing only the staff number, the first and last names, and the salary details. ANS: SELECT staffNo, fName, IName, salary FROM Staff;
  3. List full details of all hotels in London. ANS: SELECT * FROM Hotel WHERE city = 'London';
  4. List the unique property numbers of all properties that have been viewed. ANS: SELECT DISTINCT propertyNo FROM Viewing;
  5. Write a SQL query to list the staff who work in London. Please show their first name, last name and branchno. ANS: SELECT fname,lname,b.branchno FROM Staff s, Branch b WHERE s.branchno=b.branchno and b.city='London';
  6. Produce a list of monthly salaries for all staff, showing the staff number, the first and last names, and the salary details. ANS: SELECT staffNo, fName, IName, salary/12 FROM Staff;
  7. List all staff with a salary greater than $10,000. ANS: SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary > 10000;
  8. Write a SQL query to display the name for vendor lives in New York with zipcode 07811. (refer to A_Vendors) ANS: SELECT name from A_Vendors where State = 'NY' and Zipcode='07811';
  9. Write a SQL query to list the unique position for female staff with salary less than 10000. ANS: SELECT distinct position FROM Staff WHERE sex='F' and salary < 10000;
  10. List the addresses of all branch offices in London or Glasgow. ANS:

SELECT street FROM Branch WHERE city = 'London' OR city = 'Glasgow';

  1. Write a SQL query to display product names that make profit < 20. (refer to A_Products) ANS: SELECT name FROM A_Products WHERE sell_price - cost < 20;
  2. List all staff with a salary between $20,000 and $30,000. ANS: SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary BETWEEN 20000 AND 30000; ANS 2: SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary > = 20000 AND salary < = 30000;
  3. List all managers and supervisors. ANS: SELECT staffNo, fName, IName, position FROM Staff WHERE position IN ('Manager', 'Supervisor'); ANS 2: SELECT staffNo, fName, IName, position FROM Staff WHERE position = 'Manager' OR position = 'Supervisor';
  4. What is the output of the following SQL query? SELECT clientno, propertyno FROM Viewing WHERE comment!=''; ANS: +----------+------------+ | clientno | propertyno | +----------+------------+ | CR56 | PA14 | | CR62 | PA14 | | CR76 | PG4 | +----------+------------+
  5. List all double or family rooms with a price below 40.00 per night, in ascending order of price. ANS: SELECT * FROM Room WHERE price < 40 AND type IN ('double', 'family') ORDER BY price;
  6. Find all owners with the string ‘Glasgow’ in their address. ANS: SELECT ownerNo, fName, IName, address, telNo FROM PrivateOwner WHERE address LIKE '%Glasgow%';
  7. Write a SQL query to display the total number of Customers living in Union. ANS: SELECT count(name) FROM A_Customers WHERE address like '%Union%';
  8. List the details of all viewings on property PG4 where a comment has not been supplied. ANS: SELECT clientNo, viewDate FROM Viewing WHERE propertyNo = 'PG4' AND comment IS NULL;
  9. Produce a list of salaries for all staff, arranged in descending order of salary. ANS: SELECT staffNo, fName, lName, salary FROM Staff ORDER BY salary DESC;
  10. Produce an abbreviated list of properties arranged in order of property type. ANS: SELECT propertyNo, type, rooms, rent FROM PropertyForRent ORDER BY type;
  11. List the names and addresses of all guests in London, alphabetically ordered by name. ANS: SELECT guestName, guestAddress FROM Guest WHERE guestAddress LIKE '%London%' ORDER BY guestName;

AGGREGATE FUNCTIONS, GROUP BY:

ANS:

SELECT SUM(price) FROM Room WHERE type = 'double';

  1. Find the number of staff working in each branch and the sum of their salaries. ANS: SELECT branchNo, COUNT(staffNo) AS myCount, SUM(salary) AS mySum FROM Staff GROUP BY branchNo ORDER BY branchNo; ANS 2: SELECT branchNo, ( SELECT COUNT(staffNo) AS myCount FROM Staff s WHERE s.branchNo = b.branchNo ), ( SELECT SUM(salary) AS mySum FROM Staff s WHERE s.branchNo = b.branchNo )FROM Branch b ORDER BY branchNo;
  2. For each branch office with more than one member of staff, find the number of staff working in each branch and the sum of their salaries. ANS: SELECT branchNo, COUNT(staffNo) AS myCount, SUM(salary) AS mySum FROM Staff GROUP BY branchNo HAVING COUNT(staffNo) > 1 ORDER BY branchNo;
  3. List the hotel name and the number of rooms in each hotel. ANS: SELECT h.hotelname, COUNT(r.roomNo) AS count FROM Room r, Hotel h where r.hotelno=h.hotelno GROUP BY h.hotelno;
  4. What is the output of the following SQL statement? SELECT count(comment) FROM Viewing; ANS: +----------------+ | count(comment) | +----------------+ | 4 | +----------------+
  5. Show the total revenue per night for the double type room if all rooms are booked. ANS: SELECT SUM(price) FROM Room WHERE type = 'double';

SUBQUERY:

  1. Write a SQL query to find the staff name (first name, last name) who has salary higher than the average salary of branchno =’B003’; ANS: SELECT fname,lname FROM Staff where salary > (select avg(salary) from Staff WHERE branchno ='B003');
  2. Can we run the following query without any problem? SELECT city FROM Branch WHERE branchNo = (SELECT branchNo FROM Staff where sex='F'); ANS: Error, Subquery returns more than 1 row. Cannot use =, should use IN
  3. What is the output of the following SQL query? SELECT c.name FROM A_Customers c WHERE c.id NOT in (SELECT c_id FROM A_Reviews); ANS: +-------+ | name | +-------+ | BJ2 | | BJ3 | | Judy1 | | Judy2 | +-------+
  4. What is the output of the following SQL query?

SELECT count(distinct(city)) as myCt FROM Hotel WHERE hotelno in (SELECT hotelno FROM Room WHERE type='single'); ANS: +------+ | myCt | +------+ | 3 | +------+

  1. Write a SQL query to display the staffno and working branch city for the staff who has the lowest salary. ANS: SELECT s.staffno,b.city FROM Staff s, Branch b WHERE s.branchno=b.branchno and s.salary in (SELECT min(salary) FROM Staff);
  2. List the staff who work in the branch at ‘163 Main St’. ANS: SELECT staffNo, fName, IName, position FROM Staff WHERE branchNo = (SELECT branchNo FROM Branch WHERE street = '163 Main St'); ANS 2: SELECT staffNo, fName, IName, position FROM Staff s, Branch b WHERE s.branchNo = b.branchNo and street = '163 Main St';
  3. List all guests staying at the Grosvenor Hotel from April 1st to August 31st, 2004. ANS: SELECT * FROM Guest WHERE guestNo in ( SELECT guestNo FROM Booking WHERE dateFrom >= date('2004-04-01') AND dateFrom <= date('2004-08-31') AND hotelNo = (SELECT hotelNo FROM Hotel WHERE hotelName = 'Grosvenor'));
  4. List all staff whose salary is greater than the average salary, and show by how much their salary is greater than the average. ANS: SELECT staffNo, fName, LName, position, (salary - (SELECT AVG(salary) FROM Staff)) AS salDiff FROM Staff WHERE salary > (SELECT AVG(salary) FROM Staff); ANS 2: SELECT staffNo, fName, LName, position, (salary-a.avg1) AS salDiff FROM Staff s, (SELECT AVG(salary) as avg1 FROM Staff) a WHERE salary > a.avg1;
  5. List the properties that are handled by staff who work in the branch at ‘163 Main St’. ANS: SELECT propertyNo, street, city, postcode, type, rooms, rent FROM PropertyForRent WHERE staffNo IN (SELECT staffNo FROM Staff WHERE branchNo = (SELECT branchNo FROM Branch WHERE street = '163 Main St'));
  6. Find all staff whose salary is larger than the salary of at least one member of staff at branch B003. ANS: SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary > SOME (SELECT salary FROM Staff WHERE branchNo = 'B003');
  7. Find all staff whose salary is larger than the salary of every member of staff at branch B003. ANS: SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary > ALL (SELECT salary FROM Staff WHERE branchNo = 'B003');
  8. Write a SQL query to show client names who didn’t give reviews (Viewing table). ANS: SELECT c.fname,c.lname FROM Client c
  1. For each branch office, list the staff numbers and names of staff who manage properties and the properties that they manage. ANS: SELECT s.branchNo, s.staffNo, fName, IName, propertyNo FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo ORDER BY s.branchNo, s.staffNo, propertyNo;
  2. For each branch, list the staff numbers and names of staff who manage properties, including the city in which the branch is located and the properties that the staff manage. ANS: SELECT b.branchNo, b.city, s.staffNo, fName, IName, propertyNo FROM Branch b, Staff s, PropertyForRent p WHERE b.branchNo = s.branchNo AND s.staffNo = p.staffNo ORDER BY b.branchNo, s.staffNo, propertyNo;
  3. Display the product names and the comments that customer BJ1 gave. (refer to A_Cusomters, A_Reviews, A_Products) ANS: SELECT p.name, comments FROM A_Customers c, A_Reviews r, A_Products p WHERE c.id=r.c_id and p.id=r.p_id and c.name='BJ1' ;
  4. List the guestname, hotelname, number of days stayed, and the total amount needed to pay to the hotel for every guest. ANS: select guestname, hotelname, datediff(dateto,datefrom), sum(datediff(dateto,datefrom)*price) from Guest g, Hotel h, Room r, Booking b where h.hotelno=b.hotelno and r.roomno=b.roomno and g.guestno=b.guestno and dateto is not null group by guestname,hotelname;
  5. Find the number of properties handled by each staff member, along with the branch number of the member of staff. ANS: SELECT s.branchNo, s.staffNo, COUNT(*) AS myCount FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo GROUP BY s.branchNo, s.staffNo ORDER BY s.branchNo, s.staffNo;
  6. Find all staff who work in a London branch office. ANS: SELECT staffNo, fName, IName, position FROM Staff s WHERE EXISTS (SELECT * FROM Branch b WHERE s.branchNo = b.branchNo AND city = 'London'); ANS 2: SELECT staffNo, fName, IName, position FROM Staff s, Branch b WHERE s.branFchNo = b.branchNo AND city = 'London';

OUTER JOIN:

  1. List all branch offices and any properties that are in the same city. ANS: SELECT b., p. FROM Branch1 b LEFT JOIN PropertyForRent1 p ON b.bCity = p.pCity;
  2. List all properties and any branch offices that are in the same city. ANS: SELECT b., p. FROM Branch1 b RIGHT JOIN PropertyForRent1 p ON b.bCity = p.pCity;
  3. List the branch offices and properties that are in the same city along with any unmatched branches or properties. ANS:

SELECT b., p. FROM Branch1 b FULL JOIN PropertyForRent1 p ON b.bCity = p.pCity;

  1. How many rows will be generated from the following SQL statement: SELECT * FROM Staff s RIGHT JOIN Branch b ON s.branchno=b.branchno; ANS: 8 rows
  2. Write a SQL query to display all customer names (A_Customers) and their number of Reviews (A_Reviews). If a customer didn’t give review, his/her number of review will be 0. The output should have customer name in alphabetic order from A to Z. ANS: SELECT c.name, count(r.c_id) FROM A_Customers c LEFT JOIN A_Reviews r on r.c_id= c.id group by c.id order by c.name ASC;

SET (UNION, INTERSECT, EXCEPT):

  1. Construct a list of all cities where there is either a branch office or a property. ANS: (SELECT city FROM Branch WHERE city IS NOT NULL) UNION (SELECT city FROM PropertyForRent WHERE city IS NOT NULL);
  2. Construct a list of all cities where there is both a branch office and a property. ANS 1: (SELECT city FROM Branch) INTERSECT (SELECT city FROM PropertyForRent); ANS 2: SELECT DISTINCT b.city FROM Branch b,PropertyForRent p WHERE b.city=p.city;
  3. Write a SQL query to find the vendor names not providing any products. (refer to A_Vendors, A_Products tables) ANS: SELECT name FROM A_Vendors where V_Id not in (SELECT V_Id from A_Products);
  4. Construct a list of all cities where there is a branch office but no properties. ANS: (SELECT city FROM Branch) EXCEPT (SELECT city FROM PropertyForRent); ANS 2: SELECT DISTINCT city FROM Branch WHERE city NOT IN (SELECT city FROM PropertyForRent);

INSERT:

  1. Insert a new row into the Staff table supplying data for all columns. ANS: INSERT INTO Staff VALUES ('SG16', 'Alan', 'Brown', 'Assistant', 'M', DATE '1957-05-25', 8300, 'B003');
  2. Insert a new row into the Staff table supplying data for all mandatory columns: staffNo, fName, IName, position, salary, and branchNo. ANS: INSERT INTO Staff (staffNo, fName, IName, position, salary, branchNo) VALUES ('SG44', 'Anne', 'Jones', 'Assistant', 8100, 'B003'); ANS 2: INSERT INTO Staff VALUES ('SG44’, 'Anne’, 'Jones’, 'Assistant’, NULL, NULL, 8100, 'B003’);
  3. Assume that there is a table StaffPropCount that contains the names of staff and the number of properties they manage: StaffPropCount(staffNo, fName, IName, propCount) Write a SQL to populate the StaffPropCount table using details from the Staff and PropertyForRent tables. ANS: INSERT INTO StaffPropCount (SELECT s.staffNo, fName, IName, COUNT(*)
  1. Create a view vTest listing all double or family rooms with a price below 40.00 per night, in ascending order of price. ANS: CREATE VIEW vTest as SELECT * FROM Room WHERE price < 40 AND type IN ('double', 'family') ORDER BY price asc;
  2. Create a view vTest to list the number of rooms in each hotel. ANS: SELECT h.hotelname, COUNT(r.roomNo) AS count FROM Room r, Hotel h where r.hotelno=h.hotelno GROUP BY h.hotelno;
  3. Create a view vTest to list the hotel name and the total number of rooms with price per room below 40.00 per night. ANS: CREATE VIEW vTest as SELECT h.hotelname,count(*) FROM Hotel h, Room r WHERE h.hotelno=r.hotelno and r.price < 40 group by h.hotelno;
  4. Create a view so that the manager at branch B003 can see the details only for staff who work in his or her branch office. ANS: CREATE VIEW Manager3Staff AS SELECT * FROM Staff WHERE branchNo = 'B003';
  5. Create a view of the staff details at branch B003 that excludes salary information, so that only managers can access the salary details for staff who work at their branch. ANS: CREATE VIEW Staff3 AS SELECT staffNo, fName, IName, position, sex FROM Staff WHERE branchNo = 'B003';
  6. Create a view vTest to show the first name and the working city for staff who was born after January first 1960. ANS: SELECT fname, city FROM Staff s, Branch b WHERE s.branchno=b.branchno and birthday > '1960-01-01';
  7. Create a view vTest to find the total revenue per night for each hotel and the revenue is higher than 85 dollars. Assume all rooms are booked. Your output needs to show the hotel name and the amount of revenue. ANS: SELECT h.hotelno, SUM(price) as revenue FROM Hotel h, Room r WHERE h.hotelno=r.hotelno group by h.hotelno having revenue > 85;
  8. Create a view of staff who manage properties for rent, which includes the branch number they work at, their staff number, and the number of properties they manage ANS: CREATE VIEW StaffPropCnt (branchNo, staffNo, cnt) AS SELECT s.branchNo, s.staffNo, COUNT(*) FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo GROUP BY s.branchNo, s.staffNo;

GRANT, REVOKE:

  1. Give the user with authorization identifier Manager all privileges on the Staff table. ANS: GRANT ALL PRIVILEGES ON Staff TO Manager WITH GRANT OPTION;
  2. Give users Personnel and Director the privileges SELECT and UPDATE on column salary of the Staff table. ANS: GRANT SELECT, UPDATE (salary) ON Staff TO Personnel, Director;
  3. Give user xyz from IP ’10.20.30.40’ the privileges SELECT on column salary of the Staff table.

ANS:

GRANT SELECT (salary) ON test TO 'xyz'@'10.20.30.40';

  1. Remove user xyz’s SELECT privilege from test the test table. ANS: REVOKE SELECT on test from xyz;
  2. Remove user xyz’s all privileges from test the test table. ANS: REVOKE ALL PRIVILEGES on test from xyz;

DROP:

  1. Remove a table Data from the database. ANS: DROP TABLE table Data;
  2. Remove a view vData from the database. ANS: DROP VIEW vData;
  3. Remove a stored procedure pTest() from the database. ANS: DROP procedure pTest;
  4. Remove a stored function fTest() from the database. ANS: DROP function fTest;
  5. Remove a user xyz from the database. ANS: DROP USER xyz;

SQL Syntax and runtime issues:

  1. Can the following SQL be run without error? SELECT staffNo, COUNT(salary) FROM Staff; Yes, it has no syntax error, but the result is meaningless.
  2. Can the following SQL be run without error? SELECT staffNo FROM Staff where salary=max(salary); No, this query is illegal because the aggregation function max() cannot be compared directly.
  3. Is the following view updatable? CREATE VIEW vTest AS SELECT count(*) as ct FROM Staff; ANS: No, because the view is created with an aggregate function count()
  4. Is the following view updatable? CREATE VIEW vTest AS SELECT fname, lname as ct FROM Staff; ANS: Yes, because every record in vTest can be traced back to the original record in Staff.
  5. Is the following view updatable? CREATE VIEW vTest AS SELECT distinct branchno FROM Staff; ANS: No, because the view is created with the distinct keyword.
  6. Is the following view updatable? CREATE VIEW vTest AS SELECT sex FROM Staff GROUP BY sex; ANS: No, because the view is created with GROUP BY.
  7. Is the following view updatable? CREATE VIEW vTest AS SELECT branchno, sum(salary) FROM Staff GROUP BY branchno;
  1. Write a stored function named fMaxSalary(bno) which will return the staff’s highest salary for a given branch no bno. ANS: DELIMITER $$ CREATE FUNCTION fMaxSalary(bno varchar(10)) RETURNS float BEGIN DECLARE maxSalary float ; SELECT max(salary) into maxSalary FROM dreamhome.Staff WHERE branchno=bno; RETURN maxSalary ; END $$ DELIMITER ;
  2. Write a stored function named fMaxSalary(n) which will return the staff’s highest salary for a given input that is a partial string in the first name field. ANS: DELIMITER $$ CREATE FUNCTION fMaxSalary(n varchar(10)) RETURNS float BEGIN DECLARE maxSalary float ; SELECT max(salary) into maxSalary FROM dreamhome.Staff WHERE fname like concat('%',n,'%'); RETURN maxSalary ; END $$ DELIMITER ;
  3. Write the SQL statement to run a stored procedure named pGetNames ()which will display the Staff’s first name and last name who work at branch located at a given city ‘London’. ANS: call pGetNames('London');
  4. Write a stored procedure named pGetNames (bcity) which will display the Staff’s first name and last name who work at branch located at a given city bcity. ANS: DELIMITER $$ CREATE PROCEDURE pGetNames (IN bcity VARCHAR(12)) BEGIN SELECT fname,lname FROM dreamhome.Staff s, dreamhome.Branch b WHERE city= bcity and b.branchno=s.branchno; END $$ DELIMITER ;
  5. Write a stored procedure named pGetNames (bcity) which will display the Staff’s first name and last name who work at branch located at a given city bcity. If the bcity is empty ‘’, please print a message saying “The input city cannot be empty.” call pGetNames(''); +-----------------------------+ | message | +-----------------------------+ | Input city cannot be empty. | +-----------------------------+

call pGetNames('London'); +-------+-------+ | fname | lname | +-------+-------+ | John | White | | Julie | Lee | +-------+-------+ ANS: DELIMITER $$ CREATE PROCEDURE pGetNames (IN bcity VARCHAR(12)) BEGIN

if (bcity='') THEN SELECT 'Input city cannot be empty.' as message; ELSE SELECT fname,lname FROM dreamhome.Staff s, dreamhome.Branch b WHERE city= bcity and b.branchno=s.branchno; END IF; END $$ DELIMITER ;