In: Computer Science
'driver', 'car', 'accident' and 'report' are names of some tables in the insurance database system. These tables were created by executing the following SQL creation statements.
CREATE TABLE driver( driverID INT NOT NULL PRIMARY KEY, name VARCHAR(30) NOT NULL, cityAddress VARCHAR(25) );
CREATE TABLE car( plateID INT NOT NULL PRIMARY KEY, model VARCHAR(20) NOT NULL, year YEAR(4) NOT NULL );
CREATE TABLE accident( reportNumber INT NOT NULL PRIMARY KEY, date Date NOT NULL, location VARCHAR(20) NOT NULL );
CREATE TABLE report ( reportNumber INT NOT NULL, plateID INT NOT NULL, driverID INT NOT NULL, damageAmount DOUBLE );
Based on the previous SQL creation statements, you are required to write each of the following queries in SQL.
1- List the models of all cars which were not involved in any accident.
2- List the names and addresses of all drivers who were not involved in any accident.
1) List models of all cars which were not involved in any accident.
Explanation: Subquery will return all models which are involved in accident and from outer query we are retrieving all models which are not involved in any accident.
Query:
SELECT MODEL FROM CAR WHERE MODEL NOT IN (SELECT MODEL FROM CAR CR, REPORT RP, ACCIDENT AC WHERE CR.plateID = RP.plateID and RP.reportNumber = ac.reportNumber);
2) List the names and addresses of all drivers who were not involved in any accident.
Explanation: Subquery will return all the driverid's who are involved in accident and the outer select query will retrieve name, cityaddress of drivers who are not involved in accident based on NOT IN condition.
Query:
SELECT NAME, CITYADDRESS FROM DRIVER WHERE DRIVERID NOT IN (SELECT RP.DRIVERID FROM REPORT RP , ACCIDENT AC WHERE AC.reportNumber = RP.reportNumber);