CS - Database (Chapter12-16-Assignments and Type ABC Solutions)
CS - Database (Chapter12-16-Assignments and Type ABC Solutions)
Chapter 13
Simple Queries in SQL - Assignments
Question 1
Write a query to display EName and Sal of employees whose salary is greater than or equal to 2200
from table Empl.
Answer
SELECT ENAME, SAL
FROM empl
WHERE SAL >= 2200;
Output
+-----------+------+
| ENAME | SAL |
+-----------+------+
| MAHADEVAN | 2985 |
| BINA | 2850 |
| AMIR | 5000 |
| SHIAVNSH | 2450 |
| SCOTT | 3000 |
| FAKIR | 3000 |
+-----------+------+
Question 2
Write a query to display details of employees who are not getting commission from table Empl.
Answer
SELECT *
FROM empl
WHERE COMM IS NULL OR COMM = 0;
Output
+-------+-----------+-----------+------+------------+------+------+--------+
| EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO |
+-------+-----------+-----------+------+------------+------+------+--------+
| 8369 | SMITH | CLERK | 8902 | 1990-12-18 | 800 | NULL | 20 |
| 8566 | MAHADEVAN | MANAGER | 8839 | 1991-04-02 | 2985 | NULL | 20 |
| 8698 | BINA | MANAGER | 8839 | 1991-05-01 | 2850 | NULL | 30 |
| 8839 | AMIR | PRESIDENT | NULL | 1991-11-18 | 5000 | NULL | 10 |
| 8844 | KULDEEP | SALESMAN | 8698 | 1991-09-08 | 1500 | 0 | 30 |
| 8882 | SHIAVNSH | MANAGER | 8839 | 1991-06-09 | 2450 | NULL | 10 |
| 8886 | ANOOP | CLERK | 8888 | 1993-01-12 | 1100 | NULL | 20 |
| 8888 | SCOTT | ANALYST | 8566 | 1992-12-09 | 3000 | NULL | 20 |
| 8900 | JATIN | CLERK | 8698 | 1991-12-03 | 950 | NULL | 30 |
| 8902 | FAKIR | ANALYST | 8566 | 1991-12-03 | 3000 | NULL | 20 |
| 8934 | MITA | CLERK | 8882 | 1992-01-23 | 1300 | NULL | 10 |
+-------+-----------+-----------+------+------------+------+------+--------+
Question 3
Write a query to display employee name and salary of those employee who don't have their salary in
the range of 2500 to 4000.
Answer
SELECT ENAME, SAL
FROM empl
WHERE SAL NOT BETWEEN 2500 AND 4000;
Output
+----------+------+
| ENAME | SAL |
+----------+------+
| SMITH | 800 |
| ANYA | 1600 |
| SETH | 1250 |
| MOMIN | 1250 |
| AMIR | 5000 |
| KULDEEP | 1500 |
| SHIAVNSH | 2450 |
| ANOOP | 1100 |
| JATIN | 950 |
| MITA | 1300 |
+----------+------+
Question 4
Write a query to display the name, job title and salary of employee who do not have manager.
Answer
SELECT ENAME, JOB, SAL
FROM empl
WHERE MGR IS NULL ;
Output
+-------+-----------+------+
| ENAME | JOB | SAL |
+-------+-----------+------+
| AMIR | PRESIDENT | 5000 |
+-------+-----------+------+
Question 5
Write a query to display the name of employee whose name contains 'A' as third alphabet.
Answer
SELECT ENAME
FROM empl
WHERE ENAME LIKE '__A%' ;
Explanation
There are no employees whose name contains 'A' as the third alphabet in the empl table. Therefore,
the output will be empty.
Question 6
Write a query to display the name of employee whose name contains 'T' as the last alphabet.
Answer
SELECT ENAME
FROM empl
WHERE ENAME LIKE '%T' ;
Output
+-------+
| ENAME |
+-------+
| SCOTT |
+-------+
Question 7
Write a query to display the name of employee whose name contains 'M' as first alphabet 'L' as third
alphabet.
Answer
SELECT ENAME
FROM empl
WHERE ENAME LIKE 'M_L%' ;
Explanation
There are no employees whose name contains 'M' as first alphabet and 'L' as third alphabet in the
empl table. Therefore, the output will be empty.
Question 8
Write a query on the customers table whose output will exclude all customers with a rating <= 100,
unless they are located in Shimla.
Answer
SELECT *
FROM customers
WHERE rating > 100 OR city = 'Shimla' ;
Question 9
Write a query that selects all orders (Order table) except those with zeros or NULLs in the amt field.
Answer
SELECT *
FROM order
WHERE amt IS NOT NULL AND amt <> 0 ;
Question 10
Write SQL commands for the following on the basis of given table STUDENT :
Table : STUDENT
StudentNo. Class Name GAME Grade1 SUPW Grade2
Chapter 14
Table Creation and Data Manipulation Commands
Type A: Short Answer Questions/Conceptual Questions
Question 1
What are different divisions of SQL and commands ? Give examples of commands in each division.
Answer
SQL commands can be divided into following categories :
1. Data Definition Language (DDL) commands — CREATE, ALTER, DROP, TRUNCATE etc.
2. Data Manipulation Language (DML) commands — INSERT, UPDATE, DELETE etc.
3. Transaction Control Language (TCL) commands — COMMIT, ROLLBACK, SAVEPOINT etc.
4. Session Control Commands
5. System Control Commands
Question 2
What is foreign key ? How do you define a foreign key in your table ?
Answer
A non-key attribute, whose values are derived from the primary key of some other table, is known as
foreign key in its current table. Defining a foreign key in a table involves specifying the relationship
between the tables and setting up rules for data integrity. When two tables are related by a common
column or set of columns, the related column(s) in the parent table (or primary table) should be
either declared as a primary key or unique key. Meanwhile, the related column(s) in the child table (or
related table) should have a foreign key constraint referencing the primary or unique key in the parent
table.
Question 3
How is FOREIGN KEY commands different from PRIMARY KEY command ?
Answer
The PRIMARY KEY is a set of one or more attributes that can uniquely identify tuples within the
relation. A primary key column cannot contain NULL values, and it must have unique values for each
row. Only one primary key constraint can exist per table. Conversely, the FOREIGN KEY command
establishes a relationship between two tables by linking a column or set of columns in one table to
the primary key or a unique key in another table. It enforces referential integrity, ensuring that values
in the foreign key column(s) of the referencing table match values in the referenced table's primary
key or unique key column(s). A foreign key can allow NULL values, indicating that the relationship is
optional. Multiple foreign key constraints can exist in a table, each referencing a different parent
table.
Question 4
How is FOREIGN KEY commands related to the PRIMARY KEY ?
Answer
FOREIGN KEY commands establish relationships between tables by linking columns in one table to the
PRIMARY KEY or a unique key in another table. This linkage ensures referential integrity, meaning that
values in the FOREIGN KEY column(s) of the referencing table must match values in the PRIMARY KEY
or unique key column(s) of the referenced table. Therefore, FOREIGN KEY commands are directly
related to PRIMARY KEY commands as they rely on the unique identification provided by PRIMARY
KEY constraints in other tables.
Question 5
How do you enforce business rules on a database ?
Answer
Database constraints enforce business rules on a database. These include PRIMARY KEY for unique
identifiers, FOREIGN KEY for maintaining relationships between tables, UNIQUE for ensuring
uniqueness, CHECK constraint limit values that can be inserted into a column of a table, and default
constraints are utilized to specify a default value for a column when no value is explicitly provided
during an insert operation.
Question 6
What are table constraints ? What are column constraints ? How are these two different ?
Answer
Table constraints are rules or conditions applied to an entire table in a database. They are defined
when creating or altering a table's schema.
Column constraints are rules or conditions applied to individual columns within a database table.
They are specified at the column level when creating or altering a table's schema.
The difference between the two is that column constraints apply only to individual columns, whereas
table constraints apply to groups of one or more columns.
Question 7
What is default value ? How do you define it ? What is the default value of column for which no
default value is define ?
Answer
A default value is a predefined value assigned to a column in a database table. It can be specified
using the DEFAULT clause when defining the table's schema. If no default value is defined for a
column, and a new row is inserted into the table without providing a value for that column, the
column's default value will be NULL, unless the column is defined with a NOT NULL constraint. In such
cases, an error will occur if a value is not provided.
Question 8(i)
Differentiate between DROP TABLE, DROP DATABASE.
Answer
DROP TABLE DROP DATABASE
This command is used to delete a specific This command is used to delete an entire
table from the database along with all its database including all its tables, views, stored
data, indexes, triggers, and constraints. procedures, triggers, and other objects.
This command is used to delete a specific This command is used to remove a specific
table from the database along with all its component of a table, such as columns,
data, indexes, triggers, and constraints. constraints, or indexes.
1990-12-
8369 SMITH CLERK 8902 800 NULL 20
18
1991-02-
8499 ANYA SALESMAN 8698 1600 300 30
20
1991-02-
8521 SETH SALESMAN 8698 1250 500 30
22
1991-04-
8566 MAHADEVAN MANAGER 8839 2985 NULL 20
02
1991-09-
8654 MOMIN SALESMAN 8698 1250 1400 30
28
1991-05-
8698 BINA MANAGER 8839 2850 NULL 30
01
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
1991-11-
8839 AMIR PRESIDENT NULL 5000 NULL 10
18
1991-09-
8844 KULDEEP SALESMAN 8698 1500 0 30
08
1991-06-
8882 SHIAVNSH MANAGER 8839 2450 NULL 10
09
1993-01-
8886 ANOOP CLERK 8888 1100 NULL 20
12
1992-12-
8888 SCOTT ANALYST 8566 3000 NULL 20
09
1991-12-
8900 JATIN CLERK 8698 950 NULL 30
03
1991-12-
8902 FAKIR ANALYST 8566 3000 NULL 20
03
1992-01-
8934 MITA CLERK 8882 1300 NULL 10
23
UPDATE Empl
SET COMM = 500
WHERE YEAR(HIREDATE) = 1982;
Explanation
Since there are no employees who joined in the year 1982 according to the data provided in the
"Empl" table, executing the given SQL query will result in no changes to the "COMM" column.
Question 4
Allocate the department situated in BOSTON to employee with employee number 7500 (tables EMPL,
Dept)
Answer
UPDATE EMPL
SET DEPTNO = (
SELECT DEPTNO
FROM Dept
WHERE LOC = 'BOSTON'
)
WHERE EMPNO = 7500;
Question 5
Given the following tables :
Orders (OrdNo, Ord_date, ProdNo#, Qty)
Product (ProdNo, Descp, Price)
Payment (OrdNo, Pment)
Write a query to delete all those records from table Orders whose complete payment has been made.
Answer
DELETE FROM Orders
WHERE OrdNo IN (
SELECT Payment.OrdNo
FROM Payment
WHERE Payment.Pment = 'COMPLETE');
Question 6
Enlist the names of all tables created by you.
Answer
SHOW TABLES ;
Question 7
Write Query statements for following transaction : (Consider tables of question 12)
1. Increase price of all products by 10%.
2. List the details of all orders whose payment is pending as per increased price.
3. Decrease prices by 10% for all those products for which orders were placed 10 months
before.
Answer
The following tables are considered :
Orders (OrdNo, Ord_date, ProdNo#, Qty)
Product (ProdNo, Descp, Price)
Payment (OrdNo, Pment)
1.
UPDATE product
SET price = (price * 0.1) + price ;
2.
SELECT *
FROM Orders
JOIN Payment ON Orders.OrdNo = Payment.OrdNo
WHERE Payment.Pment = 'Pending';
3.
UPDATE Product
SET Price = Price - (Price * 0.1)
WHERE ProdNo IN (
SELECT ProdNo#
FROM Orders
WHERE YEAR(Ord_date) = YEAR(CURDATE()) - 1
AND MONTH(Ord_date) = MONTH(CURDATE()) - 10
);
Question 8
Modify table Empl, add another column called Grade of VARCHAR type, size 1 into it.
Answer
ALTER TABLE Empl
ADD (Grade VARCHAR(1)) ;
Question 9
In the added column Grade, assign grades as follows :
if sal is in range 700 — 1500, Grade is 1 ;
if sal is in range 1500 — 2200, Grade is 2 ;
if sal is in range 2200 — 3000, Grade is 3 ;
if sal is in range 3000 — Grade is 4 ;
Answer
UPDATE Empl
SET Grade = '1'
WHERE Sal >= 700 AND Sal <= 1500;
UPDATE Empl
SET Grade = '2'
WHERE Sal > 1500 AND Sal <= 2200;
UPDATE Empl
SET Grade = '3'
WHERE Sal > 2200 AND Sal <= 3000;
UPDATE Empl
SET Grade = '4'
WHERE Sal > 3000;
Question 10
Add a constraint (NN-Grade) in table Empl that declares column Grade not null.
Answer
ALTER TABLE Empl
ADD CONSTRAINT NN_Grade
(Grade NOT NULL) ;
Question 11
Insert a record of your choice in table Empl. Make sure not to enter Grade.
Answer
INSERT INTO Empl (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
VALUES (12345, 'DEEPAK', 'CLERK', 8902, '1990-12-18', 8000, 200, 10);
Question 12
Modify the definition of column Grade. Increase its size to 2.
Answer
ALTER TABLE Empl
MODIFY (Grade VARCHAR(2)) ;
Question 13
Drop the table Empl.
Answer
DROP TABLE IF EXISTS Empl;
Question 14
Create the table Department table based on the following table instance chart.
Column Name ID Name
Length 8 25
Answer
CREATE TABLE Department (
ID NUMBER(8),
Name VARCHAR(25)
);
Question 15
Populate the table Department with data from table dept. Including only required columns.
Answer
INSERT INTO Department (ID, Name)
SELECT ID, Name
FROM dept ;
Question 16
Create the table Employee based on the following table instance chart.
Column Name Data Type Length
ID NUMBER 8
First_Name VARCHAR 25
Last_Name VARCHAR 25
Dept_ID NUMBER 8
Answer
CREATE TABLE Employee (
ID NUMBER(8),
First_Name VARCHAR(25),
Last_Name VARCHAR(25),
Dept_ID NUMBER(8)
);
Question 17
Drop table Employee and Department.
Answer
DROP TABLE IF EXISTS Employee ;
DROP TABLE IF EXISTS Department ;
Question 18
Create table Customer as per following Table Instance Chart.
Column Name Data Type Length
Cust_ID NUMBER 7
Cust_Name VARCHAR 30
Cust_Address1 VARCHAR 20
Cust_Address2 VARCHAR 30
Pincode NUMBER 6
Cust_Phone VARCHAR 10
Answer
CREATE TABLE Customer (
Cust_ID NUMBER(7),
Cust_Name VARCHAR(30),
Cust_Address1 VARCHAR(20),
Cust_Address2 VARCHAR(30),
Pincode NUMBER(6),
Cust_Phone VARCHAR(10)
);
Question 19
Add one column Email of data type VARCHAR and size 30 to the table Customer.
Answer
ALTER TABLE Customer
ADD (Email VARCHAR(30)) ;
Question 20
Add one more column CustomerIncomeGroup of datatype VARCHAR(10).
Answer
ALTER TABLE Customer
ADD (CustomerIncomeGroup VARCHAR(10));
Question 21
Insert few records with relevant information, in the table.
Answer
INSERT INTO Customer (Cust_ID, Cust_Name, Cust_Address1, Cust_Address2, Pincode, Cust_Phone,
Email, CustomerIncomeGroup)
VALUES
(11, 'Amit', '1st Main Street', 'Mumbai', 12345, '5551234121', '[email protected]', 'High'),
(24, 'Vidya', '4th Main Street', 'Bangalore', 54321, '5234325678', '[email protected]', 'Medium'),
(39, 'Amruta', '78th Main Street', 'Goa', 98765, '5976539012', '[email protected]', 'Low');
Question 22
Drop the column CustomerIncomeGroup from table Customer.
Answer
ALTER TABLE Customer
DROP COLUMN CustomerIncomeGroup ;
Question 23
Create table Department as per following Table Instance Chart.
Column Name DeptID DeptName
Length 2 20
Answer
CREATE TABLE Department (
DeptID NUMBER(2) PRIMARY KEY,
DeptName VARCHAR(20) NOT NULL
);
Question 24
Create table Employee as per following Table Instance Chart.
Column EmpNam EmpAddres EmpPhon
EmpID EmpSal DeptID
Name e s e
Nulls/Uniqu NOT
e NULL
Departmen
Fk Table
t
Fk Column Dept_ID
NUMBE NUMBE
Datatype VARCHAR VARCHAR VARCHAR VARCHAR
R R
Length 6 20 30 10 9, 2 2
Answer
CREATE TABLE Employee (
EmpID NUMBER(6) PRIMARY KEY,
EmpName VARCHAR(20) NOT NULL,
EmpAddress VARCHAR(30),
EmpPhone VARCHAR(10),
EmpSal NUMBER(9, 2),
DeptID VARCHAR(2),
FOREIGN KEY (DeptID) REFERENCES Department (Dept_ID)
ON DELETE CASCADE ON UPDATE CASCADE
);
Question 25
View structures of all tables created by you.
Answer
DESCRIBE <TABLENAME> ;
Chapter 15
Grouping Records, Joins in SQL
Type A: Short Answer Questions/Conceptual Questions
Question 1
What is the difference between HAVING and WHERE clause ?
Answer
HAVING clause WHERE clause
BOOK_ID
BOOK_TITLE
PRICE
Which SQL statement allows you to find the highest price from the table BOOK_INFORMATION?
1. SELECT BOOK_ID, BOOK_TITLE, MAX(PRICE) FROM BOOK_INFORMATION;
2. SELECT MAX(PRICE) FROM BOOK_INFORMATION;
3. SELECT MAXIMUM(PRICE) FROM BOOK_INFORMATION;
4. SELECT PRICE FROM BOOK_INFORMATION ORDER BY PRICE DESC;
Answer
SELECT MAX(PRICE) FROM BOOK_INFORMATION;
Explanation
1. SELECT BOOK_ID, BOOK_TITLE, MAX(PRICE) FROM BOOK_INFORMATION; — This query
selects the BOOK_ID, BOOK_TITLE, and maximum PRICE from the BOOK_INFORMATION table.
However, the requirement is to find the highest price only.
2. SELECT MAX(PRICE) FROM BOOK_INFORMATION; — This query selects the maximum
PRICE from the BOOK_INFORMATION table using the MAX() aggregate function. This option is
correct because it directly retrieves the highest price among all the books listed in the
BOOK_INFORMATION table, which is what the question asks for.
3. SELECT MAXIMUM(PRICE) FROM BOOK_INFORMATION; — There is no MAXIMUM()
function in SQL.
4. SELECT PRICE FROM BOOK_INFORMATION ORDER BY PRICE DESC; — This query selects
all prices from the BOOK_INFORMATION table and orders them in descending order using
ORDER BY PRICE DESC but it doesn't directly give the highest price.
Question 2
Table SALES
Column Name
STORE_ID
SALES_DATE
SALES_AMOUNT
Which SQL statement lets you find the sales amount for each store?
1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES;
2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES ORDER BY STORE_ID;
3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID;
4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES HAVING UNIQUE STORE_ID;
Answer
SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID;
Explanation
1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES; — This statement selects the
store_ID and calculates the total sales amount using SUM() aggregate function from the SALES
table. It does not group the results by store ID, so it will return a single row with the total sales
amount across all stores.
2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES ORDER BY STORE_ID; — This
statement selects the store_ID and calculates the total sales amount using SUM() aggregate
function from the SALES table and uses an ORDER BY clause to sort the results by store ID.
However, it still doesn't group the results by store_ID.
3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID; — This
statement selects the store_ID and calculates the total sales amount using SUM() aggregate
function from the SALES table and uses the GROUP BY clause to group the results by store ID.
It calculates the total sales amount for each store ID separately. As a result, it calculates the
total sales amount for each unique store ID separately, providing a breakdown of sales
amounts for each store in the dataset.
4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES HAVING UNIQUE STORE_ID; —
This statement is incorrect because the HAVING clause is used for filtering grouped data based
on a condition, not for identifying unique values. Also, "UNIQUE STORE_ID" is not a valid
condition in SQL.
Question 3
Table SALES
Column Name
STORE_ID
SALES_DATE
SALES_AMOUNT
Which SQL statement lets you list all stores whose total sales amount is over 5000 ?
1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING
SUM(SALES_AMOUNT) > 5000;
2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING
SALES_AMOUNT > 5000;
3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
WHERE SUM(SALES_AMOUNT) > 5000 GROUP BY STORE_ID;
4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
WHERE SALES_AMOUNT > 5000 GROUP BY STORE_ID;
Answer
SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
GROUP BY STORE_ID HAVING SUM(SALES_AMOUNT) > 5000;
Explanation
1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING
SUM(SALES_AMOUNT) > 5000; — This statement selects the store ID and calculates the total
sales amount for each store using the SUM() aggregate function. The GROUP BY STORE_ID
clause ensures that the results are grouped by store ID. The HAVING SUM(SALES_AMOUNT) >
5000 condition then filters the grouped data, selecting only those stores whose total sales
amount is over 5000.
2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING
SALES_AMOUNT > 5000; — This option is incorrect because the HAVING clause cannot directly
reference SALES_AMOUNT without an aggregate function like SUM() since
SUM(SALES_AMOUNT) is used in the SELECT statement.
3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE SUM(SALES_AMOUNT)
> 5000 GROUP BY STORE_ID; — This option is incorrect because aggregate functions like
SUM(SALES_AMOUNT) cannot be used directly in the WHERE clause. The WHERE clause is
used for filtering individual rows before grouping.
4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE SALES_AMOUNT >
5000 GROUP BY STORE_ID; — This option is incorrect because it tries to filter individual sales
amounts (SALES_AMOUNT) directly without using the SUM() aggregate function to calculate
the total sales amount for each store. The GROUP BY STORE_ID clause is used for grouping
after the filtering, which is not the correct approach for filtering based on the total sales
amount.
Question 4
Table SALES
Column Name
STORE_ID
SALES_DATE
SALES_AMOUNT
Which SQL statement lets you find the total number of stores in the SALES table?
1. SELECT COUNT(STORE_ID) FROM SALES;
2. SELECT COUNT(DISTINCT STORE_ID) FROM SALES;
3. SELECT DISTINCT STORE_ID FROM SALES;
4. SELECT COUNT(STORE_ID) FROM SALES GROUP BY STORE_ID;
Answer
SELECT COUNT(DISTINCT STORE_ID) FROM SALES;
Explanation
1. SELECT COUNT(STORE_ID) FROM SALES; — This query uses the COUNT() aggregate
function with the STORE_ID column in the SELECT statement. It counts the number of non-null
values in the STORE_ID column, and this count includes duplicates.
2. SELECT COUNT(DISTINCT STORE_ID) FROM SALES; — This option uses COUNT(DISTINCT
STORE_ID) to count the number of unique store IDs in the SALES table. The DISTINCT keyword
ensures that only distinct (unique) values are counted, avoiding overcounting due to
duplicates.
3. SELECT DISTINCT STORE_ID FROM SALES; — This option selects distinct (unique) store
IDs from the SALES table but does not count or provide the total number of stores.
4. SELECT COUNT(STORE_ID) FROM SALES GROUP BY STORE_ID; — This option attempts
to count the number of occurrences of each store ID by using COUNT(STORE_ID) and grouping
by store ID with GROUP BY STORE_ID. However, this results in a count for each unique store ID
separately, not the total number of stores in the table.
Question 5
Table SALES
Column Name
STORE_ID
SALES_DATE
SALES_AMOUNT
Which SQL statement allows you to find the total sales amount for Store ID 25 and the total sales
amount for Store ID 45?
1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
WHERE STORE_ID IN (25, 45) GROUP BY STORE_ID;
2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
GROUP BY STORE_ID HAVING STORE_ID IN (25, 45);
3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE STORE_ID IN (25, 45);
4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
WHERE STORE_ID = 25 AND STORE_ID = 45 GROUP BY STORE_ID;
Answer
SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
WHERE STORE_ID IN (25, 45) GROUP BY STORE_ID;
Explanation
1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE STORE_ID IN (25, 45)
GROUP BY STORE_ID; — This query uses the IN operator to filter rows where the STORE_ID is
either 25 or 45. It then calculates the total sales amount for each store ID using
SUM(SALES_AMOUNT) and groups the results by STORE_ID. This query correctly finds the total
sales amount for Store ID 25 and Store ID 45 separately.
2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING
STORE_ID IN (25, 45); — This query will also give the required output but it is inefficient
because it first retrieves all rows from the "SALES" table, then groups the results by store ID,
and finally filters the result set to include only store IDs 25 and 45. The inefficiency arises from
the fact that it processes all rows in the "SALES" table before filtering out the unnecessary
data. This means that it processes more data than necessary, which can be wasteful in terms
of computational resources and time. A more efficient approach would be to select only the
rows having store IDs 25 and 45 first (using WHERE clause), and then perform the aggregation.
3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE STORE_ID IN (25,
45); — This query filters rows where the STORE_ID is either 25 or 45 and calculates the total
sales amount for these store IDs using SUM(SALES_AMOUNT). However, it doesn't include a
GROUP BY clause, so it would return a single row with the total sales amount for both Store ID
25 and Store ID 45 combined.
4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE STORE_ID = 25 AND
STORE_ID = 45 GROUP BY STORE_ID; — This query filter rows where the STORE_ID is both 25
and 45 simultaneously using STORE_ID = 25 AND STORE_ID = 45. However, this condition is
impossible to satisfy because a single value cannot be both 25 and 45 at the same time.
Therefore, this query would not return any results.
Question 6
Table EXAM_RESULTS
STU ID FNAME LNAME EXAM ID EXAM_SCORE
10 LAURA LYNCH 1 90
10 LAURA LYNCH 2 85
11 GRACE BROWN 1 78
11 GRACE BROWN 2 72
12 JAY JACKSON 1 95
12 JAY JACKSON 2 92
13 WILLIAM BISHOP 1 70
14 CHARLES PRADA 2 85
What SQL statement do we use to find the average exam score for EXAM_ID = 1?
1. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS;
2. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID WHERE
EXAM_ID = 1;
3. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID HAVING
EXAM_ID = 1;
4. SELECT COUNT(EXAM_SCORE) FROM EXAM_RESULTS WHERE EXAM_ID = 1;
Answer
SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID HAVING EXAM_ID = 1;
Output
+-----------------+
| AVG(EXAM_SCORE) |
+-----------------+
| 83.2500 |
+-----------------+
Explanation
1. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS; — This statement calculates the
average exam score across all exam IDs in the EXAM_RESULTS table.
2. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID WHERE
EXAM_ID = 1; — This statement is incorrect because the WHERE clause should come before
the GROUP BY clause. Additionally, grouping by EXAM_ID and then trying to filter by EXAM_ID
= 1 within the GROUP BY clause will result in an error because grouping should be done before
filtering.
3. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID HAVING
EXAM_ID = 1; — This query groups the exam results by EXAM_ID and then calculates the
average exam score for each group. The HAVING clause filters the groups and returns only
those where the EXAM_ID is equal to 1, giving us the average exam score for the exam with
EXAM_ID equal to 1.
4. SELECT COUNT(EXAM_SCORE) FROM EXAM_RESULTS WHERE EXAM_ID = 1; — This
statement calculates the count of exam scores for EXAM_ID = 1, but it doesn't calculate the
average score.
Question 7
Table EXAM_RESULTS
STU ID FNAME LNAME EXAM ID EXAM_SCORE
10 LAURA LYNCH 1 90
10 LAURA LYNCH 2 85
11 GRACE BROWN 1 78
11 GRACE BROWN 2 72
12 JAY JACKSON 1 95
12 JAY JACKSON 2 92
13 WILLIAM BISHOP 1 70
14 CHARLES PRADA 2 85
Which SQL statement do we use to find out how many students took each exam?
1. SELECT COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID;
2. SELECT EXAM_ID, MAX(STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID;
3. SELECT EXAM_ID, COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY
EXAM_ID;
4. SELECT EXAM_ID, MIN(STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID;
Answer
SELECT EXAM_ID, COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID;
Output
+---------+------------------------+
| EXAM_ID | COUNT(DISTINCT STU_ID) |
+---------+------------------------+
| 1| 4|
| 2| 5|
+---------+------------------------+
Explanation
1. SELECT COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID; — It
groups the EXAM_RESULTS table by EXAM_ID and uses the COUNT(DISTINCT STU_ID) function
to count the number of distinct student IDs for each exam. However, the result set does not
include EXAM_ID.
2. SELECT EXAM_ID, MAX(STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID; — This
query groups the results by EXAM_ID and then selects the maximum STU_ID for each exam.
However, this doesn't provide the count of students who took each exam, as it gives the
maximum student ID instead of counting the distinct student IDs.
3. SELECT EXAM_ID, COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY
EXAM_ID; — It groups the EXAM_RESULTS table by EXAM_ID and uses the COUNT(DISTINCT
STU_ID) function to count the number of distinct student IDs for each exam. The result set
includes the EXAM_ID and the count of students who took each exam.
4. SELECT EXAM_ID, MIN(STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID; — This
query groups the results by EXAM_ID and selects the minimum STU_ID for each exam. It does
not provide information about the number of students who took each exam.
Question 8
Table EXAM_RESULTS
STU ID FNAME LNAME EXAM ID EXAM_SCORE
10 LAURA LYNCH 1 90
10 LAURA LYNCH 2 85
11 GRACE BROWN 1 78
11 GRACE BROWN 2 72
12 JAY JACKSON 1 95
12 JAY JACKSON 2 92
13 WILLIAM BISHOP 1 70
STU ID FNAME LNAME EXAM ID EXAM_SCORE
14 CHARLES PRADA 2 85
What SQL statement do we use to print out the record of all students whose last name starts with 'L'?
1. SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L%' ;
2. SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L';
3. SELECT * FROM EXAM_RESULTS WHERE LNAME 'L';
4. SELECT * FROM EXAM_RESULTS WHERE LNAME <> 'L';
Answer
SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L%' ;
Output
+--------+-------+-------+---------+------------+
| stu_id | fname | lname | exam_id | exam_score |
+--------+-------+-------+---------+------------+
| 10 | LAURA | LYNCH | 1| 90 |
| 10 | LAURA | LYNCH | 2| 85 |
+--------+-------+-------+---------+------------+
Explanation
1. SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L%'; — The LIKE operator is used
for pattern matching in SQL. '%' is a wildcard character that matches zero or more characters.
'L%' specifies that the last name (LNAME) should start with 'L' followed by zero or more
characters. The SELECT * statement retrieves all columns from the EXAM_RESULTS table for
the matching records.
2. SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L'; — This query attempts to
select all columns (*) from the EXAM_RESULTS table where the last name (LNAME) is exactly
equal to 'L'. However, when using the LIKE operator in SQL for pattern matching, we use
wildcard characters (%) to represent unknown parts of a string.
3. SELECT * FROM EXAM_RESULTS WHERE LNAME 'L'; — This statement contains a syntax
error. In SQL, when using the WHERE clause to filter records based on a specific condition, we
need to use comparison operators or functions to define the condition properly.
4. SELECT * FROM EXAM_RESULTS WHERE LNAME <> 'L'; — This query retrieves records
where the last name is not equal to 'L'. It does not specifically look for last names starting with
'L', so it's not the correct option for the given requirement.
Question 9
Table EXAM_RESULTS
STU ID FNAME LNAME EXAM ID EXAM_SCORE
10 LAURA LYNCH 1 90
10 LAURA LYNCH 2 85
11 GRACE BROWN 1 78
STU ID FNAME LNAME EXAM ID EXAM_SCORE
11 GRACE BROWN 2 72
12 JAY JACKSON 1 95
12 JAY JACKSON 2 92
13 WILLIAM BISHOP 1 70
14 CHARLES PRADA 2 85
What is the result of the following SQL statement ?
SELECT MAX(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID HAVING EXAM_ID = 1;
1. 90
2. 85
3. 100
4. 95
Answer
Output
+-----------------+
| MAX(EXAM_SCORE) |
+-----------------+
| 95 |
+-----------------+
Explanation
The above SQL query calculates the maximum exam score for EXAM_ID 1 from the EXAM_RESULTS
table, by grouping results based on EXAM_ID and filtering using HAVING.
Question 10
Given the following table :
Table : CLUB
COACH-ID COACHNAME AGE SPORTS DATOFAPP PAY SEX
first_name
last_name
address
city
state
zip
Orders
order id (PK)
order_date
amount
customer_id (FK)
List the total of customers' orders grouped by customer (id).
Answer
SELECT c.customer_id, COUNT(o.order_id) AS total_orders
FROM Customers c, orders o
WHERE c.customer_id = o.customer_id
GROUP BY c.customer_id;
Question 22
Below are the customer and order tables :
Customers
customer id (PK)
first_name
last_name
address
city
state
zip
Orders
order id (PK)
order_date
amount
customer_id (FK)
List the sum of the totals of orders grouped by customer and state.
Answer
SELECT c.customer_id, c.state, SUM(o.amount) AS total_order_amount
FROM Customers c, orders o
WHERE c.customer_id = o.customer_id
GROUP BY c.customer_id, c.state;
Question 23
Below are the customer and order tables :
Customers
customer id (PK)
first_name
last_name
address
city
state
zip
Orders
order id (PK)
order_date
amount
customer_id (FK)
List the customers (name) and the total amount of all their orders.
Answer
SELECT CONCAT(c.first_name, ' ', c.last_name) AS customer_name,
SUM(o.amount) AS total_order_amount
FROM Customers c, Orders o
WHERE c.customer_id = o.customer_id
GROUP BY c.customer_id;
Question 24
Schemas of tables EMPL, Dept, SalaryGrade are being shown below :
EMPL (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
db_con = mysql.connect(
host = "localhost",
user = "root",
password = "tiger",
database = "School"
)
cursor = db_con.cursor()
db_con.close()
Output
(101, 'RUHANII', 76.8, 'A', 'A', 'PENDING')
(103, 'SIMRAN', 81.2, 'A', 'B', 'EVALUATED')
Question 3
Predict the output of the following code :
import mysql.connector
db = mysql.connector.connect(....)
cursor = db.cursor()
sql1 = "update category set name = '%s' WHERE ID = %s" % ('CSS',2)
cursor.execute(sql1)
db.commit()
print("Rows affected:", cursor.rowcount)
db.close()
Answer
Table category
id name
1 abc
id name
2 pqr
3 xyz
Output
Rows affected: 1
SELECT * FROM category ;
+----+------+
| id | name |
+----+------+
| 1 | abc |
| 2 | CSS |
| 3 | xyz |
+----+------+
Explanation
This Python script uses the mysql.connector module to connect to MySQL database. It updates the
'name' field in the 'category' table where ID is 2 to 'CSS'. The cursor.execute() method executes the
SQL query, db.commit() commits the changes, and cursor.rowcount gives the number of affected
rows. Finally, db.close() closes the database connection, ending the Python interface with the MySQL
database.
Question 4
Explain what the following query will do ?
import mysql.connector
db = mysql.connector.connect(....)
cursor = db.cursor()
person_id = input("Enter required person id")
lastname = input("Enter required lastname")
db.execute("INSERT INTO staff (person_id, lastname) VALUES ({}, '{}')".format(person_id, lastname))
db.commit()
db.close()
Answer
This Python script uses the mysql.connector package to connect to MySQL database. Then it prompts
users for person ID and last name, inserts these values into the 'staff' table, using the INSERT INTO
SQL statement. After that, it executes the SQL query using the db.execute method. The changes made
by the query are then committed to the database using db.commit(), ensuring that the changes are
saved permanently. Finally, db.close() closes the database connection, ending the Python interface
with the MySQL database.
Question 5
Explain what the following query will do ?
import mysql.connector
db = mysql.connector.connect(....)
cursor = db.cursor()
db.execute("SELECT * FROM staff WHERE person_id in {}".format((1, 3, 4)))
db.commit()
db.close()
Answer
This Python script uses the mysql.connector package to connect to MySQL database. It executes an
SQL SELECT query on the 'staff' table, retrieving all rows where the 'person_id' is 1, 3, 4 (using the IN
clause). The db.commit() is unnecessary for a SELECT query since it doesn't modify the database,
and db.close() closes the database connection, ending the Python interface with the MySQL database.
Type B: Application Based Questions
Question 1
Design a Python application that fetches all the records from Pet table of menagerie database.
Answer
import mysql.connector
records = cursor.fetchall()
for record in records:
print(record)
db_con.close()
Output
('Fluffy', 'Harold', 'cat', 'f', datetime.date(1993, 2, 4), None)
('Claws', 'Gwen', 'cat', 'm', datetime.date(1994, 3, 17), None)
('Buffy', 'Harold', 'dog', 'f', datetime.date(1989, 5, 13), None)
('Fang', 'Benny', 'dog', 'm', datetime.date(1990, 8, 27), None)
('Bowser', 'Diane', 'dog', 'm', datetime.date(1979, 8, 31), datetime.date(1995, 7, 29))
('Chirpy', 'Gwen', 'bird', 'f', datetime.date(1998, 9, 11), None)
('Whistler', 'Gwen', 'bird', None, datetime.date(1997, 12, 9), None)
('Slim', 'Benny', 'snake', 'm', datetime.date(1996, 4, 29), None)
Question 2
Design a Python application that fetches only those records from Event table of menagerie database
where type is Kennel.
Answer
import mysql.connector
db_con = mysql.connector.connect(host = "localhost",
user = "root",
passwd = "lion",
database = "menagerie")
cursor = db_con.cursor()
records = cursor.fetchall()
for record in records:
print(record)
db_con.close()
Output
('Bowser', datetime.date(1991, 10, 12), 'kennel', None)
('Fang', datetime.date(1991, 10, 12), 'kennel', None)
Question 3
Schema of table EMPL is shown below :
EMPL (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
Design a Python application to obtain a search criteria from user and then fetch records based on that
from empl table. (given in chapter 13, Table 13.5)
Answer
Table Empl
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
1990-12-
8369 SMITH CLERK 8902 800 NULL 20
18
1991-02-
8499 ANYA SALESMAN 8698 1600 300 30
20
1991-02-
8521 SETH SALESMAN 8698 1250 500 30
22
1991-04-
8566 MAHADEVAN MANAGER 8839 2985 NULL 20
02
1991-09-
8654 MOMIN SALESMAN 8698 1250 1400 30
28
1991-05-
8698 BINA MANAGER 8839 2850 NULL 30
01
1991-11-
8839 AMIR PRESIDENT NULL 5000 NULL 10
18
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
1991-09-
8844 KULDEEP SALESMAN 8698 1500 0 30
08
1991-06-
8882 SHIAVNSH MANAGER 8839 2450 NULL 10
09
1993-01-
8886 ANOOP CLERK 8888 1100 NULL 20
12
1992-12-
8888 SCOTT ANALYST 8566 3000 NULL 20
09
1991-12-
8900 JATIN CLERK 8698 950 NULL 30
03
1991-12-
8902 FAKIR ANALYST 8566 3000 NULL 20
03
1992-01-
8934 MITA CLERK 8882 1300 NULL 10
23
import mysql.connector
records = cursor.fetchall()
print("Fetched records:")
for record in records:
print(record)
db_con.close()
Output
Enter search criteria : job = 'clerk'
Fetched records:
(8369, 'SMITH', 'CLERK', 8902, datetime.date(1990, 12, 18), 800.0, None, 20)
(8886, 'ANOOP', 'CLERK', 8888, datetime.date(1993, 1, 12), 1100.0, None, 20)
(8900, 'JATIN', 'CLERK', 8698, datetime.date(1991, 12, 3), 950.0, None, 30)
(8934, 'MITA', 'CLERK', 8882, datetime.date(1992, 1, 23), 1300.0, None, 10)