0% found this document useful (0 votes)
4 views

Database Systems-Lab Manual

The document is a lab manual for a Database Systems course at the National University of Modern Languages, focusing on teaching students SQL and database management concepts through hands-on labs. It includes various lab exercises covering topics such as SQL statements, data retrieval, table management, and constraints. The manual outlines objectives, theoretical descriptions, and tasks for each lab, providing a structured approach to learning database systems.

Uploaded by

muteebrehman1213
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)
4 views

Database Systems-Lab Manual

The document is a lab manual for a Database Systems course at the National University of Modern Languages, focusing on teaching students SQL and database management concepts through hands-on labs. It includes various lab exercises covering topics such as SQL statements, data retrieval, table management, and constraints. The manual outlines objectives, theoretical descriptions, and tasks for each lab, providing a structured approach to learning database systems.

Uploaded by

muteebrehman1213
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/ 64

LAB MANUAL

DATABASE SYSTEMS

DEPARTMENT OF SOFTWARE ENGINEERING


FACULTY OF ENGINEERING & COMPUTING
NATIONAL UNIVERSITY OF MODERN LANGUAGES
ISLAMABAD
BS (Software Engineering) 2025

Preface
This lab is about database management system. In this lab students will learn about Database from basic
and they will also learn about the concept and usage of queries to manage and maintain the database
using the SQL statements. In the lab SQL statements will be used to manage and maintain the database.
Students will get the knowledge regarding creating table and performing different operations on the
tables. The Theoretical Description is to familiarize students with SQL and to equip students with
hands-on experience of implementing SQL for managing the database management system. This lab
provides hands-on experience of implementing DBMS concepts using Structured Query Language,
which ultimately helps students to understand the basic concept and usage of DBMS and provides them
skills to manage and manipulate the database.

Tools/ Technologies
 Mysql OR SQL management studio

2
BS (Software Engineering) 2025

TABLE OF CONTENTS

Preface ....................................................................................................................................................... 2
Tools/ Technologies .................................................................................................................................. 2
LAB 1: Installation of Relational Database Management Systems ..................................................... 4
LAB 2: Retrieving Data Using the SQL SELECT Statement .............................................................. 3
LAB 3: Restricting using where clause and Sorting Data using order by clause ............................... 9
LAB 4 : Using DDL Statements to Create and Manage Tables ......................................................... 16
LAB 5 : Creating other schema objects like table level and column level constraints .................... 19
LAB 6: Using Single-Row Character Functions to Customize Output ............................................. 23
LAB 7: Using Single-Row Date Functions to Customize Output & Type conversion ..................... 30
LAB 8: Constructing ERD using VISIO or draw.io ........................................................................... 33
LAB 9: Constructing enhanced ERD using visio or draw.io ............................................................. 35
LAB 10: Aggregating data using SQL Aggregate functions and group functions ........................... 36
LAB 11: Use of joins for displaying data from multiple tables .......................................................... 43
LAB 12: Sub Queries and set operators ............................................................................................... 46
LAB 13: Normalization .......................................................................................................................... 54
Open Ended Lab (OEL) ........................................................................................................................ 55

3
BS (Software Engineering) 2025

LAB 1: Installation of Relational Database Management Systems


Objectives
● To discuss the role of relational database management studio
● To install MySQL or Oracle or Sql server
Theoretical description
1. Step 1: Go to mysql.com
2. Step 2:Go to downloads and select mysql community gpl downloads and select mysqlinstaller for
windows
3. Step 3:It will show you Generally Available (GA) Releases. Where we can see two different
installers, one is a web community installer which comes as a little file and another one is
MySQL installer community. Click the Download button on the second one (mysql-installer-
community)
4. Step 4 It will ask your MySQL credentials to download the .msi file. If you have your
credentials, you can log in or else if you wish to sign up now you can click on the green coloured
signup button.If you are not interested in login or sign up for now, you can directly go and click
on No thanks, just start my download option. It will download selected MySQL for you on
your local machine

5. Step 5:Go to downloads folder where you can see the mysql-installer- community file, right
click on that file and click Install option.

This window configures the installer, in the middle, it may ask you for permissions to
change your computer settings or firewall confirmation, you can accept and then it will take
a few seconds to configure the installer.

4
BS (Software Engineering) 2025

6. Step 6: Read the license agreement and accept the license terms.

7. Step 7:This window provides you to set up different types of MySQL installations. You can set
up Mysql in 5 different types as provided below. Now I am selecting the server only not I am a
developer so that I need all the products which help my development Theoretical Descriptions.
Click on Next.

5
BS (Software Engineering) 2025

8. Step 8:Based on your Windows configuration, it may prompt you like “One or more product requirements
have not been satisfied”. You can just click on YES.

9. Step 9: Click execute

10. Step 10:Upon successful execution of all required products, now the MySQL allows us to configure the
server settings. Click on Next to configure the server

6
BS (Software Engineering) 2025

11. Step 11:Select default setting

12. Step 12:Add password

13. Step 13:Select default setting

7
BS (Software Engineering) 2025

14. Step 14:Click on reconfigure

15. Step 15:Check named pipe and shared memory

16. Step 16

8
17. Step 17:Enter root password i.e password in my case and click check it which shows
green symbol andclick next

18. Step 18:Again select next


19. Step 19:Click on execute and than finish

20. Step 20:Now go back to mysql.com and select downloads and select mysql
community gpl downloads and select mysql work bench and click on download button
in below screen
BS (Software Engineering) 2025

21. Step 21: select complete

22. Step 22:Work bench is installed and screen shown is click on local instance and enter

your password
Lab Task
Q1.Observe the tool and explain all its findings in your own words with screebshots
Q2.Import any Mysql database and perform following tasks.Show output as well as give
reasoning
1. Expand the database from left side of workbench window and list down the catagories
of tables in the specific database
2. Click on any table of your choice to inspect table and show the schema attribute
names and other metadata
3. Choose the above mentioned table and navigate through the contents of database
tables
4. Observe multiple options in data view such as sorting
5. Observe errors warnings and messages within log pane

2
BS (Software Engineering) 2025

LAB 2: Retrieving Data Using the SQL SELECT Statement


Objectives
 To list the capabilities of SQL SELECT statements
 To execute a basic SELECT statement
Theoretical description
SQL KEYWORDS
Basic SELECT Statement

• SELECT identifies the columns to be displayed.


• FROM identifies the table containing those columns.
Selecting All Columns

Selecting Specific Columns

Writing SQL Statements


• SQL statements are not case-sensitive.

3
BS (Software Engineering) 2025

SQL statements can be entered on one or more lines.

• Keywords cannot be abbreviated or split across lines


.

Clauses are usually placed on separate lines


.

• Indents are used to enhance readability.

• In SQL*Plus, you are required to end each SQL statement with a semicolon (;).
Arithmetic Expressions
Create expressions with number and date data by using arithmetic operators.

Using Arithmetic Operators

4
BS (Software Engineering) 2025

SELECT first_name, last_name, salary, salary – 300 FROM


employees;

SELECT first_name, last_name, salary, salary * 2 FROM


employees;

SELECT first_name, last_name, salary, salary / 1000 FROM


employees;

Operator Precedence
• Multiplication and division take priority over addition and subtraction.
• Operators of the same priority are evaluated from left to right.
• Parentheses are used to force prioritized evaluation and to clarify statements

Defining a Column Alias


A column alias:
• Renames a column heading
• Is useful with calculations
• Immediately follows the column name (There can also be the optional AS keyword
between the column name and alias.)
5
BS (Software Engineering) 2025

• Requires double quotation marks if it contains spaces or special characters, or if it is case-


sensitive
Using Column Aliases

Concatenation Operator
A concatenation operator:
• Links columns or character strings to other columns
• Is represented by command concat
• Creates a resultant column that is a character expression

Duplicate Rows
The default display of queries is all rows, including duplicate rows.
SELECT department_id
FROM employees;

6
BS (Software Engineering) 2025

Displaying the Table Structure


• Use the DESCRIBE command to display the structure of a table.
• Or, select the table in the Connections tree and use the Columns tab to view
the table structure.

7
BS (Software Engineering) 2025

Using the DESCRIBE Command

Lab Task
Consider the database given to you and perform following tasks on it
Q1. Write an SQL query to display all records from city table
Q2. Write an SQL Query to display the following records. Give reasoning also that
which table would be used get the following records
 Name
 local name
 government form
 Head of state
 Capital
Q3. Describe the structure of country language table and city table and also explain in your
words about the output result
Q4. Consider country table and use arithmetic operators within SQL query to calculate 10 %
on population column
Q5 Consider any one table of database. Take at least any one appropriate scenario and apply
operator precedence. Also give reasoning
Q6. Consider country language table. Write SQL query to concatenate columns i.e. Country
code and language .Also use column alias to rename the concatenated column as country
details column

8
BS (Software Engineering) 2025

LAB 3: Restricting using where clause and Sorting Data using order by
clause

Objectives
• To limit the rows that are retrieved by a query
• To sort the rows that are retrieved by a query
• To use ampersand substitution to restrict and sort output at run time
Theoretical Description
LIMITING ROWS USING SELECTION

9
BS (Software Engineering) 2025

CHARACTER STRINGS AND DATES

OTHER COMPARISON OPERATORS

10
BS (Software Engineering) 2025

11
BS (Software Engineering) 2025

12
BS (Software Engineering) 2025

USING NOT OPERATOR

RULES OF PRECENDENCE

13
BS (Software Engineering) 2025

SORTING IN DESCENDING ORDER

SORTING BY COLUMN ALIAS

SORTING MULTIPLE COLUMNS

Lab Task
Consider the database given and perform following tasks
Q1. Write a Single Query to display local name and Gross National Product for Countries
who specifically are in range of 372.00,4834,11705,60,650) Or those Countries who’s Local
Name starts off with B

Q2. Write an SQL Query to display Population, Expected Population after


twenty years and Red Zone Areas with Population Exceeding 250,000.Also display
information in descending order

14
BS (Software Engineering) 2025

Q3 Select Name, Capital, Region and Independence Year from Country Table Where Year
Must be Equal to ‘1991’ and The Name Must be Start with ‘A’ and Capital Must be Less
Than 500.

Q4 Select Surface Area and Population from Country Table Where Population Must be Equal
to 500000 and Surface Area should Between 1000(lower) And 5000(Higher)

Q5.Write a single query which uses majority of concepts taught in lab 2 and lab 03

15
BS (Software Engineering) 2025

LAB 4 : Using DDL Statements to Create and Manage Tables

Objectives
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
• Create a simple table
• Explain how constraints are created at the time of table creation
• Describe how schema objects work
Theoretical description

16
BS (Software Engineering) 2025

17
BS (Software Engineering) 2025

Lab Task
Q1 Create tables of your project
Q2. Insert data that is 25 to 30 records in all tables in your project

18
BS (Software Engineering) 2025

LAB 5 : Creating other schema objects like table level and column level
constraints

Objectives
● Understand table level and column level constraints and their working

Theoretical Description
SQL Constraints
• Constraints are used to limit the type of data that can go into a table.
• MySQL constraints are statements that can be applied at the column level or table level to
specify rules for the data that can be entered into a column or data table

NOT NULL CONSTRAINT


❑ NOT NULL constraint is applied to a column, it ensures that the column will not
accept NULL values.
❑ A null value means that a particular field has been left empty, and values such as zero
or blank space do not come under Null values
❑ primary key column implicitly includes a not null constraint

19
BS (Software Engineering) 2025

UNIQUE KEY CONSTRAINT


❑ A unique key is a constraint in SQL which helps in uniquely identifying a record in
the data table.
❑ It is similar to the Primary key as both of them guarantees the uniqueness of a record.
❑ Unlike primary key, a unique key can accept NULL values, a unique Key can include
a NULL value but only one NULL value per column is allowed.

EXAMPLE OF UNIQUE CONSTRAINT TABLE LEVEL AND COLUMN LEVEL

PRIMARY KEY CONSTRAINT

20
BS (Software Engineering) 2025

21
BS (Software Engineering) 2025

CHECK CONSTRAINT COLUMN LEVEL AND TABLE LEVEL

Lab Task
Create a database named as Data definition Lab and create following table
Table name Attributes Constraints
Customer Customer_ID Customer_ID is a primary
Customer_Name key
Customer_Address Customer_Name cannot be
Customer_State null and its size is 35
chracters
The size of customer_address
is variable and is of 35
characters as well as it can be
null
Customer_dtate is fixed two
characters and cannot be Null
Sales_Order Order_Id Order_Id is a primary key
Order_Date For order_Date use date
Customer_ID datatype
Customer Id is a foreign key
Products Product_ID Product_ID is a primary key
Product_Name Product_name is unique and
Product_Line_ID contains 40 chracters
Product_line_id is always
greater than or equal to 10
and less than or equal to 100
so use constraint to check this
condition
Order_line Order_ID (order_id and product_id ) are
Product_ID primary keys
Order_id is a foreign key
Product_id is a foreign key
and cannot be null

Q2. Insert 15 to 20 records in the above mentioned tables

22
BS (Software Engineering) 2025

LAB 6: Using Single-Row Character Functions to Customize


Output
Objectives
To describe various types of functions available in SQL
To use character, number, and date functions in SELECT statements

Theoretical description
Single row functions are the one who work on single row and return one output per row.
For example, length and case conversion functions are single row functions. Single row
functions can be character functions, numeric functions, date functions, and
conversion functions. These functions require one or more input arguments and operate on
each row, thereby returning one output value for each row.Single row functions can be used
in SELECT statement, WHERE and ORDER BY clause.

23
BS (Software Engineering) 2025

24
BS (Software Engineering) 2025

Example of character manipulation functions


1. Substring function and instring function

25
BS (Software Engineering) 2025

2. Replace function

26
BS (Software Engineering) 2025

27
BS (Software Engineering) 2025

28
BS (Software Engineering) 2025

Lab Task
Consider database given to you and answer following questions
Q1.Write a single sql query to display employee first name, last name and job joined
together, similarly display length of employee email address, and the numeric position of
letter A in the employee last name, for all employees whose employee number is 1002 and
job is president

Q2. Write a query to display the last names of all customers who have the letter p in their first
name and the letter A at the 5th position in their last name.

Q3. Write a single query which covers all character manipulation functions such as substring
,instring, concat, upper case, trim,replace and lpad or rpad and should use where clause as
well as comparison operators

Q4.Format the credit limit column to be 15 character long ,left padded with Rs of only those
customers whose last name is king and their credit limit is greater than 10000 .Also label
column as credit balance

Q5. Consider order table and round off the price of only those orders whose order number is
10100

29
BS (Software Engineering) 2025

LAB 7: Using Single-Row Date Functions to Customize Output & Type


conversion

Objectives
• To describe various types of functions available in SQL
• To use character, number, and date functions in SELECT statements

Theoretical description
Date format functions
This function allows the developer to format the date anyway that they wish by specifying a
sequence of format strings. A string is composed of the percentage symbol '%' followed by a
letter that signifies how we wish to display the date. These are some of the more common
strings to use:

Syntax:
DATE_FORMAT(date, sequence)

Date format functions

String Displays Example


%d The numeric day of the month 01....10....17....24 etc
%D The day of the month with a 1st, 2nd, 3rd.... etc
suffix
%m The numeric month 01....04....08....11 etc
%M The Month name January....April....August etc
%b The Abbreviated Month Name Jan....Apr....Aug....Nov etc
%y Two digit year 98, 99, 00, 01, 02, 03 etc
%Y Four digit year 1998, 2000, 2002, 2003 etc
%W Weekday name Monday.... Wednesday....Friday etc
%a Abbreviated Weekday name Mon....Wed....Fri etc
%H Hour (24 hour clock) 07....11....16....23 etc
%h Hour (12 hour clock) 07....11....04....11 etc
%p AM or PM AM....PM
%i Minutes 01....16....36....49 etc
%s Seconds 01....16....36....49 etc
%c Month Numeric (0…12)
%e Day of month Numeric (0….31)
%f Microseconds
%r Time 12 hour hh:mm:ss followed by AM or PM

30
BS (Software Engineering) 2025

EXAMPLE

DATE EXTRACTION FUNCTIONS


As well as using DATE_FORMAT() there are other functions that allow we to extract
specific information about a date (year, month, day etc). These include:
Function Displays Example
DAYOFMONTH(date) The numeric day of the month 01....10....17....24 etc
DAYNAME(date) The Name of the day Monday.... Wednesday....
MONTH(date) The numeric month 01....04....08....11 etc
MONTHNAME(date) The Month name January....April....August etc
YEAR(date) Four digit year 1998, 2000, 2002, 2003 etc
HOUR(time) Hour (24 hour clock) 07....11....16....23 etc
MINUTE(time) Minutes 01....16....36....49 etc
SECOND(time) Seconds 01....16....36....49 etc
DAYOFYEAR(date) Numeric day of the year 1.....366

EXAMPLE 1 DAY NAME

31
BS (Software Engineering) 2025

EXAMPLE 2
CHANGING DATE VALUES

Lab Task
Q1.Consider order table and round off the price of only those orders whose
order number is 10100
Q2.Consider three major scenarios on classic model database in which
major data format and time functions are covered?
Q3. Explain following functions and also explain how sql queries are written for them
• Time difference()
• Time stamp()
• Sysdate()

32
BS (Software Engineering) 2025

LAB 8: Constructing ERD using VISIO or draw.io

Objectives
⮚ To learn about Entity Relationship Diagram (ERD).
⮚ To learn about the notations used in tools.
⮚ We will make an ER Diagram using draw.io

Theoretical description
Entity Relationship Diagram:
An entity–relationship model describes interrelated things of interest in a specific domain of
knowledge. A basic ER model is composed of entity types and specifies relationships that can
exist between entities. ER Diagrams are most often used to design or debug relational
databases in the fields of software engineering, business information systems, education and
research.

Notations Used in ERD:


These shapes are independent from other
entities, and are often called parent entities,
since they will often have weak entities that
1. Entity(strong) depend on them. They will also have a
primary key, distinguishing each occurrence
of the entity.

Weak entities depend on some other entity


type. They don't have primary keys, and
have no meaning in the diagram without
2. Entity(Weak) their parent entity.

Associative entities relate the instances of


several entity types. They also contain
attributes specific to the relationship
between those entity instances.
3. Associative entity

Attributes are characteristics of an entity, a


many-to-many relationship, or a one-to-one
4. Attributes relationship.

33
BS (Software Engineering) 2025

Relationships are associations between or


among entities.

5. Relationship

SmartDraw:
SmartDraw is a diagram tool used to make flowcharts, organization charts,
mind maps, project charts, and other business visuals. SmartDraw allows you to draw and
print architectural and engineering diagrams to scale. SmartDraw even provides an
AutoCAD-like annotation layer that automatically resizes to match a diagram.

ERD Diagram:

Lab Task
Q1 Create enhanced er diagram using crow feet notation chenn notation for following

An MDXCS computer supply is a wholesale company which buys computers from suppliers
and sells them to customers. MDXCS has a number of suppliers and each product is supplied
by on supplier only. However, suppliers may supply more than one product. MDXCS also
keeps record of suppliers who are not currently supplying any products. The company has
divided their operation into different geographical areas. Each storehouse is responsible for
each geographical area to deliver products to customers. Customers may be located in more
than one place and every storehouse has at least one customer. There are a number of
storehouses which hold stocks of products and these storehouses are assigned to deliver
orders to customers. Suppliers supply product to a particular storehouse and then
MDXCS stock in other depots. When a customer places an order, the company gives them a
unique order reference number. One order can be for different products. Customer can pay by
card or cash and orders are marked as delivered by entering a delivery date.
Note: Specify all the entities, relationships and their cardinalities

34
BS (Software Engineering) 2025

LAB 9: Constructing enhanced ERD using visio or draw.io


Objectives
• Identify enhanced erd notations
• Identify how to construct enhanced ERD
Lab Task
Q1. Create an enhanced entity relationship diagram for following .
Ali as a customer wants to purchase plot/plots in a housing scheme for investment. He can
buy plots of different sizes and categories like commercial, residential and farm house along
Marla details. On commercial plots tax payer ID details must be mentioned. System should
also keep the record of Down Payment and quarterly installments. Regional office
information with respect to cities should be kept. If regional office is removed then agent
information should be removed. Notifications regarding new plots/schemes should also be
shared with the registered and unregistered users.

Q2. Consider Learning management system and list down business rules and create an
enhanced entity relationship diagram for it

Note: Apply all Enhanced ERD concepts

35
BS (Software Engineering) 2025

LAB 10: Aggregating data using SQL Aggregate functions and group
functions
Objectives
• Identify aggregate functions
• Identify the available group functions
• Describe the use of group functions
• Group data by using the GROUP BY clause
• Include or exclude grouped rows by using the HAVING clause
Theoretical description
Group functions
⮚ They give the user the ability to answer business questions such as:
▪ What is the average salary of an employee in the company?
▪ What were the total salaries for a particular year?
▪ What are the maximum and minimum salaries in the Computer Department?
⮚ They perform a variety of actions such as counting all the rows in a table, averaging a
column’s data, and summing numeric data.
⮚ They can also search a table to find the highest “MAX” or lowest “MIN” values in a
column.

Example

U
sing
Mini
36
BS (Software Engineering) 2025

mum and Max Functions

Using count function

37
BS (Software Engineering) 2025

Example of group by clause

38
BS (Software Engineering) 2025

Illegal queries using group by functions

39
BS (Software Engineering) 2025

40
BS (Software Engineering) 2025

Lab Task
Q1 .Create following table with all these records and apply all types of
aggregate functions you have learned so far on the appropriate data from
all the columns in below mentioned table and show the SQL query and the
resultant output also

41
BS (Software Engineering) 2025

Q2. Create following table

42
BS (Software Engineering) 2025

LAB 11: Use of joins for displaying data from multiple tables
Objectives
• Retrieve data from different tables
Theoretical Description
Create different tables applying referential integrity constraints. Use foreign keys for integrity
constraints and then apply different joins to overserve the retrieved data.
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.

Syntax:
⮚ SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name =
table2.column_name;
JOIN and INNER JOIN are same in MySQL:
⮚ SELECT column_name(s) FROM table1 INNER JOIN table2 ON
table1.column_name = table2.column_name;
Tables:

Example:
43
BS (Software Engineering) 2025

1. Now, we create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:
mysql> select STUDENT.sname,COURSE.coursename from STUDENT JOIN
COURSE ON STUDENT.sid=COURSE.sid;

The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are records in the "STUDENT" table that do not have matches
in "COURSE", these will not be shown.

2. Now, we create the following SQL statement (that contains an INNER JOIN), that selects
all records that have matching values in both tables:
mysql> select * from STUDENT JOIN COURSE ON STUDENT.sid=COURSE.sid;

3. JOIN and INNER JOIN are same in MySQL:


mysql> select * from STUDENT INNER JOIN COURSE ON
STUDENT.sid=COURSE.sid;

JOIN Three Tables:


mysql> select * from STUDENT join COURSE ON STUDENT.sid=COURSE.sid join
teacher on COURSE.tid=TEACHER.tid;
44
BS (Software Engineering) 2025

mysql> select STUDENT.sname,COURSE.coursename,TEACHER.name from


STUDENT join COURSE ON STUDENT.sid=COURSE.sid join teacher on
COURSE.tid=TEACHER.tid;

4. INNER JOIN with where clause:


mysql> select STUDENT.sname,COURSE.coursename from STUDENT inner join
COURSE ON STUDENT.sid=COURSE.sid where student.sid>2;

Lab Task
Q1. Consider your project and apply joins on two tables as well as multiple tables

45
BS (Software Engineering) 2025

LAB 12: Sub Queries and set operators


Objectives
• Learn different ways to extract data using sub queries
• Learn Nesting of subqueries
• Learn SET Operators (UNION, UNION ALL, INTERSECT, & EXCEPT) in MySQL.
• Implement SET operations examples.

Theoretical Description
Subquery Syntax :

● The subquery (inner query) executes once before the main query (outer query)
executes.
● The main query (outer query) use the subquery result.

MySQL Subquery Example:

Using a subquery, list the name of the employees, paid more than 'Alexander' from
emp_details .

There are some guidelines to consider when using subqueries :


- A subquery must be enclosed in parentheses.
- Use single-row operators with single-row subqueries, and use multiple-row operators with
multiple-row subqueries.
- If a subquery (inner query) returns a null value to the outer query, the outer query will not
return any rows when using certain comparison operators in a WHERE clause.

MySQL Subqueries: Using Comparisons

A subquery can be used before or after any of the comparison operators. The subquery can
return at most one value. The value can be the result of an arithmetic expression or a column
function. SQL then compares the value that results from the subquery with the value on the
other side of the comparison operator. You can use the following comparison operators:

46
BS (Software Engineering) 2025

Operator Description
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
!= Not equal to
<> Not equal to
<=> NULL-safe equal to operator
For example, suppose you want to find the employee id, first_name, last_name, and salaries
for employees whose average salary is higher than the average salary throughout the
company.

MySQL Subqueries with ALL, ANY, IN, or SOME

Example: MySQL Subquery, ALL operator

The following query selects the department with the highest average salary. The subquery
finds the average salary for each department, and then the main query selects the department
with the highest average salary.

mysql> SELECT department_id, AVG(SALARY)


FROM EMPLOYEES GROUP BY department_id
HAVING AVG(SALARY)>=ALL
(SELECT AVG(SALARY) FROM EMPLOYEES GROUP BY department_id);
+---------------+--------------+
| department_id | AVG(SALARY) |
+---------------+--------------+
| 90 | 19333.333333 |
+---------------+--------------+
1 row in set (0.00 sec)

Note: Here we have used ALL keyword for this subquery as the department selected by the
query must have an average salary greater than or equal to all the average salaries of the other
departments.

47
BS (Software Engineering) 2025

The following query selects any employee who works in the location 1800. The subquery
finds the department id in the 1800 location, and then the main query selects the employees
who work in any of these departments.

mysql> SELECT first_name, last_name,department_id


FROM employees WHERE department_id= ANY
(SELECT DEPARTMENT_ID FROM departments WHERE location_id=1800);
+------------+-----------+---------------+
| first_name | last_name | department_id |
+------------+-----------+---------------+
| Michael | Hartstein | 20 |
| Pat | Fay | 20 |
+------------+-----------+---------------+
2 rows in set (0.00 sec)
MySQL Row Subqueries

A row subquery is a subquery that returns a single row and more than one column value. You
can use = , >, <, >=, <=, <>, !=, <=> comparison operators. See the following examples:

Example: MySQL Row Subqueries

In the following examples, queries shows differentr result according to above conditions :

mysql> SELECT first_name


FROM employees
WHERE ROW(department_id, manager_id) = (SELECT department_id, manager_id FROM
departments WHERE location_id = 1800);
+------------+
| first_name |
+------------+
| Pat |
+------------+
1 row in set (0.00 sec)

The SET Operators in MySQL are basically used to combine the result of more than 1 select
statement and return the output as a single result set. In SQL, 4 types of set operators are.
They are as follows:
1. UNION: It is used to combine two or more result sets into a single set, without
duplicates.
2. UNION ALL: It is used to combine two or more result sets into a single set,
including duplicates.
3. INTERSECT: It is used to combine two result sets and returns the data which are
common in both the result set.
4. EXCEPT: It is used to combine two result sets and returns the data from the first
result set which is not present in the second result set.

48
BS (Software Engineering) 2025

We are going to use the following EmployeeUK and EmployeeUSA tables to understand the
SET Operators in MySQL.

UNION Operator in MySQL


The UNION operator is used to combine the result set of two or more SELECT statements
into a single result set by removing the duplicate records. That means the UNION Operator
selects only the distinct values. Following is the Syntax to use UNION Operator in MySQL.

MySQL UNION Operator Example:


The following query combines two select statements using the UNION operator. In our
example, both the EmployeeUK and EmployeeUSA tables having seven records.
SELECT FirstName, LastName, Gender, Department FROM EmployeeUK
UNION
SELECT FirstName, LastName, Gender, Department FROM EmployeeUSA;
Once you execute the above query, you will get the following result set. Please observe, here
we don’t have any duplicate data. Here, in the result set, we got a total of 11 rows out of 14
rows. This is because 3 rows are present in both the result set.

UNION ALL Operator in MySQL

49
BS (Software Engineering) 2025

The UNION ALL operator is used to combine the result set of two or more SELECT
statements into a single result including the duplicate values. Following is the Syntax to use
UNION ALL Operator in MySQL.

MySQL UNION ALL Operator Example:


The following query combines two select statements using the UNION ALL operator
SELECT FirstName, LastName, Gender, Department FROM EmployeeUK
UNION ALL
SELECT FirstName, LastName, Gender, Department FROM EmployeeUSA;
Once you execute the above query, you will get the following result set. Please observe, here
we got all the 14 rows in the result set.

Differences between UNION and UNION ALL Operator in MySQL


From the output, it is very clear to us that UNION Operator removes duplicate rows
whereas UNION ALL operator does not remove the duplicate rows. When we use a UNION
operator, in order to remove the duplicate rows from the result set, it has to do a distinct
operation which is time-consuming. For this reason, UNION ALL is much faster than
UNION Operator in MySQL.
UNION/UNION ALL with ORDER BY Clause in MySQL
The UNION/UNION ALL Operator can be used with the ORDER BY clause to sort the
result returned from the query. Suppose we want to sort the employees by First Name column
values. ORDER BY clause should be part of the last select statement. The SQL statement
will be:
SELECT FirstName, LastName, Gender, Department FROM EmployeeUK
UNION
SELECT FirstName, LastName, Gender, Department FROM EmployeeUSA
ORDER BY FirstName;
Now execute the query and you should get the following output.

50
BS (Software Engineering) 2025

Here you can see the employees are sorted according to their FirstName column values.
MySQL EXCEPT Operator:
The EXCEPT operator is used to combine two tables or two result sets and will return rows
from the first select statement that are not present in the second select statement. Following is
the syntax of EXCEPT Operator.

But, the EXCEPT Operator is not supported by MYSQL. We can achieve the EXCEPT
Operator functionality in MySQL using the following ways.
Using NOT IN Operator to achieve EXCEPT functionality:
Here, we are checking the FirstName column value only. Following is the SQL Query using
the NOT IN Operator which returns the employees from the first EmployeeUK table that are
not present in the EmployeeUSA table.
SELECT * FROM EmployeeUK
WHERE FirstName NOT IN (SELECT FirstName FROM EmployeeUSA);
Once you execute the above query, you will get the following result set.

51
BS (Software Engineering) 2025

Using Join to achieve EXCEPT functionality in MySQL:


We can use LEFT JOIN to achieve the functionality of EXCEPT Operator. Here, the join
clause needs to contain all 4 columns FirstName, LastName, Gender, and Department. The
where clause picks null values in EmployeeId in EmployeeUSA, which limits to rows that
exist in EmployeeUK only.
SELECT t1.* FROM EmployeeUK AS t1
LEFT JOIN EmployeeUSA AS t2 ON
t1.FirstName=t2.FirstName
AND t1.LastName=t2.LastName
AND t1.Gender=t2.Gender
AND t1.Department=t2.Department
WHERE t2.EmployeeId IS NULL;
Once you execute the above join query, you will get the following result set.

INTERSECT Operator in MySQL


The INTERSECT operator is used to combine two result sets and returns the data which are
common in both the result set. Following is the syntax of INTERSECT operator.

But the INTERSECT Operator is not supported by MYSQL. We can achieve the
INTERSECT Operator functionality in MySQL using the following ways.
Using IN Operator to achieve INTERSECT functionality:
Here, we are checking the FirstName column value only. Following is the SQL Query using
the IN Operator which returns the common employees i.e. the employees which are present in
both t EmployeeUK and EmployeeUSA tables. Here, we are checking common based on the
First Name column value.
SELECT * FROM EmployeeUK
WHERE FirstName IN (SELECT FirstName FROM EmployeeUSA);
Once you execute the above query, you will get the following result set.

Using Join to achieve INTERSECT functionality in MySQL:


We can use INNER JOIN to achieve the functionality of INTERSECT Operator. Here, the
join clause needs to contain all 4 columns FirstName, LastName, Gender, and Department.
52
BS (Software Engineering) 2025

SELECT t1.* FROM EmployeeUK AS t1


INNER JOIN EmployeeUSA AS t2 ON
t1.FirstName=t2.FirstName
AND t1.LastName=t2.LastName
AND t1.Gender=t2.Gender
AND t1.Department=t2.Department;
Once you execute the above join query, you will get the following result set.

Lab Task
Q1 Practice union, union all, intersect and except on your project
Q2. Consider your project and write multiple scenarios to apply subqueries

53
BS (Software Engineering) 2025

LAB 13: Normalization

Objectives
 The students would apply 1NF 2NF 3NF normalization and denormalization on the
projects assigned to them
Theoretical description
Normalization is a systematic approach to organize data in a database to eliminate
redundancy, avoid anomalies and ensure data consistency. The process involves breaking
down large tables into smaller, well-structured ones and defining relationships between them.
This not only reduces the chances of storing duplicate data but also improves the overall
efficiency of the database. Normalization consists of following forms

 A relation in BCNF is also in 3NF , a relation in 3NF is also in 2NF and a relation in 2NF is also
in 1NF.
 A relation in BCNF is considered fully normalized.

Lab Task
Students will apply normalization on their projects

54
BS (Software Engineering) 2025

Open Ended Lab (OEL)

Course: Database Systems Total Marks: 15

OEL Title: Building a Library Management System

OEL Level: Level 1

Objectives:
To guide students through creating a library database system using predefined tables and
SQL queries while encouraging them to generate their own outputs and analyze results.
 Hands-on experience in implementing a database structure.
 Writing SQL queries to fulfill functional requirements.
 Understanding how to analyze and present results from database queries.

Background Information:
Libraries require efficient database systems to store and retrieve information about books,
users, and borrowing activities. This lab focuses on implementing a library management
system based on predefined requirements, with the freedom to interpret and present results
independently.

Problem:
Design a library management system that meets the following predefined specifications:

1. Books: Stores book details (e.g., BookID, Title, Author, PublicationYear, and Genre).

2. Users: Stores user details (e.g., UserID, Name, MembershipDate, and ContactInfo).

3. Transactions: Tracks borrowing activities (TransactionID, UserID, BookID,


BorrowDate, ReturnDate, and FineAmount).

Requirements:
1. Students must create three predefined tables
2. Students must populate tables with at least 10 entries per table. Sample data can be
based on the structure provided below but should be generated by the students:

 Books: Details like titles, authors, and genres.


 Users: Fictional user details.

55
BS (Software Engineering) 2025

 Transactions: Borrowing and returning records.

3. Students must write and execute SQL queries for the following tasks:

 List all available books in the library.


 Identify overdue books (assume the return due date is 7 days after borrowing).
 Retrieve the borrowing history of a specific user (student’s choice).
 Calculate the total fines generated in the library.

56

You might also like