0% found this document useful (0 votes)
37 views69 pages

Database Systems-SEDB-227-Lab Manual

The document is a lab manual for a course on Database Systems at the National University of Modern Languages, Islamabad. It covers various aspects of database management, including SQL statements, installation of relational database management systems, and practical lab tasks to enhance students' understanding of database concepts. The manual includes detailed instructions for multiple labs focusing on SQL queries, data retrieval, and manipulation using different SQL functions and operators.
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)
37 views69 pages

Database Systems-SEDB-227-Lab Manual

The document is a lab manual for a course on Database Systems at the National University of Modern Languages, Islamabad. It covers various aspects of database management, including SQL statements, installation of relational database management systems, and practical lab tasks to enhance students' understanding of database concepts. The manual includes detailed instructions for multiple labs focusing on SQL queries, data retrieval, and manipulation using different SQL functions and operators.
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/ 69

LAB MANUAL

DATABASE SYSTEMS
SEDB-227

DEPARTMENT OF SOFTWARE ENGINEERING


FACULTY OF ENGINEERING & COMPUTING
NATIONAL UNIVERSITY OF MODERN LANGUAGES
ISLAMABAD
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 Oracle OR SQL management studio

2
TABLE OF CONTENTS

Preface ....................................................................................................................................................... 2
Tools/ Technologies .................................................................................................................................. 2
LAB 01: Installation of Relational Database Management Systems ................................................... 4
LAB 02: Retrieving Data Using the SQL SELECT Statement ............................................................ 4
LAB 03: Restricting using where clause and Sorting Data using order by clause ........................... 10
LAB 4: Using Single-Row Character Functions to Customize Output ........................................ 19
LAB 05: Using Single-Row Date Functions to Customize Output & Type conversion ................... 26
LAB 06: Constructing ERD using VISIO or draw.io ......................................................................... 30
LAB 07 : Using DDL Statements to Create and Manage Tables ....................................................... 32
LAB 08 : Creating other schema objects like table level and column level constraints .................. 35
LAB 09: Aggregating data using SQL Aggregate functions and group functions ........................... 40
LAB 10: Constructing enhanced ERD using visio or draw.io ........................................................... 47
LAB 11: Use of joins for displaying data from multiple tables .......................................................... 48
LAB 12: Sub Queries ............................................................................................................................. 51
LAB 13: Set Operations in MySQL ...................................................................................................... 55
LAB 14: Normalization.......................................................................................................................... 60
LAB 15: SQL project evaluation lab .................................................................................................... 61

3
LAB 01: 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 thesecond 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 thegreen coloured signup button.If
you are not interested in login or sign up for now, you can directly go and clickon 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
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
8. Step 8:Based on your Windows configuration, it may prompt you like “One or moreproduct 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 usto configure the
server settings. Click on Next to configure the server

6
11. Step 11:Select default setting

12. Step 12:Add password

13. Step 13:Select default setting

7
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


BS (Software Engineering) 2023

20. Step 20:Now go back to mysql.com and select downloads and select mysql
community gpl downloadsand select mysql work bench and click on download button
in below screen

21. Step 21: select complete

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

2
BS (Software Engineering) 2023

Lab Task

3
BS (Software Engineering) 2023

LAB 02: 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.

4
BS (Software Engineering) 2023

• SSQL 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

5
BS (Software Engineering) 2023

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

3*2+10=16, 3*(2+10)=36

Defining a Column Alias


A column alias:
• Renames a column heading
• Is useful with calculations

6
BS (Software Engineering) 2023

• Immediately follows the column name (There can also be the optional AS keyword
between the column name and alias.)
• 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;

7
BS (Software Engineering) 2023

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.

8
BS (Software Engineering) 2023

Using the DESCRIBE Command

Lab Task
Consider the database named as world. mySQL 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.
(a) Consider country table and use arithmetic operators within SQL query to calculate 10 %
on population column
(b). Consider any one table of database. Take at least any one appropriate scenario and apply
operator precedence. Also give reasoning

Q5. 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

9
BS (Software Engineering) 2023

LAB 03: 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

10
BS (Software Engineering) 2023

11
BS (Software Engineering) 2023

OTHER COMPARISON OPERATORS

12
BS (Software Engineering) 2023

13
BS (Software Engineering) 2023

Using Null operator

14
BS (Software Engineering) 2023

15
BS (Software Engineering) 2023

RULES OF PRECENDENCE

16
BS (Software Engineering) 2023

SORTING IN DESCENDING ORDER

SORTING BY COLUMN ALIAS

SORTING MULTIPLE COLUMNS

17
BS (Software Engineering) 2023

Lab Task
Consider the database given to you such as world.sql 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

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

18
BS (Software Engineering) 2023

LAB 4: 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
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.

19
BS (Software Engineering) 2023

20
BS (Software Engineering) 2023

21
BS (Software Engineering) 2023

22
BS (Software Engineering) 2023

23
BS (Software Engineering) 2023

24
BS (Software Engineering) 2023

Lab Task
Consider database given to you i.e classic models’ 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

25
BS (Software Engineering) 2023

LAB 05: 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 01....10....17....24 etc
month
%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 Jan....Apr....Aug....Nov etc
Name
%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

26
BS (Software Engineering) 2023

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


27
BS (Software Engineering) 2023

EXAMPLE 2
CHANGING DATE VALUES

28
BS (Software Engineering) 2023

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

29
BS (Software Engineering) 2023

LAB 06: 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 SmartDRAW.

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 their
2. Entity(Weak) 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.

30
BS (Software Engineering) 2023

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 erd 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

31
BS (Software Engineering) 2023

LAB 07 : 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

32
BS (Software Engineering) 2023

33
BS (Software Engineering) 2023

Lab Task
Q1 Create tables of your project
Q2. Insert data that is 30 to 40 records in all tables in your project
34
BS (Software Engineering) 2023

LAB 08 : 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

35
BS (Software Engineering) 2023

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

36
BS (Software Engineering) 2023

PRIMARY KEY CONSTRAINT

37
BS (Software Engineering) 2023

CHECK CONSTRAINT COLUMN LEVEL AND TABLE LEVEL

38
BS (Software Engineering) 2023

Lab Task

Q2.

39
BS (Software Engineering) 2023

LAB 09: 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.

40
BS (Software Engineering) 2023

Example

Using Minimum and Max Functions

Using count function

41
BS (Software Engineering) 2023

42
BS (Software Engineering) 2023

Example of group by clause

Illegal queries using group by functions

43
BS (Software Engineering) 2023

44
BS (Software Engineering) 2023

45
BS (Software Engineering) 2023

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

Q2. Create following table

46
BS (Software Engineering) 2023

LAB 10: 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

47
BS (Software Engineering) 2023

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:

48
BS (Software Engineering) 2023

Example:
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;

49
BS (Software Engineering) 2023

JOIN Three Tables:


mysql> select * from STUDENT join COURSE ON STUDENT.sid=COURSE.sid join
teacher on COURSE.tid=TEACHER.tid;

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

50
BS (Software Engineering) 2023

LAB 12: Sub Queries


Objectives
• Learn different ways to extract data using sub queries
• Learn Nesting of subqueries
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 .

mysql> SELECT first_name,last_name, salary FROM emp_details


WHERE salary >(SELECT salary FROM emp_details
WHERE first_name='Alexander');
+------------+-----------+----------+
| first_name | last_name | salary |
+------------+-----------+----------+
| Steven | King | 24000.00 |
| Neena | Kochhar | 17000.00 |
| Lex | De Haan | 17000.00 |
| RABI | CHANDRA | 15000.00 |
| Ana | King | 17000.00 |
+------------+-----------+----------+
5 rows in set (0.00 sec)
Subqueries: Guidelines

51
BS (Software Engineering) 2023

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:
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> SELECT employee_id,first_name,last_name,salary


FROM employees WHERE salary >
(SELECT AVG(SALARY) FROM employees);
+-------------+-------------+------------+----------+
| employee_id | first_name | last_name | salary |
+-------------+-------------+------------+----------+
| 100 | Steven | King | 24000.00 |
| 101 | Neena | Kochhar | 17000.00 |
| 102 | Lex | De Haan | 17000.00 |
| 103 | Alexander | Hunold | 9000.00 |

52
BS (Software Engineering) 2023

| 108 | Nancy | Greenberg | 12000.00 |


| 109 | Daniel | Faviet | 9000.00 |
| 120 | Matthew | Weiss | 8000.00 |
| 121 | Adam | Fripp | 8200.00 |
| 122 | Payam | Kaufling | 7900.00 |
|- - - - - - - - - - - - - - - - - - - - - - - - - -|
|- - - - - - - - - - - - - - - - - - - - - - - - - -|
+-------------+-------------+------------+----------+
51 rows in set (0.00 sec)
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.

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 |
+------------+-----------+---------------+
53
BS (Software Engineering) 2023

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)

Lab Task
Q1. Consider your project and write multiple scenarios to apply subqueries

54
BS (Software Engineering) 2023

LAB 13: Set Operations in MySQL


Objectives
• Learn SET Operators (UNION, UNION ALL, INTERSECT, & EXCEPT) in MySQL.
• Implement SET operations examples.
Theoretical Description
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.

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;

55
BS (Software Engineering) 2023

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


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.

56
BS (Software Engineering) 2023

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.

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.

57
BS (Software Engineering) 2023

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.

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.

58
BS (Software Engineering) 2023

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.
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

59
BS (Software Engineering) 2023

LAB 14: Normalization


Objectives
• The students would apply 1NF 2NF 3NF normalization and denormalization on the
projects assigned to them
Lab Task
Students will present their projects

60
BS (Software Engineering) 2023

LAB 15: SQL project evaluation lab


Objectives
This lab is based on project evaluation, intended to take viva of students regarding
their project i.e., a database design, implementation and use of CRUD operations if
used.
Lab Task
Students will present their projects and answer the questions asked by students and
teachers.

61

You might also like