0% found this document useful (0 votes)
55 views67 pages

CS - Database (Chapter12-16-Assignments and Type ABC Solutions)

Uploaded by

priyahithesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views67 pages

CS - Database (Chapter12-16-Assignments and Type ABC Solutions)

Uploaded by

priyahithesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Chapter 12

Relational Databases - Assignments


Question 1
Summarize the major differences between a relation and a traditional file.
Answer
Relation file Traditional file

Data organized in tables with rows and


Data stored in unstructured formats.
columns.

Supports structured querying with SQL. Lacks standardized querying abilities.

Allows for defining relationships between


No inherent support for relationships.
tables.

Offers flexibility in data storage and


Limited flexibility in data organisation.
retrieval.

Examples : Text files, CSV files, Excel


Examples : MySQL, PostgreSQL
spreadsheets
Question 2(i)
Define database.
Answer
A database is defined as a collection of interrelated data stored together to serve multiple
applications.
Question 2(ii)
Define SQL.
Answer
The Structured Query Language (SQL) is a language that enables us to create and operate on
relational databases (RDBMS), which are sets of related information stored in tables.
Question 2(iii)
Define view.
Answer
A view is a (virtual) table that does not really exist in its own right but is instead derived from one or
more underlying base tables.
Question 3
What is data redundancy ? How does it impact a database ?
Answer
Duplication of data is known as data redundancy. Data redundancy in a database leads to wasted
storage and multiple copies of the same data. When these copies do not match with one another, it
leads to data inconsistency. Additionally, data redundancy can result in performance degradation,
security risks, and increased complexity.
Question 4
What is data inconsistency ? How does it impact a database ?
Answer
Mismatched multiple copies of same data is known as data inconsistency. Data inconsistency
undermines database reliability, hindering decision-making, causing operational errors, and increasing
complexity.
Question 5(i)
Define tuple.
Answer
The rows of tables (relations) are called tuples.
Question 5(ii)
Define attribute.
Answer
The columns of tables (relations) are called attributes.
Question 5(iii)
Define domain.
Answer
A domain is a pool of values from which the actual values appearing in a given column are drawn.
Question 5(iv)
Define degree.
Answer
The number of attributes in a relation is called degree of a relation.
Question 5(v)
Define cardinality.
Answer
The number of rows in a relation is known as cardinality of the relation.
Question 6(i)
Define primary key.
Answer
A primary key is a set of one or more attributes that can uniquely identify tuples within the relation.
Question 6(ii)
Define foreign key.
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.
Question 7
What is MySQL ? What are its functions and features ?
Answer
MySQL is a freely available open source Relational Database Management System (RDBMS) that uses
Structured Query Language (SQL). MySQL provides us with a rich set of features that support a secure
environment for storing, maintaining and accessing data.
The functions and features of MySQL are as follows :
1. Speed — If the server hardware is optimal, MySQL runs very fast. It supports clustered
servers for demanding applications.
2. Ease of use — MySQL is a high performance, relatively simple database system. From
the beginning, MySQL has typically been configured, monitored and managed from the
command line. However, several MySQL graphical interfaces are also available.
3. Query Language Support — MySQL understands standards based SQL.
4. Portability — MySQL provides portability as it has been tested with a broad range of
different compilers and can work on many different platforms. It is fully multi-threaded using
kernel threads. It can easily use multiple CPUs if they are available.
5. Cost — MySQL is available free of cost. MySQL is a open source database.
6. Data Types — MySQL provides many data types to support different types of data. It
also supports fixed-length and variable-length records.
7. Security — MySQL offers a privilege and password system that is very flexible and
secure, and that allows host-based verification. Passwords are secure because all password
traffic is encrypted when we connect to a server.
8. Scalability and Limits — MySQL can handle large databases. Some real life MySQL
databases contain 50 million records, some have up to 60,000 tables and about 5,000,000,000
rows.
9. Connectivity — Clients can connect to MySQL Server using several protocols.
10. Localization — The server can provide error messages to clients in many languages.
11. Clients and Tools — MySQL provides several client and utility programs. These include
both command-line programs such as mysqldump and mysqladmin, and graphical programs
such as MySQL Administrator and MySQL Query Browser. MySQL Server has built-in support
for SQL statements to check, optimize and repair tables.
Question 8
What is the role of database server in database management system ? Give the key features of
MySQL.
Answer
A database server is the key to solving the problems of database management system (information
system). In general, a server must reliably manage a large amount of data in a multi-user environment
so that many users can concurrently access the same data. A database server must also prevent
unauthorized access and provide efficient solutions for failure recovery.
The key features of MySQL are as follows :
1. Speed — If the server hardware is optimal, MySQL runs very fast. It supports clustered
servers for demanding applications.
2. Ease of use — MySQL is a high performance, relatively simple database system. From
the beginning, MySQL has typically been configured, monitored and managed from the
command line. However, several MySQL graphical interfaces are also available.
3. Query Language Support — MySQL understands standards based SQL.
4. Portability — MySQL provides portability as it has been tested with a broad range of
different compilers and can work on many different platforms. It is fully multi-threaded using
kernel threads. It can easily use multiple CPUs if they are available.
5. Cost — MySQL is available free of cost. MySQL is a open source database.
6. Data Types — MySQL provides many data types to support different types of data. It
also supports fixed-length and variable-length records.
7. Security — MySQL offers a privilege and password system that is very flexible and
secure, and that allows host-based verification. Passwords are secure because all password
traffic is encrypted when we connect to a server.
8. Scalability and Limits — MySQL can handle large databases. Some real life MySQL
databases contain 50 million records, some have up to 60,000 tables and about 5,000,000,000
rows.
9. Connectivity — Clients can connect to MySQL Server using several protocols.
10. Localization — The server can provide error messages to clients in many languages.
11. Clients and Tools — MySQL provides several client and utility programs. These include
both command-line programs such as mysqldump and mysqladmin, and graphical programs
such as MySQL Administrator and MySQL Query Browser. MySQL Server has built-in support
for SQL statements to check, optimize and repair tables.
Question 9
What is the use of SQL in MySQL ?
Answer
All programs and users accessing data within the MySQL database must utilize Structured Query
Language (SQL). MySQL is compatible with standard-based SQL, enabling it to understand and process
SQL commands efficiently. Additionally, the MySQL server incorporates built-in support for executing
SQL statements, allowing users to perform tasks such as checking, optimizing, and repairing tables.
Question 10
How are SQL commands classified ?
Answer
SQL commands can be divided into the following categories :
1. Data Definition Language (DDL) Commands
2. Data Manipulation Language (DML) Commands
3. Transaction Control Language (TCL) Commands
4. Session Control Commands
5. System Control Commands
Question 11
What functions should be performed by ideal DDL ?
Answer
An ideal DDL should perform the following functions :
1. It should identify the types of data division such as data item, segment, record and
data-base file.
2. It should give a unique name to each data-item-type, record-type, file-type, database
and other data subdivision.
3. It should specify the proper data types.
4. It should specify how the record types are related to make structures.
5. It may define the type of encoding the program uses in the data items (binary,
character, bit, string etc.). This should not be confused with the encoding employed in physical
representation.
6. It may define the length of the data items.
7. It may define the range of values that a data-item can assume.
8. It may specify means of checking for errors in the data.
9. It may specify privacy locks for preventing unauthorized reading or modification of the
data.
10. A logical data definition should not specify addressing, indexing or searching
techniques or specify the placement of data on the storage units, because these topics are in
the domain of physical, not logical, organization.
Question 12
Differentiate between DDL and DML commands.
Answer
Data Manipulation Language
Data Definition Language (DDL)
(DML)

DML is a language that enables


DDL provides a set of definitions to specify the
users to access or manipulate
storage structure and access methods used by the
data as organized by the
database system.
appropriate data model.

DDL commands are used to perform tasks such as


creating, altering, and dropping schema objects. DML commands are used to
They are also used to grant and revoke privileges and retrieve, insert, delete, modify
roles, as well as for maintenance commands related data stored in the database.
to tables.

Examples of DML commands are


Examples of DDL commands are CREATE, ALTER,
INSERT, UPDATE, DELETE, SELECT
DROP, GRANT, ANALYZE etc.
etc.
Question 13
Name some commands used to assign/revoke privileges from database users.
Answer
Commands used to assign/revoke privileges from database users are GRANT, REVOKE.
Question 14
Name some table maintenance commands.
Answer
Table maintenance commands are ANALYZE TABLE, CHECK TABLE, REPAIR TABLE, RESTORE TABLE.
Question 15
What is TCL part of SQL ?
Answer
TCL part of SQL includes commands for specifying the beginning and ending of transactions along
with commands to have control over transaction processing. Some examples of TCL commands are
COMMIT, ROLLBACK, SET TRANSACTION and SAVEPOINT. These commands manage changes made by
DML commands.

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

10 7 Sameer Cricket B Photography A

11 8 Sujit Tennis A Gardening C

12 7 Kamal Swimming B Photography B


StudentNo. Class Name GAME Grade1 SUPW Grade2

13 7 Veena Tennis C Cooking A

14 9 Archana Basket Ball A Literature A

15 10 Arpit Cricket A Gardening C


1. Display the names of the students who are getting a grade 'C' in either GAME or SUPW.
2. Display the different games offered in the school.
3. Display the SUPW taken up by the students, whose name starts with 'A'.
Answer
1.
SELECT Name
FROM STUDENT
WHERE Grade1 = 'C' OR Grade2 = 'C' ;
Output
+-------+
| Name |
+-------+
| Sujit |
| Veena |
| Arpit |
+-------+
2.
SELECT DISTINCT GAME
FROM STUDENT ;
Output
+-------------+
| GAME |
+-------------+
| Cricket |
| Tennis |
| Swimming |
| Basket Ball |
+-------------+
3.
SELECT SUPW
FROM STUDENT
WHERE Name LIKE 'A%' ;
Output
+------------+
| SUPW |
+------------+
| Literature |
| Gardening |
+------------+
Question 11
Write SQL commands for the following on the basis of given table SPORTS :
Table : SPORTS
StudentNo. Class Name Game1 Grade1 Game2 Grade2

10 7 Sameer Cricket B Swimming A

11 8 Sujit Tennis A Skating C

12 7 Kamal Swimming B Football B

13 7 Venna Tennis C Tennis A

14 9 Archana Basketball A Cricket A

15 10 Arpit Cricket A Athletics C


1. Display the names of the students who have grade 'C' in either Game1 or Game2 or
both.
2. Display the names of the students who have same game for both Game1 and Game2.
3. Display the games taken up by the students, whose name starts with 'A'.
Answer
1.
SELECT Name
FROM SPORTS
WHERE Grade1 = 'C' OR Grade2 = 'C' ;
Output
+-------+
| Name |
+-------+
| Sujit |
| Venna |
| Arpit |
+-------+
2.
SELECT Name
FROM SPORTS
WHERE Game1 = Game2 ;
Output
+-------+
| Name |
+-------+
| Venna |
+-------+
3.
SELECT Game1, Game2
FROM SPORTS
WHERE Name LIKE 'A%' ;
Output
+------------+-----------+
| Game1 | Game2 |
+------------+-----------+
| Basketball | Cricket |
| Cricket | Athletics |
+------------+-----------+
Question 12
Write SQL commands for the following on the basis of given table CLUB :
Table : CLUB
COACH_ID COACHNAME AGE SPORTS PAY SEX DATOFAPP

1 KUKREJA 35 KARATE 1000 M 1996-03-27

2 RAVINA 34 KARATE 1200 F 1998-01-20

3 KARAN 34 SQUASH 2000 M 1998-02-19

4 TARUN 33 BASKETBALL 1500 M 1998-01-01

5 ZUBIN 36 SWIMMING 750 M 1998-01-12

6 KETAKI 36 SWIMMING 800 F 1998-02-24

7 ANKITA 39 SQUASH 2200 F 1998-02-20

8 ZAREEN 37 KARATE 1100 F 1998-02-22

9 KUSH 41 SWIMMING 900 M 1998-01-13

10 SHAILYA 37 BASKETBALL 1700 M 1998-02-19


1. To show all information about the swimming coaches in the club.
2. To list names of all coaches with their date of appointment (DATOFAPP) in descending
order.
3. To display a report, showing coachname, pay, age and bonus (15% of pay) for all the
coaches.
Answer
1.
SELECT *
FROM CLUB
WHERE SPORTS = 'SWIMMING' ;
Output
+----------+-----------+-----+----------+-----+-----+------------+
| COACH_ID | COACHNAME | AGE | SPORTS | PAY | SEX | DATOFAPP |
+----------+-----------+-----+----------+-----+-----+------------+
| 5 | ZUBIN | 36 | SWIMMING | 750 | M | 1998-01-12 |
| 6 | KETAKI | 36 | SWIMMING | 800 | F | 1998-02-24 |
| 9 | KUSH | 41 | SWIMMING | 900 | M | 1998-01-13 |
+----------+-----------+-----+----------+-----+-----+------------+
2.
SELECT COACHNAME, DATOFAPP
FROM CLUB
ORDER BY DATOFAPP DESC ;
Output
+-----------+------------+
| COACHNAME | DATOFAPP |
+-----------+------------+
| KETAKI | 1998-02-24 |
| ZAREEN | 1998-02-22 |
| ANKITA | 1998-02-20 |
| KARAN | 1998-02-19 |
| SHAILYA | 1998-02-19 |
| RAVINA | 1998-01-20 |
| KUSH | 1998-01-13 |
| ZUBIN | 1998-01-12 |
| TARUN | 1998-01-01 |
| KUKREJA | 1996-03-27 |
+-----------+------------+
3.
SELECT COACHNAME, PAY, AGE, (PAY * 0.15) AS BONUS
FROM CLUB ;
Output
+-----------+------+-----+--------+
| COACHNAME | PAY | AGE | BONUS |
+-----------+------+-----+--------+
| KUKREJA | 1000 | 35 | 150.00 |
| RAVINA | 1200 | 34 | 180.00 |
| KARAN | 2000 | 34 | 300.00 |
| TARUN | 1500 | 33 | 225.00 |
| ZUBIN | 750 | 36 | 112.50 |
| KETAKI | 800 | 36 | 120.00 |
| ANKITA | 2200 | 39 | 330.00 |
| ZAREEN | 1100 | 37 | 165.00 |
| KUSH | 900 | 41 | 135.00 |
| SHAILYA | 1700 | 37 | 255.00 |
+-----------+------+-----+--------+
Question 13
Write SQL commands for the following on the basis of given table STUDENT1 :
Table : STUDENT1
No. Name Stipend Stream AvgMark Grade Class

1 Karan 400.00 Medical 78.5 B 12B

2 Divakar 450.00 Commerce 89.2 A 11C

3 Divya 300.00 Commerce 68.6 C 12C

4 Arun 350.00 Humanities 73.1 B 12C

5 Sabina 500.00 Nonmedical 90.6 A 11A

6 John 400.00 Medical 75.4 B 12B

7 Robert 250.00 Humanities 64.4 C 11A

8 Rubina 450.00 Nonmedical 88.5 A 12A

9 Vikas 500.00 Nonmedical 92.0 A 12A

10 Mohan 300.00 Commerce 67.5 C 12C


1. Select all the Nonmedical stream students from STUDENT1.
2. List the names of those students who are in class 12 sorted by Stipend.
3. List all students sorted by AvgMark in descending order.
4. Display a report, listing Name, Stipend, Stream and amount of stipend received in a
year assuming that the Stipend is paid every month.
Answer
1.
SELECT *
FROM STUDENT1
WHERE Stream = 'Nonmedical' ;
Output
+-----+--------+---------+------------+---------+-------+-------+
| No. | Name | Stipend | Stream | AvgMark | Grade | Class |
+-----+--------+---------+------------+---------+-------+-------+
| 5 | Sabina | 500 | Nonmedical | 90.6 | A | 11A |
| 8 | Rubina | 450 | Nonmedical | 88.5 | A | 12A |
| 9 | Vikas | 500 | Nonmedical | 92.0 | A | 12A |
+-----+--------+---------+------------+---------+-------+-------+
2.
SELECT Name
FROM STUDENT1
WHERE Class LIKE '12%'
ORDER BY Stipend ;
Output
+--------+
| Name |
+--------+
| Divya |
| Mohan |
| Arun |
| Karan |
| John |
| Rubina |
| Vikas |
+--------+
3.
SELECT *
FROM STUDENT1
ORDER BY AvgMark DESC ;
Output
+-----+---------+---------+------------+---------+-------+-------+
| No. | Name | Stipend | Stream | AvgMark | Grade | Class |
+-----+---------+---------+------------+---------+-------+-------+
| 9 | Vikas | 500 | Nonmedical | 92.0 | A | 12A |
| 5 | Sabina | 500 | Nonmedical | 90.6 | A | 11A |
| 2 | Divakar | 450 | Commerce | 89.2 | A | 11C |
| 8 | Rubina | 450 | Nonmedical | 88.5 | A | 12A |
| 1 | Karan | 400 | Medical | 78.5 | B | 12B |
| 6 | John | 400 | Medical | 75.4 | B | 12B |
| 4 | Arun | 350 | Humanities | 73.1 | B | 12C |
| 3 | Divya | 300 | Commerce | 68.6 | C | 12C |
| 10 | Mohan | 300 | Commerce | 67.5 | C | 12C |
| 7 | Robert | 250 | Humanities | 64.4 | C | 11A |
+-----+---------+---------+------------+---------+-------+-------+
4.
SELECT Name, Stipend, Stream, (Stipend * 12) AS Yearly_Stipend
FROM STUDENT1 ;
Output
+---------+---------+------------+----------------+
| Name | Stipend | Stream | Yearly_Stipend |
+---------+---------+------------+----------------+
| Karan | 400 | Medical | 4800 |
| Divakar | 450 | Commerce | 5400 |
| Divya | 300 | Commerce | 3600 |
| Arun | 350 | Humanities | 4200 |
| Sabina | 500 | Nonmedical | 6000 |
| John | 400 | Medical | 4800 |
| Robert | 250 | Humanities | 3000 |
| Rubina | 450 | Nonmedical | 5400 |
| Vikas | 500 | Nonmedical | 6000 |
| Mohan | 300 | Commerce | 3600 |
+---------+---------+------------+----------------+
Question 14
Consider the table Student1 of Q. 13. Give the output of following SQL statement :
1. SELECT TRUNCATE(AvgMark) FROM Student1 WHERE AvgMark < 75 ;
2. SELECT ROUND(AvgMark) FROM Student1 WHERE Grade = 'B' ;
3. SELECT CONCAT(Name, Stream) FROM Student1 WHERE Class = '12A' ;
4. SELECT RIGHT(Stream, 2) FROM Student1 ;
Answer
1. It will return error because no argument is passed as decimal places to truncate. Syntax of truncate
function is TRUNCATE(number, decimals).
2.
Output
+----------------+
| ROUND(AvgMark) |
+----------------+
| 78 |
| 73 |
| 75 |
+----------------+
3.
Output
+----------------------+
| CONCAT(Name, Stream) |
+----------------------+
| RubinaNonmedical |
| VikasNonmedical |
+----------------------+
4.
Output
+------------------+
| RIGHT(Stream, 2) |
+------------------+
| al |
| ce |
| ce |
| es |
| al |
| al |
| es |
| al |
| al |
| ce |
+------------------+
Question 15
Given the following table :
Table : STUDENT
No. Name Stipend Stream AvgMark Grade Class

1 Karan 400.00 Medical 78.5 B 12B

2 Divakar 450.00 Commerce 89.2 A 11C

3 Divya 300.00 Commerce 68.6 C 12C

4 Arun 350.00 Humanities 73.1 B 12C

5 Sabina 500.00 Nonmedical 90.6 A 11A

6 John 400.00 Medical 75.4 B 12B

7 Robert 250.00 Humanities 64.4 C 11A

8 Rubina 450.00 Nonmedical 88.5 A 12A

9 Vikas 500.00 Nonmedical 92.0 A 12A

10 Mohan 300.00 Commerce 67.5 C 12C


Give the output of following SQL statements :
1. SELECT MIN(AvgMark) FROM STUDENT WHERE AvgMark < 75 ;
2. SELECT SUM(Stipend) FROM STUDENT WHERE Grade = 'B' ;
3. SELECT AVG(Stipend) FROM STUDENT WHERE Class = '12A' ;
4. SELECT COUNT(DISTINCT) FROM STUDENT ;
Answer
1.
Output
+--------------+
| MIN(AvgMark) |
+--------------+
| 64.4 |
+--------------+
2.
Output
+--------------+
| SUM(Stipend) |
+--------------+
| 1150 |
+--------------+
3.
Output
+--------------+
| AVG(Stipend) |
+--------------+
| 475 |
+--------------+
4. It will give an error because the COUNT function requires an argument specifying what to count.
Additionally, the DISTINCT keyword is followed by a column name to count the distinct values of that
column.
Question 16
Write SQL commands for the following on the basis of given table MOV :
Table : MOV
No Title Type Rating Stars Qty Price

1 Gone with the Wind Drama G Gable 4 39.95

2 Friday the 13th Horror R Jason 2 69.95

3 Top Gun Drama PG Cruise 7 49.95

4 Splash Comedy PG13 Hanks 3 29.95

5 Independence Day Drama R Turner 3 19.95

6 Risky Business Comedy R Cruise 2 44.95

7 Cocoon Scifi PG Ameche 2 31.95

8 Crocodile Dundee Comedy PG13 Harris 2 69.95

9 101 Dalmatians Comedy G 3 59.95

10 Tootsie Comedy PG Hoffman 1 29.95


1. Display a list of all movies with Price over 20 and sorted by Price.
2. Display all the movies sorted by QTY in decreasing order.
3. Display a report listing a movie number, current value and replacement value for each
movie in the above table. Calculate the replacement value for all movies as : QTY * Price *
1.15.
Answer
1.
SELECT Title
FROM MOV
WHERE Price > 20
ORDER BY Price ;
Output
+--------------------+
| Title |
+--------------------+
| Splash |
| Tootsie |
| Cocoon |
| Gone with the Wind |
| Risky Business |
| Top Gun |
| 101 Dalmatians |
| Friday the 13th |
| Crocodile Dundee |
+--------------------+
2.
SELECT Title
FROM MOV
ORDER BY Qty DESC ;
Output
+--------------------+
| Title |
+--------------------+
| Top Gun |
| Gone with the Wind |
| Splash |
| Independence Day |
| 101 Dalmatians |
| Friday the 13th |
| Risky Business |
| Cocoon |
| Crocodile Dundee |
| Tootsie |
+--------------------+
3.
SELECT No AS Movie_Number , Price AS Current_Value, (Qty * Price * 1.15) AS Replacement_Value
FROM MOV ;
Output
+--------------+---------------+--------------------+
| Movie_Number | Current_Value | Replacement_Value |
+--------------+---------------+--------------------+
| 1| 39.95 | 183.77000350952147 |
| 2| 69.95 | 160.884992980957 |
| 3| 49.95 | 402.09750614166256 |
| 4| 29.95 | 103.3275026321411 |
| 5| 19.95 | 68.8275026321411 |
| 6| 44.95 | 103.38500175476074 |
| 7| 31.95 | 73.48500175476073 |
| 8| 69.95 | 160.884992980957 |
| 9| 59.95 | 206.8275026321411 |
| 10 | 29.95 | 34.44250087738037 |
+--------------+---------------+--------------------+
Question 17
Write SQL commands for the following on the basis of given table Teacher :
Table : Teacher
No Name Age Department Salary Sex Dateofjoin

1 Jugal 34 Computer 12000 M 1997-01-10

2 Sharmila 31 History 20000 F 1998-03-24

3 Sandeep 32 Maths 30000 M 1996-12-12

4 Sangeeta 35 History 40000 F 1999-07-01

5 Rakesh 42 Maths 25000 M 1997-09-05

6 Shyam 50 History 30000 M 1998-06-27

7 Shiv Om 44 Computer 21000 M 1997-02-25

8 Shalakha 33 Maths 20000 F 1997-07-31


1. To show all information about the teacher of history department.
2. To list the names of female teachers who are in Hindi department.
3. To list names of all teachers with their date of joining in ascending order.
Answer
1.
SELECT *
FROM Teacher
WHERE Department = 'History' ;
Output
+----+----------+-----+------------+--------+-----+------------+
| No | Name | Age | Department | Salary | Sex | Dateofjoin |
+----+----------+-----+------------+--------+-----+------------+
| 2 | Sharmila | 31 | History | 20000 | F | 1998-03-24 |
| 4 | Sangeeta | 35 | History | 40000 | F | 1999-07-01 |
| 6 | Shyam | 50 | History | 30000 | M | 1998-06-27 |
+----+----------+-----+------------+--------+-----+------------+
2.
SELECT Name
FROM Teacher
WHERE Sex = 'F' and Department = 'Hindi' ;
Explanation
There are no records in the Teacher table where the department is 'Hindi'. Hence, there will be no
output.
3.
SELECT Name, Dateofjoin
FROM Teacher
ORDER BY Dateofjoin ;
Output
+----------+------------+
| Name | Dateofjoin |
+----------+------------+
| Sandeep | 1996-12-12 |
| Jugal | 1997-01-10 |
| Shiv Om | 1997-02-25 |
| Shalakha | 1997-07-31 |
| Rakesh | 1997-09-05 |
| Sharmila | 1998-03-24 |
| Shyam | 1998-06-27 |
| Sangeeta | 1999-07-01 |
+----------+------------+

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.

The syntax is : DROP DATABASE


The syntax is : DROP TABLE table_name;.
database_name;.
Question 8(ii)
Differentiate between DROP TABLE, DROP clause of ALTER TABLE.
Answer
DROP TABLE DROP clause of ALTER TABLE

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.

The syntax is : ALTER TABLE table_name


The syntax is : DROP TABLE table_name;
DROP COLUMN column_name;
Type B: Application Based Questions
Question 1
Insert all those records of table Accounts into table Pending where amt_outstanding is more than
10000.
Answer
INSERT INTO Pending
SELECT * FROM Accounts
WHERE amt_outstanding > 10000;
Question 2
Increase salary of employee records by 10% (table employee).
Answer
Table employee
ID First_Name Last_Name User_ID Salary

1 Dim Joseph Jdim 5000


ID First_Name Last_Name User_ID Salary

2 Jaganath Mishra jnmishra 4000

3 Siddharth Mishra smishra 8000

4 Shankar Giri sgiri 7000

5 Gautam Buddha bgautam 2000


UPDATE employee
SET Salary = (Salary * 0.1) + Salary ;
Output
To view all the details (all columns and rows) of the "employee" table the below query is executed :
SELECT * FROM employee ;
+----+------------+-----------+----------+--------+
| ID | First_Name | Last_Name | User_ID | Salary |
+----+------------+-----------+----------+--------+
| 1 | Dim | Joseph | Jdim | 5500 |
| 2 | Jaganath | Mishra | jnmishra | 4400 |
| 3 | Siddharth | Mishra | smishra | 8800 |
| 4 | Shankar | Giri | sgiri | 7700 |
| 5 | Gautam | Buddha | bgautam | 2200 |
+----+------------+-----------+----------+--------+
Question 3
Give commission of Rs.500 to all employees who joined in year 1982 (table Empl).
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
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

Data Type NUMBER VARCHAR

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

Key Type Primary

Nulls/Unique NOT NULL

Datatype NUMBER VARCHAR

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

Key Type Primary Foreign

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

HAVING conditions are applicable to groups WHERE conditions are applicable to


formed by GROUP BY clause. individual rows.

HAVING conditions can include aggregate WHERE conditions cannot include


functions. aggregate functions.

It filters rows based on specified


It allows conditions to be applied to grouped data.
conditions.
Question 2
What is the use of GROUP BY clause ?
Answer
The GROUP BY clause in SQL is used to combine all records that have identical values in a particular
field or group of fields. This grouping results in one summary record per group if group functions,
such as aggregate functions, are used with it.
Question 3
What are aggregate functions? What is their use? Give some examples.
Answer
Aggregate functions in SQL work with data from multiple rows at a time and return a single
aggregated value. They are used to perform calculations across multiple rows and return a summary
result for that group.
Examples of aggregate functions include SUM(), COUNT(), MAX(), MIN(), AVG() etc.
Question 4
What type of functions can you use with GROUP BY and HAVING clauses ?
Answer
Aggregate functions are used with the GROUP BY and HAVING clauses to apply conditions on grouped
data.
Question 5
What is sql join ? How is it useful ?
Answer
A SQL join is a query that combines rows from two or more tables. Join allows retrieving data from
related tables simultaneously in a single query. Joins enable the combination of data from different
tables to obtain a comprehensive view of the information.
Question 6
What are most common types of SQL joins ?
Answer
The most common types of SQL joins are as follows :
1. Equi-Join
2. Non-Equi-Join
3. Natural join
Type B: Application Based Questions
Question 1
Table BOOK_INFORMATION
Column Name

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

13 WILLIAM BISHOP 2 100

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

13 WILLIAM BISHOP 2 100

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

13 WILLIAM BISHOP 2 100

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

13 WILLIAM BISHOP 2 100

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

1 KUKREJA 35 KARATE 27/03/1996 1000 M

2 RAVINA 34 KARATE 20/01/1998 1200 F

3 KARAN 34 SQUASH 19/02/1998 2000 M

4 TARUN 33 BASKETBALL 01/01/1998 1500 M

5 ZUBIN 36 SWIMMING 12/01/1998 750 M

6 KETAKI 36 SWIMMING 24/02/1998 800 F

7 ANKITA 39 SQUASH 20/02/1998 2200 F


COACH-ID COACHNAME AGE SPORTS DATOFAPP PAY SEX

8 ZAREEN 37 KARATE 22/02/1998 1100 F

9 KUSH 41 SWIMMING 13/01/1998 900 M

10 SHAILYA 37 BASKETBALL 19/02/1998 1700 M


Give the output of following SQL statements :
1. SELECT COUNT(DISTINCT SPORTS) FROM Club ;
2. SELECT MIN(Age) FROM CLUB WHERE Sex = 'F' ;
3. SELECT AVG(Pay) FROM CLUB WHERE Sports = 'KARATE' ;
4. SELECT SUM(Pay) FROM CLUB WHERE Datofapp > '1998-01-31' ;
Answer
1.
Output
+------------------------+
| COUNT(DISTINCT SPORTS) |
+------------------------+
| 4|
+------------------------+
Explanation
The SQL query SELECT COUNT(DISTINCT SPORTS) FROM Club ; calculates the count of unique values in
the 'SPORTS' column of the 'Club' table. This query helps us to get information about the number of
sports offered by the club.
2.
Output
+----------+
| MIN(Age) |
+----------+
| 34 |
+----------+
Explanation
The SQL query SELECT MIN(Age) FROM CLUB WHERE Sex = 'F' ; retrieves the minimum Age from the
'CLUB' table where the 'Sex' column has the value 'F'. This query gives us the age of the youngest
female coach in the club.
3.
Output
+-----------+
| AVG(Pay) |
+-----------+
| 1100.0000 |
+-----------+
Explanation
The SQL query SELECT AVG(Pay) FROM CLUB WHERE Sports = 'KARATE' ; calculates the average value
of the 'Pay' column from the 'CLUB' table where the 'Sports' column has the value 'KARATE'. This
query helps us to get information about the average pay of karate coaches in the club.
4.
Output
+----------+
| SUM(Pay) |
+----------+
| 7800 |
+----------+
Explanation
The SQL query SELECT SUM(Pay) FROM CLUB WHERE Dateofapp > '1998-01-31'; calculates the sum of
the 'Pay' column from the 'CLUB' table where the 'Dateofapp' column has a date value greater than
'1998-01-31'. This query gives us the total pay of all the coaches who joined after 31/01/1998.
Question 11
In a Database, there are two tables given below :
Table : EMPLOYEE
EMPLOYEEID NAME SALES JOBID

E1 SUMIT SINHA 1100000 102

E2 VIJAY SINGH TOMAR 1300000 101

E3 AJAY RAJPAL 1400000 103

E4 MOHIT RAMNANI 1250000 102

E5 SHAILJA SINGH 1450000 103


Table : JOB
JOBID JOBTITLE SALARY

101 President 200000

102 Vice President 125000

103 Administration Assistant 80000

104 Accounting Manager 70000

105 Accountant 65000

106 Sales Manager 80000


Write SQL Queries for the following :
1. To display employee ids, names of employees, job ids with corresponding job titles.
2. To display names of employees, sales and corresponding job titles who have achieved
sales more than 1300000.
3. To display names and corresponding job titles of those employees who have 'SINGH'
(anywhere) in their names.
4. Identify foreign key in the table EMPLOYEE.
5. Write SQL command to change the JOBID to 104 of the EMPLOYEE with ID as E4 in the
table 'EMPLOYEE'.
Answer
1.
SELECT EMPLOYEE.EMPLOYEEID, EMPLOYEE.NAME, EMPLOYEE.JOBID, JOB.JOBTITLE
FROM EMPLOYEE, JOB
WHERE EMPLOYEE.JOBID = JOB.JOBID;
Output
+------------+-------------------+-------+--------------------------+
| EMPLOYEEID | NAME | JOBID | JOBTITLE |
+------------+-------------------+-------+--------------------------+
| E1 | SUMIT SINHA | 102 | VICE PRESIDENT |
| E2 | VIJAY SINGH TOMAR | 101 | PRESIDENT |
| E3 | AJAY RAJPAL | 103 | ADMINISTARTION ASSISTANT |
| E4 | MOHIT RAMNANI | 102 | VICE PRESIDENT |
| E5 | SHAILJA SINGH | 103 | ADMINISTARTION ASSISTANT |
+------------+-------------------+-------+--------------------------+
2.
SELECT EMPLOYEE.NAME, EMPLOYEE.SALES, JOB.JOBTITLE
FROM EMPLOYEE, JOB
WHERE EMPLOYEE.JOBID = JOB.JOBID
AND EMPLOYEE.SALES > 1300000;
Output
+---------------+---------+--------------------------+
| NAME | SALES | JOBTITLE |
+---------------+---------+--------------------------+
| AJAY RAJPAL | 1400000 | ADMINISTARTION ASSISTANT |
| SHAILJA SINGH | 1450000 | ADMINISTARTION ASSISTANT |
+---------------+---------+--------------------------+
3.
SELECT EMPLOYEE.NAME, JOB.JOBTITLE
FROM EMPLOYEE, JOB
WHERE EMPLOYEE.JOBID = JOB.JOBID
AND EMPLOYEE.NAME LIKE '%SINGH%';
Output
+-------------------+--------------------------+
| NAME | JOBTITLE |
+-------------------+--------------------------+
| VIJAY SINGH TOMAR | PRESIDENT |
| SHAILJA SINGH | ADMINISTARTION ASSISTANT |
+-------------------+--------------------------+
4. In the given tables, EMPLOYEE and JOB, the JOBID column in the EMPLOYEE table is a foreign key
referencing the JOBID column in the JOB table.
5.
UPDATE EMPLOYEE
SET JOBID = 104
WHERE EMPLOYEEID = 'E4';
Output
SELECT * FROM EMPLOYEE ;
+------------+-------------------+---------+-------+
| EMPLOYEEID | NAME | SALES | JOBID |
+------------+-------------------+---------+-------+
| E1 | SUMIT AINHA | 1100000 | 102 |
| E2 | VIJAY SINGH TOMAR | 1300000 | 101 |
| E3 | AJAY RAJPAL | 1400000 | 103 |
| E4 | MOHIT RAMNANI | 1250000 | 104 |
| E5 | SHAILJA SINGH | 1450000 | 103 |
+------------+-------------------+---------+-------+
Question 12
Consider the following tables Employee and Salary. Write SQL commands for the statements (i) to (iv)
and give outputs for SQL queries (v) to (vii)
Table : Employee
Eid Name Depid Qualification Sec

1 Deepali Gupta 101 MCA F

2 Rajat Tyagi 101 BCA M

3 Hari Mohan 102 B.A. M

4 Harry 102 M.A. M

5 Sumit Mittal 103 B.Tech. M

6 Jyoti 101 M.Tech. F


Table : Salary
Eid Basic D.A HRA Bonus

1 6000 2000 2300 200

2 2000 300 300 30

3 1000 300 300 40

4 1500 390 490 30

5 8000 900 900 80


Eid Basic D.A HRA Bonus

6 10000 300 490 89


1. To display the frequency of employees department wise.
2. To list the names of those employees only whose name starts with 'H'
3. To add a new column in salary table. The column name is Total_Sal.
4. To store the corresponding values in the Total_Sal column.
5. Select max(Basic) from Salary where Bonus > 40 ;
6. Select count(*) from Employee group by Sex ;
7. Select Distinct Depid from Employee ;
Answer
1.
SELECT Depid, COUNT(*) AS Frequency
FROM Employee
GROUP BY Depid;
2.
SELECT Name
FROM Employee
WHERE Name LIKE 'H%';
3.
ALTER TABLE Salary
ADD COLUMN Total_Sal FLOAT;
4.
UPDATE Salary
SET Total_Sal = Basic + `D.A.` + HRA + Bonus;
5.
SELECT MAX(Basic)
FROM Salary
WHERE Bonus > 40;
Output
+------------+
| MAX(Basic) |
+------------+
| 10000 |
+------------+
6.
SELECT Sec as sex, COUNT(*) AS Count
FROM Employee
GROUP BY Sec ;
Output
+-----+-------+
| sex | Count |
+-----+-------+
|F | 2|
|M | 4|
+-----+-------+
7.
SELECT DISTINCT Depid FROM Employee ;
Output
+-------+
| Depid |
+-------+
| 101 |
| 102 |
| 103 |
+-------+
Question 13
With reference to following relations PERSONAL and JOB answer the questions that follow :
Create following tables such that Empno and Sno are not null and unique, date of birth is after '12-
Jan-1960', name is never blank, Area and Native place is valid, hobby, dept is not empty, salary is
between 4000 and 10000.
Table : Personal
Empno Name Dobirth Native-place Hobby

123 Amit 23-Jan-1965 Delhi Music

127 Manoj 12-dec-1976 Mumbai Writing

124 Abhai 11-aug-1975 Allahabad Music

125 Vinod 04-apr-1977 Delhi Sports

128 Abhay 10-mar-1974 Mumbai Gardening

129 Ramesh 28-oct-1981 Pune Sports


Table : Job
Sno Area App_date Salary Retd_date Dept

123 Agra 25-jan-2006 5000 25-jan-2026 Marketing

127 Mathura 22-dec-2006 6000 22-dec-2026 Finance

124 Agra 19-aug-2007 5500 19-aug-2027 Marketing

125 Delhi 14-apr-2004 8500 14-apr-2018 Sales

128 Pune 13-mar-2008 7500 13-mar-2028 Sales

129 Bangalore 21-july-2003 7000 21-july-2023 Finance


(a) Show empno, name and salary of those who have Sports as hobby.
(b) Show name of the eldest employee.
(c) Show number of employee area wise.
(d) Show youngest employees from each Native place.
(e) Show Sno, Name, Hobby and Salary in descending order of Salary.
(f) Show the hobbies of those whose name pronounces as 'Abhay'.
(g) Show the appointment date and native place of those whose name starts with 'A' or ends in 'd'.
(h) Show the salary expense with suitable column heading of those who shall retire after 20-jan-2006.
(i) Show additional burden on the company in case salary of employees having hobby as sports, is
increased by 10%.
(j) Show the hobby of which there are 2 or more employees.
(k) Show how many employee shall retire today if maximum length of service is 20 years.
(l) Show those employee name and date of birth who have served more than 17 years as on date.
(m) Show names of those who earn more than all of the employees of Sales dept.
(n) Increase salary of the employees by 5 % of their present salary with hobby as Music or they have
completed atleast 3 years of service.
(o) Write the output of :
1. Select distinct hobby from personal ;
2. Select avg(salary) from personal, job where Personal.Empno = Job.Sno and Area in
('Agra','Delhi') ;
3. Select count(distinct Native_place) from personal.
4. Select name, max(salary) from Personal, Job where Personal.Empno = Job.Sno;
(p) Add a new tuple in the table Personal essentially with hobby as Music.
(q) Insert a new column email in Job table
(r) Create a table with values of columns empno, name, and hobby.
(s) Create a view of Personal and Job details of those who have served less than 15 years.
(t) Erase the records of employee from Job table whose hobby is not Sports.
(u) Remove the table Personal.
Answer
(a)
SELECT P.EMPNO, P.NAME, J.Salary
FROM PERSONAL P, JOB J
WHERE P.EMPNO = J.Sno AND P.Hobby = 'Sports';
Output
+-------+--------+--------+
| EMPNO | NAME | Salary |
+-------+--------+--------+
| 125 | Vinod | 8500 |
| 129 | Ramesh | 7000 |
+-------+--------+--------+
(b)
SELECT name
FROM personal
WHERE dobirth = (
SELECT MIN(dobirth)
FROM personal
);
Output
+------+
| name |
+------+
| Amit |
+------+
(c)
SELECT Area, COUNT(Sno) AS Employee_Count
FROM Job
GROUP BY Area;
Output
+-----------+----------------+
| Area | Employee_Count |
+-----------+----------------+
| Agra | 2|
| Delhi | 1|
| Mathura | 1|
| Pune | 1|
| Bangalore | 1|
+-----------+----------------+
(d)
SELECT Name, `Native-place`, dobirth
FROM personal
WHERE dobirth = (SELECT MAX(dobirth)
FROM personal p2
WHERE personal.`Native-place` = p2.`Native-place` ) ;
Output
+--------+--------------+------------+
| Name | Native-place | dobirth |
+--------+--------------+------------+
| Abhai | Allahabad | 1975-08-11 |
| Vinod | Delhi | 1977-04-04 |
| Manoj | Mumbai | 1976-12-12 |
| Ramesh | Pune | 1981-10-28 |
+--------+--------------+------------+
(e)
SELECT SNO, NAME, HOBBY, SALARY
FROM PERSONAL, JOB
WHERE PERSONAL.EMPNO = JOB.SNO
ORDER BY SALARY DESC;
Output
+-----+--------+-----------+--------+
| SNO | NAME | HOBBY | SALARY |
+-----+--------+-----------+--------+
| 125 | Vinod | Sports | 8500 |
| 128 | Abhay | Gardening | 7500 |
| 129 | Ramesh | Sports | 7000 |
| 127 | Manoj | Writing | 6000 |
| 124 | Abhai | Music | 5500 |
| 123 | Amit | Music | 5000 |
+-----+--------+-----------+--------+
(f)
SELECT HOBBY
FROM PERSONAL
WHERE Name = 'abhay' or Name = 'abhai' ;
Output
+-----------+
| HOBBY |
+-----------+
| Music |
| Gardening |
+-----------+
(g)
SELECT App_date, nativeplace
FROM personal, job
WHERE personal.empno = job.sno
AND (Name LIKE 'A%' OR Name LIKE '%d') ;
Output
+------------+--------------+
| App_date | native-place |
+------------+--------------+
| 2006-01-25 | Delhi |
| 2007-08-19 | Allahabad |
| 2004-04-14 | Delhi |
| 2008-03-13 | Mumbai |
+------------+--------------+
(h)
SELECT Salary AS "Salary Expense"
FROM Job
WHERE `Retd_date` > '2006-01-20';
Output
+----------------+
| Salary Expense |
+----------------+
| 5000 |
| 5500 |
| 8500 |
| 6000 |
| 7500 |
| 7000 |
+----------------+
(i)
SELECT SUM(Salary * 0.1) AS "Additional Burden"
FROM PERSONAL, JOB
WHERE PERSONAL.EMPNO = JOB.SNO AND HOBBY = 'SPORTS' ;
Output
+-------------------+
| Additional Burden |
+-------------------+
| 1550.0 |
+-------------------+
(j)
SELECT Hobby
FROM PERSONAL
GROUP BY Hobby
HAVING COUNT(*) >= 2;
Output
+--------+
| Hobby |
+--------+
| Music |
| Sports |
+--------+
(k)
SELECT COUNT(*)
FROM Job
WHERE DATEDIFF(CURDATE(), App_date) >= 20 * 365;
Output
+----------+
| COUNT(*) |
+----------+
| 0|
+----------+
(l)
SELECT P.Name, P.Dobirth
FROM Personal P, Job J
WHERE P.Empno = J.Sno AND J.Retd_date > CURDATE() AND DATEDIFF(CURDATE(), J.App_date) > 17 *
365;
Output
+-------+------------+
| Name | Dobirth |
+-------+------------+
| Amit | 1965-01-23 |
| Manoj | 1976-12-12 |
+-------+------------+
(m)
SELECT Name
FROM Personal, job
where personal.Empno = job.Sno
and job.Salary > ( select max(salary)
from job
where dept = 'sales');
Explanation
There will be no output because there are no employees whose salary is greater than the highest
salary in the Sales department.
(n)
UPDATE Job J, Personal P
SET J.Salary = (J.Salary * 0.05 ) + J.Salary
WHERE J.Sno = P.Empno
AND (P.Hobby = 'Music'
OR DATEDIFF(CURDATE(), J.App_date) >= 3 * 365);
Output
+-----+-----------+------------+--------+------------+-----------+
| sno | area | app_date | salary | retd_date | dept |
+-----+-----------+------------+--------+------------+-----------+
| 123 | Agra | 2006-01-25 | 5250 | 2026-01-25 | Marketing |
| 124 | Agra | 2007-08-19 | 5775 | 2027-08-19 | Marketing |
| 125 | Delhi | 2004-04-14 | 8925 | 2018-04-14 | Sales |
| 127 | Mathura | 2006-12-22 | 6300 | 2026-12-22 | Finance |
| 128 | Pune | 2008-03-13 | 7875 | 2028-03-13 | Sales |
| 129 | Bangalore | 2003-07-21 | 7350 | 2023-07-21 | Finance |
+-----+-----------+------------+--------+------------+-----------+
(o)
1.
Select distinct hobby from personal ;
Output
+-----------+
| hobby |
+-----------+
| Music |
| Sports |
| Writing |
| Gardening |
+-----------+
2.
Select avg(salary) from personal, job where Personal.Empno = Job.Sno and Area in ('Agra','Delhi') ;
Output
+-------------+
| AVG(SALARY) |
+-------------+
| 6650.0000 |
+-------------+
3.
Select count(distinct Native_place) from personal;
Output
+--------------------------------+
| COUNT(DISTINCT `NATIVE-PLACE`) |
+--------------------------------+
| 4|
+--------------------------------+
4.
Select name, max(salary)
from Personal, Job where Personal.Empno = Job.Sno ;
Output
+------+-------------+
| name | max(salary) |
+------+-------------+
| Amit | 8500 |
+------+-------------+
Explanation
The given query retrieves the maximum salary from the 'Job' table and pairs it with the corresponding
employee name from the 'Personal' table based on the matching Empno and Sno values. However,
including a non-group field like 'name' in the select-list means it will return the value from the first
record of the group for the 'name' field. Therefore, 'Amit' is the first record in the 'Personal' table,
the query returns 'Amit' as the value for the 'name' field.
(p)
INSERT INTO Personal (Empno, Name, Dobirth, `Native-place`, Hobby)
VALUES (130, 'Amruta', '1990-05-15', 'Chennai', 'Music');
Output
select * from personal;
+-------+--------+------------+--------------+-----------+
| empno | name | dobirth | native-place | hobby |
+-------+--------+------------+--------------+-----------+
| 123 | Amit | 1965-01-23 | Delhi | Music |
| 124 | Abhai | 1975-08-11 | Allahabad | Music |
| 125 | Vinod | 1977-04-04 | Delhi | Sports |
| 127 | Manoj | 1976-12-12 | Mumbai | Writing |
| 128 | Abhay | 1974-03-10 | Mumbai | Gardening |
| 129 | Ramesh | 1981-10-28 | Pune | Sports |
| 130 | Amruta | 1990-05-15 | Chennai | Music |
+-------+--------+------------+--------------+-----------+
(q)
ALTER TABLE Job
ADD COLUMN Email VARCHAR(55);
(r)
insert into empdetails(empno, name, hobby)
select empno, name, hobby
from personal ;
Output
select * from empdetails ;
+-------+--------+-----------+
| Empno | Name | Hobby |
+-------+--------+-----------+
| 123 | Amit | Music |
| 124 | Abhai | Music |
| 125 | Vinod | Sports |
| 127 | Manoj | Writing |
| 128 | Abhay | Gardening |
| 129 | Ramesh | Sports |
| 130 | Amruta | Music |
+-------+--------+-----------+
(s)
CREATE VIEW LessThan15YearsView AS
SELECT * FROM Personal p, Job j
WHERE p.Empno = j.Sno AND
DATEDIFF(CURDATE(), J.App_date) < 15 * 365;
(t)
DELETE j
FROM Job j, Personal p
WHERE j.Sno = p.Empno AND p.Hobby <> 'Sports';
(u)
DROP TAbLE Personal;
Question 14a
With reference to the table below, answer the questions that follow :
Table : Employees
Empid Firstname Lastname Address City

010 Ravi Kumar Raj nagar GZB

105 Harry Waltor Gandhi nagar GZB

152 Sam Tones 33 Elm St. Paris

215 Sarah Ackerman 440 U.S. 110 Upton

244 Manila Sengupta 24 Friends street New Delhi

300 Robert Samuel 9 Fifth Cross Washington

335 Ritu Tondon Shastri Nagar GZB

400 Rachel Lee 121 Harrison St. New York

441 Peter Thompson 11 Red Road Paris


Table : EmpSalary
Empid Salary Benefits Designation

010 75000 15000 Manager

105 65000 15000 Manager

152 80000 25000 Director

215 75000 12500 Manager

244 50000 12000 Clerk

300 45000 10000 Clerk

335 40000 10000 Clerk

400 32000 7500 Salesman

441 28000 7500 Salesman


Write the SQL commands for the following using above tables :
(i) To show firstname, lastname, address and city of all employees living in Pairs.
(ii) To display the content of Employees table in descending order of Firstname.
(iii) To display the firstname, lastname and total salary of all managers from the tables Employes and
EmpSalary, where total salary is calculated as Salary + Benefits.
(iv) To display the maximum salary among managers and clerks from the table EmpSalary.
Answer
(i)
SELECT Firstname, Lastname, Address, City
FROM Employees
WHERE City = 'Paris';
Output
+-----------+----------+-------------+-------+
| Firstname | Lastname | Address | City |
+-----------+----------+-------------+-------+
| SAM | TONES | 33 ELM ST. | PARIS |
| PETER | THOMPSON | 11 RED ROAD | PARIS |
+-----------+----------+-------------+-------+
(ii)
SELECT *
FROM Employees
ORDER BY Firstname DESC;
Output
+-------+-----------+----------+-------------------+------------+
| empid | FIRSTNAME | LASTNAME | ADDRESS | CITY |
+-------+-----------+----------+-------------------+------------+
| 215 | SARAH | ACKERMAN | 440 U.S. 110 | UPTON |
| 152 | SAM | TONES | 33 ELM ST. | PARIS |
| 300 | ROBERT | SAMUEL | 9 FIFTH CROSS | WASHINGTON |
| 335 | RITU | TONDON | SHASTRI NAGAR | GZB |
| 10 | RAVI | KUMAR | RAJ NAGAR | GZB |
| 400 | RACHEL | LEE | 121 HARRISON ST. | NEW YORK |
| 441 | PETER | THOMPSON | 11 RED ROAD | PARIS |
| 244 | MANILA | SENGUPTA | 24 FRIENDS STREET | NEW DELHI |
| 105 | HARRY | WALTOR | GANDHI NAGAR | GZB |
+-------+-----------+----------+-------------------+------------+
(iii)
SELECT e.Firstname, e.Lastname,
(s.Salary + s.Benefits) AS TotalSalary
FROM Employees e, EmpSalary s
WHERE e.Empid = s.Empid AND s.Designation = 'Manager';
Output
+-----------+----------+-------------+
| Firstname | Lastname | TotalSalary |
+-----------+----------+-------------+
| RAVI | KUMAR | 90000 |
| HARRY | WALTOR | 80000 |
| SARAH | ACKERMAN | 87500 |
+-----------+----------+-------------+
(iv)
SELECT Designation, MAX(Salary)
FROM EmpSalary
WHERE Designation IN ('Manager', 'Clerk')
group by designation;
Output
+-------------+-------------+
| Designation | MAX(Salary) |
+-------------+-------------+
| MANAGER | 75000 |
| CLERK | 50000 |
+-------------+-------------+
Question 14b
With reference to the table below, answer the questions that follow :
Table : Employees
Empid Firstname Lastname Address City

010 Ravi Kumar Raj nagar GZB

105 Harry Waltor Gandhi nagar GZB

152 Sam Tones 33 Elm St. Paris

215 Sarah Ackerman 440 U.S. 110 Upton

244 Manila Sengupta 24 Friends street New Delhi

300 Robert Samuel 9 Fifth Cross Washington

335 Ritu Tondon Shastri Nagar GZB

400 Rachel Lee 121 Harrison St. New York

441 Peter Thompson 11 Red Road Paris


Table : EmpSalary
Empid Salary Benefits Designation

010 75000 15000 Manager

105 65000 15000 Manager

152 80000 25000 Director

215 75000 12500 Manager

244 50000 12000 Clerk

300 45000 10000 Clerk

335 40000 10000 Clerk

400 32000 7500 Salesman

441 28000 7500 Salesman


Give the Output of following SQL commands :
(i) Select firstname, Salary from Employees, Empsalary where Designation = 'Salesman' and
Employees.Empid = Empsalary.Empid ;
(ii) Select count(distinct designation) from EmpSalary ;
(iii) Select designation, sum(salary) from EmpSalary group by designation having count(*) > 2 ;
(iv) Select sum(Benefits) from EmpSalary where Designation = 'Clerk' ;
Answer
(i)
Output
+-----------+--------+
| FIRSTNAME | SALARY |
+-----------+--------+
| RACHEL | 32000 |
| PETER | 28000 |
+-----------+--------+
(ii)
Output
+-----------------------------+
| COUNT(DISTINCT DESIGNATION) |
+-----------------------------+
| 4|
+-----------------------------+
(iii)
Output
+-------------+-------------+
| DESIGNATION | SUM(SALARY) |
+-------------+-------------+
| MANAGER | 215000 |
| CLERK | 135000 |
+-------------+-------------+
(iv)
Output
+---------------+
| SUM(BENEFITS) |
+---------------+
| 32000 |
+---------------+
Question 15
Show the average salary for all departments with more than 3 people for a job.
Answer
SELECT job, AVG(Sal) AS AvgSalary
FROM Empl
GROUP BY job HAVING COUNT(*) > 3;
Output
+----------+-----------+
| job | AvgSalary |
+----------+-----------+
| CLERK | 1037.5 |
| SALESMAN | 1400 |
+----------+-----------+
Question 16
Display only the jobs with maximum salary greater than or equal to 3000.
Answer
SELECT Job
FROM Empl
GROUP BY Job HAVING MAX(Sal) >= 3000;
Output
+-----------+
| Job |
+-----------+
| PRESIDENT |
| ANALYST |
+-----------+
Question 17
Find out number of employees having "Manager" as Job.
Answer
SELECT COUNT(*) AS NumManagers
FROM EmpSalary
WHERE Designation = 'Manager';
Output
+-------------+
| NumManagers |
+-------------+
| 3|
+-------------+
Question 18
List the count of employees grouped by deptno. (table EMPL)
Answer
SELECT deptno, COUNT(*) AS employee_count
FROM EMPL
GROUP BY deptno;
Output
+--------+----------------+
| deptno | employee_count |
+--------+----------------+
| 20 | 5|
| 30 | 6|
| 10 | 3|
+--------+----------------+
Question 19
List the sum of employees' salaries grouped by department. (table EMPL)
Answer
SELECT deptno, SUM(sal) AS total_salary
FROM EMPL
GROUP BY deptno;
Output
+--------+--------------+
| deptno | total_salary |
+--------+--------------+
| 20 | 10885 |
| 30 | 9400 |
| 10 | 8750 |
+--------+--------------+
Question 20
List the maximum salary of employee grouped by their department number.
Answer
SELECT deptno, MAX(sal) AS max_salary
FROM EMPL
GROUP BY deptno;
Output
+--------+------------+
| deptno | max_salary |
+--------+------------+
| 20 | 3000 |
| 30 | 2850 |
| 10 | 5000 |
+--------+------------+
Question 21
Below are the customer and order tables :
Customers
customer id (PK)

first_name

last_name

email

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

email

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

email

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)

SALARYGRADE (Lowsal, Highsal, Grade)

DEPT (Deptno, DeptName, Location)


List the department names and the number of their employees.
Answer
SELECT d.DeptName AS Department_Name, COUNT(e.EMPNO) AS Number_of_Employees
FROM DEPT d, EMPL e
WHERE d.Deptno = e.DEPTNO
GROUP BY d.DeptName;
Question 25
Schemas of tables EMPL, Dept, SalaryGrade are being shown below :
EMPL (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)

SALARYGRADE (Lowsal, Highsal, Grade)

DEPT (Deptno, DeptName, Location)


List the employee names and the name of their departments.
Answer
SELECT e.ENAME AS Employee_Name, d.DeptName AS Department_Name
FROM EMPL e, DEPT d
WHERE e.DEPTNO = d.Deptno;
Chapter 16
Interface Python with MySQL
Type A: Short Answer Questions/Conceptual Questions
Question 1
What are the steps to connect to a database from within a Python application ?
Answer
The steps to connect to a database from within a Python application are as follows :
Step 1 : Start Python.
Step 2 : Import the packages required for database programming.
Step 3 : Open a connection.
Step 4 : Create a cursor instance.
Step 5 : Execute a query.
Step 6 : Extract data from result set.
Step 7 : Clean up the environment.
Question 2
Write code to connect to a MySQL database namely School and then fetch all those records from
table Student where grade is ' A' .
Answer
Table Student of MySQL database School
rollno name marks grade section project

101 RUHANII 76.8 A A PENDING

102 GEOGRE 71.2 B A SUBMITTED

103 SIMRAN 81.2 A B EVALUATED

104 ALI 61.2 B C ASSIGNED

105 KUSHAL 51.6 C C EVALUATED


rollno name marks grade section project

106 ARSIYA 91.6 A+ B SUBMITTED

107 RAUNAK 32.5 F B SUBMITTED


import mysql.connector as mysql

db_con = mysql.connect(
host = "localhost",
user = "root",
password = "tiger",
database = "School"
)

cursor = db_con.cursor()

cursor.execute("SELECT * FROM Student WHERE grade = 'A'")


student_records = cursor.fetchall()

for student in student_records:


print(student)

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

db_con = mysql.connector.connect(host = "localhost",


user = "root",
passwd = "lion",
database = "menagerie")
cursor = db_con.cursor()

cursor.execute("SELECT * FROM Pet")

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()

cursor.execute("SELECT * FROM event WHERE type = 'kennel'")

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

db_con = mysql.connector.connect(host = "localhost",


user = "root",
passwd = "fast",
database = "employeedb")
cursor = db_con.cursor()

search_criteria = input("Enter search criteria : ")


sql1 = "SELECT * FROM EMPL WHERE {}".format(search_criteria)
cursor.execute(sql1)

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)

You might also like