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

DB Lab Manuals

Lab Manual for the Subject of Database Management System

Uploaded by

Bakht Khilji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

DB Lab Manuals

Lab Manual for the Subject of Database Management System

Uploaded by

Bakht Khilji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 87

Computer Laboratory Manuals

CS-220 Database Systems

DEPARTMENT OF COMPUTER SCIENCE


NUST Balochistan Campus, Quetta
National University of Sciences and Technology
www.nbc.nust.edu.pk
INTRODUCTION
The objective of this lab manual is to facilitate the students of Computer Science in studying,
understanding, and equip students with the knowledge and skills necessary to design, create,
manage, and optimize databases effectively and efficiently. Pre-requisite of this course is CS-101 or
Equivalent. The lab introduces MySQL as language to design and develop real world database
systems. Students’ understanding of the subject and their knowledge of database problems will be
evaluated by several Lab exercises & Assignments. One midterm practice session will further help to
assess the understanding of students and accordingly shape the course covering. Finally, their
overall performance is examined by the final lab exam. There will be one course project which will
be carried out in groups of three students. Each group will submit its final project before the final lab
session.

FEATURES
To ensure a successful experience for instructors and students alike, these lab manuals includes the
following features:

 Lab Objectives: Every lab has a brief description with examples and a list of learning
objectives.

 Materials Required: Every lab includes information on hardware, software, and other
materials you will need to complete the lab.

 Blanks Exercise: Every has the fill in the blanks exercise to ensure that you have read the
document completely.

 Tasks Sections: Every lab has 3-5 tasks to complete and paste the code below the questions
and submit in google classroom.

 Step-by-Step Instructions: Every lab provides steps to enhance technical proficiency; some
labs include Critical Thinking exercises to challenge students.

 Completion Times: Every lab has an estimated completion time so that you can plan your
activities more accurately.

 Review Questions: Some labs include.

EQUIPMENTS REQUIRED
 Workstation (PCs)
 MySQL Workbench and MS Access (Software)

PREPARED BY
Lab manual is revised by Bakht Muhammad under the supervision of Head of Research Department
Dr. Adnan Idris in year 2022-2023.

2|Page
COURSE OUTLINE
CS-220 Database Systems
Course Code: CS-220 Semester: 3rd
Credit Hours: 3+1 Prerequisite Codes: CS-101 or Equivalent
Instructor: Dr. Adnan Idris Class: BS CS-5AB
Office: A-104 VoIP: 2183
Lecture Days: E-mail: [email protected]
Classroom: Consulting Hours: By Appointment
Lab Engineer: Bakht Muhammad Lab Engineer Email: [email protected]
Knowledge Group: Data Management Updates on LMS: Daily basis

Course Description:
Databases are at the heart of modern software systems. They are used to store large amounts of
data for efficient update and retrieval. The purpose of this course is to introduce the design and
use of database systems.
Course Objectives:
The course objective is that its successful completion should enable students to engineer
database system and handle practical problems in modeling and implementation of real-world
data repositories.

Course Learning Outcomes (CLOs):


At the end of the course the students will be able to: PLO BT Level*
1. Develop a database schema that incorporates keys and 3 C-3
integrity constraints.
2. Formulate SQL queries to retrieve information from a 9 C-5
relational database.
3. Design a relational schema using the entity relationship 2 C-5
model.
4. Apply normalization to relations. 10 C-4

* BT= Bloom’s Taxonomy, C=Cognitive domain, P=Psychomotor domain, A=


Affective domain

Mapping of CLOs to Program Learning Outcomes

CLO1 CLO2 CLO3 CLO4 Emphasis


PLOs/CLOs Level
PLO 1 (Computing Knowledge)
PLO 2 (Problem and Requirement Analysis) X
PLO 3 (Design, Implementation and X
Evaluation of Solutions)
PLO 4 (Individual and Teamwork)
PLO 5 (Professional and ethical
Responsibility)
PLO 6 (Communication)
PLO 7 (Local and Global Computing Impact
Analysis)
PLO 8 (Lifelong Learning)
PLO 9 (Modern tool usage) X
PLO 10 (Design Choices and Tradeoffs X

3|Page
Analysis)
PLO 11 (Adherence to Design and
Development Principles)
Mapping of CLOs to Program Learning Outcomes

Mapping of CLOs to Assessment Modules and Weightages (In accordance with NUST statutes)
To be filled in at the end of the course.
CLO1 CLO2 CLO3 CLO4 CLO5
Assessments/CLOs
Theory: 75%
Quizzes: 10%
Assignments: 10%
OHT-1: 20%
OHT-2: 20%
End Semester Exam: 40%
Labs: 25%
Lab Tasks: 60%
Semester Project: 40%
Total: 100 %

References / Books:
Textbook: 1. R. Elmasri, S.B. Navathe (2016): Fundamentals of Database Systems, 7/E, Addison-
Wesley
Reference 1. J. A. Hoffer, V. Ramesh, and H. Topi (2013): Modern Database Management 11/E,
Books: Pearson
2. Silberschatz, Korth and Sudarshan (2010): Database System Concepts 6/E,
McGraw-Hill

4|Page
Table of Contents
LAB 1: LESSON SET 01 7
INTRODUCTION TO DATABSE SYSTEM AND AWARNESS WITH ACCESS 7
Pre-Lab Reading Assignment 8
Pre-Lab Writing Assignment 9
Lab Tasks 14
LAB 2: LESSON SET 02 15
TOOLS FOR DATABASE SYSTEM AND THEIR INSTALLATION 15
Pre-Lab Reading Assignment 16
Pre-Lab Writing Assignment 18
Lab Tasks 21
LAB 3: LESSON SET 03 22
INTRODUCTION TO SQL CONSTRAINTS AND WHY WE ARE USING IT 22
Pre-Lab Reading Assignment 23
Pre-Lab Writing Assignment 26
Lab Tasks 27
LAB 4: LESSON SET 04 28
INTRODUCTION TO BOOLEAN LOGIC AND BETWEEN OPERATOR SYNTAX 28
Pre-Lab Reading Assignment 29
Pre-Lab Writing Assignment 31
Lab Tasks 32
LAB 5: LESSON SET 05 33
INTRODUCTION TO WILDCARDS, REGULAR EXPRESSIONS ORDER BY, DISTINCT AND IS NULL OPERATOR 33
Pre-Lab Reading Assignment 36
Pre-Lab Writing Assignment 37
Lab Tasks 38
LAB 6: LESSON SET 06 38
INTRODUCTION TO LIMIT & OFFSET, AGGREGATE FUNCTIONS 38
Pre-Lab Reading Assignment 39
Pre-Lab Writing Assignment 41
Lab Tasks 42
LAB 7: LESSON SET 07 43
INTRODUCTION TO PRIMARY KEY AND FOREIGN KEY, 43
Pre-Lab Reading Assignment 44
Pre-Lab Reading Assignment 47
Lab Tasks 48S
LAB 8: LESSON SET 08 49

5|Page
INTRODUCTION TO DIAGRAMS, WHY DFDS, ELEMENTS OF DFDS AND ERD 49
Pre-Lab Reading Assignment 50
Pre-Lab Writing Assignment 53
Lab Taks 54
LAB 9: LESSON SET 09 55
INNER, LEFT, RIGHT, CROSS AND MULTIPLE JOIN 55
Pre-Lab Reading Assignment 56
Pre-Lab Writing Assignment 59
Lab Tasks 60
LAB 10: LESSON SET 10 61
GROUP BY, HAVING, SUBQUERY WITH EXIST, UNION AND UNION ALL 61
Pre-Lab Reading Assignment 62
Pre-Lab Writing Assignments 64
Lab Tasks 65
LAB 11: LESSON SET 11 66
ENTITY RELATIONSHIP DIAGRAM66
Pre-Lab Reading Assignment 67
Lab Tasks 68
Master Solution: 70

6|Page
Introduction to Database system and
Lesson Set Tools for Database system and their Installation
1
Purpose 1. To get basic awareness of MS Access
2. To understand database system and why we are using it
3. To learn the basics of an editor and create simple database and add data to
the tables.
4. File Handling

Procedure 1. Students should read the Pre-lab Reading assignment before coming to lab.
2. Students should complete the Pre-lab Writing assignment before coming to
lab.
3. In the lab, students should complete Labs 1.1 through 1.4 in sequence.
Your instructor will give further instructions as to grading and completion of
the lab.
4. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 4

Lab 1

Lab 1.1 Pre-lab reading 30 min 5


Installing MS Access

Lab 1.2 Awareness of - 9


Lab Tasks GUI and Rules

7|Page
PRE-LAB READING ASSIGNMENT

MS Access

Microsoft Access is a Database Management System (DBMS) from Microsoft


that combines the relational Microsoft Jet Database Engine with a graphical
user interface and software development tools. It is a member of the Microsoft
Office suite of applications, included in the professional and higher editions.
 Microsoft Access is just one part of Microsoft’s overall data
management product strategy.
 It stores data in its own format based on the Access Jet
Database Engine.
 Like relational databases, Microsoft Access also allows you to
link related information easily. For example, customer and
order data. However, Access 2013 also complements other
database products because it has several powerful
connectivity features.
 It can also import or link directly to data stored in other
applications and databases.
 As its name implies, Access can work directly with data from
other sources, including many popular PC database
programs, with many SQL (Structured Query Language)
databases on the desktop, on servers, on minicomputers, or
on mainframes, and with data stored on Internet or intranet
web servers.
 Access can also understand and use a wide variety of other
data formats, including many other database file structures.
 You can export data to and import data from word processing
files, spreadsheets, or database files directly.
 Access can work with most popular databases that support
the Open Database Connectivity (ODBC) standard, including
SQL Server, Oracle, and DB2.
 Software developers can use Microsoft Access to develop
application software.

File Processing

In Computer Science, File Processing System (FPS) is a way of storing,


retrieving and manipulating data which is present in various files.
Files are used to store various documents. All files are grouped based on
their categories. The file names are very related to each other and arranged
properly to easily access the files. In file processing system, if one needs to
insert, delete, modify, store or update data, one must know the entire
hierarchy of the files.

8|Page
PRELAB WRITING ASSIGNMENT

Fill in the blanks 1. What is RDBM _______________________


2. MS Access is a ___________________
3. In database data stored in a _____________ form
4. MongoDB is a type of ______________ database.
5. Flicker, Pinterest, and Wikipedia is using __________ for storing and
retrieving data.

9|Page
Lab 1

Lab 1.1
Installing MS Access
for database

Log in to Office 365. You can get to login page by clicking the Email
tab or the Office 365 tab in Access or by going to:
http://office365.bristolcc.edu.

Sign in with your student email and password.


[email protected]

 Once you have signed in, click on Office 365 in the upper left-hand
corner to navigate to the home page.

 Uncheck the Bing and MSN browser setting options. Click on Install

now.

 Just a few more steps to install. Once the setup file is downloaded,
click Run, Say Yes and stay online until the installation is complete.
(Click to close this window)

10 | P a g e
 Download and Run the installer (Browser Examples):

 Wait while the installer loads…

 Wait while Office Installs…

11 | P a g e
 Launch an Office application like Word, Excel, or Powerpoint and
click Accept to agree to the license terms

 Click Sign in to get the most out of Office on the top right to register
your software.

 Enter your email address to sign in and click Next. NOTE -- Signing
into your Office 365 account is required to register your software!

 The Installation is Complete! Look for Access 2016 under installed


programs and Click to run

12 | P a g e
13 | P a g e
Lab 1.2 Lab Tasks

1. Create a Database with your name and make a table by name Friend List. The field
should be ID, First Name, Last Name, Phone Number, Email Address, Picture. And then
add records minimum 5.

Screenshot of database should be paste here

2. Define the Terms:


 Queries
 Forms
 Reports

3. Modify the code to create a txt file. The file name should be your name. Add all the data
to the file (ID, First Name, Last Name, Phone Number, Email Address). Now you need to
read the email address in the file exist.

4. #include <iostream>
5. #include <fstream>
6. using namespace std;
7. int main() {
8. string ID, first_name, last_name, phone_number,
email_address;
9. fstream username;
10. username.open("my_file", ios::out);
11. if (!username) {
12. cout << "File not created!";
13. }
14. else {
15. cout << "File created successfully! Now
Enter the Fields to insert in file";
16. cout << "ID: "; cin>>ID;
17. cout << "First Name: "; cin>>first_name;
18. cout << "Last Name: "; cin>>last_name;
19. cout << "Phone Number: "; cin>>phone_number;
20. cout << "Email Address: ";
cin>>email_address;
21. username.close();
22. }
23. return 0;
24. }
25.

14 | P a g e
Introduction to Database system and
Lesson Set Tools for Database system and their Installation
2
Purpose 5. To get basic awareness of Database system
6. To understand MySQL workbench and why we are using it.
7. To become familiar with the tools used for database and their installation.
8. To learn the basics of an editor and compiler and be able to compile and
run sample query.
9. To create new database and table from scratch

Procedure 5. Students should read the Pre-lab Reading assignment before coming to lab.
6. Students should complete the Pre-lab Writing assignment before coming to
lab.
7. In the lab, students should complete Labs 2.1 through 2.4 in sequence.
Your instructor will give further instructions as to grading and completion of
the lab.
8. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 5

Lab 2

Lab 2.1 Pre-lab reading 30 min 6


Installing MySQL for database

Lab 2.2 Awareness of - 8


Lab Tasks Syntax Rules

15 | P a g e
PRE-LAB READING ASSIGNMENT

Database Systems

Database Systems or DBMS is software that caters to the collection of


electronic and digital records to extract useful information and store that
information is known as Database Systems/ Database Management Systems
or DBMS. The purpose of a standard database is to store and retrieve data.
Databases, such as Standard Relational Databases, are specifically designed
to store and process structured data.

Introduction to MySQL Database

MySQL is a fast, easy-to-use RDBMS being used for many small and big
businesses. MySQL is developed, marketed and supported by MySQL AB,
which is a Swedish company. MySQL is becoming so popular because of
many good reasons −
 MySQL is released under an open-source license. So you
have nothing to pay to use it.
 MySQL is a very powerful program in its own right. It handles
a large subset of the functionality of the most expensive and
powerful database packages.
 MySQL uses a standard form of the well-known SQL data
language.
 MySQL works on many operating systems and with many
languages including PHP, PERL, C, C++, JAVA, etc.
 MySQL works very quickly and works well even with large
data sets.
 MySQL is very friendly to PHP, the most appreciated
language for web development.
 MySQL supports large databases, up to 50 million rows or
more in a table. The default file size limit for a table is 4GB,
but you can increase this (if your operating system can handle
it) to a theoretical limit of 8 million terabytes (TB).
 MySQL is customizable. The open-source GPL license allows
programmers to modify the MySQL software to fit their own
specific environments.

Types of Databases

Relational:
This database is based on the relational data model, which stores data in the
form of rows(tuple) and columns(attributes), and together forms a
table(relation). A relational database uses SQL for storing, manipulating, as
well as maintaining the data. E.F. Codd invented the database in 1970. Each
table in the database carries a key that makes the data unique from others.

NoSQL:
Non-SQL/Not Only SQL is a type of database that is used for storing a wide
range of data sets. It is not a relational database as it stores data not only in
tabular form but in several different ways. It came into existence when the
demand for building modern applications increased. Thus, NoSQL presented
a wide variety of database technologies in response to the demands.

Advantage of MySQL  Cross platform


 Used with multiple languages (PHP, NodeJS, python, C#)
 MySQL software is open source.
 MySQL is RDBMS
 The MySQL database server is fast, reliable, scalable and easy to

16 | P a g e
use.
 MySQL sever works client/server or embedded system

Integrated
Environments

An integrated development environment (IDE) is a software package that


bundles an editor (used to write programs), a compiler (that translates
programs) and a run time component into one system. For example, the
figure below shows a screen from the Microsoft Visual C++ integrated
environment. Other systems may have this component separate which makes
the process of running a program a little more difficult. You should also be
aware of which Operating System you are using. An Operating System is
the most important software on your computer. It is the “grand master” of
programs that interfaces the computer with your requests. Your instructor will
explain your particular system and C++ environment so that you will be able
to develop, compile and run C++ programs on it.

17 | P a g e
PRE LAB-WRITING ASSIGNMENT

Fill in the blanks 6. The purpose of a standard database is to ______________ data.


7. MySQL works on many _____________ and with many languages
including PHP, PERL, C, C++, JAVA, etc.
8. NoSQL is not a ______________ database.
The database types are ____________________
9. RDBMS stand for ____________________________
10. A relational database uses ______________ for storing, manipulating,
as well as maintaining the data

18 | P a g e
Lab 2

Lab 2.1
Installing MySQL for
database

Download the latest MySQL Community server from MySQL official


website. For me, it is 8.0.30, if the version differs you no problem the
installation steps will be the same.
 Double click the .exe file to start the installing process. Once the
installation process it will appear window like this and just select custom
option and then click next.

 Drag the MySQL Server, workbench and shell by selecting through the
drop-down list and then just click the forward arrow icon to move for the
installation. Click next=>next=>next

 Now it’s the time to download the selected options, just click the execute
button below to start downloading. This will take some time, Once all
three products downloaded just click the next button to move to
the installation page.

19 | P a g e
 After the downloading process you will be directed to the next page just
click the execute button to install all three products.
 Once the above process done you just leave everything as default just click
next=>next=>next and so on.

Important: In the configuration page you need to setup password for the
root. By default, there is no password. You need to give password to your root.
The password should be 1234

20 | P a g e
Lab 2.2 Lab Tasks

1. Write SQL statement to create database by your name.

2. Write SQL statement to create table by name courses. It should have two fields,
course_id and course_name. The course_id should be the primary key.

3. Write SQL statement to add data into the courses table.

4. Write SQL statement to show all data where course_id is equal to the 3.

21 | P a g e
Lesson Set Introduction to SQL constraints and why
we are using it
3
Purpose 10. To get basic awareness of constraints
11. To understand the SQL constraints and why we are using it
12. How and where we can use these constraints
13. Create new table and use the constraints

Procedure 9. Students should read the Pre-lab Reading assignment before coming to lab.
10. Students should complete the Pre-lab Writing assignment before coming to
lab.
11. In the lab, students should complete Labs 3.1 through 3.4 in sequence.
Your instructor will give further instructions as to grading and completion of
the lab.
12. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 6

Lab 3

Lab 3.1 Pre-lab reading 30 min 6


Recalling the SQL syntax

Lab 3.2 Awareness of - 7


Lab Tasks Syntax Rules

22 | P a g e
PRE-LAB READING ASSIGNMENT

Constraints

SQL constraints are rules that you can imply on the data in a table. It allows
you to restrict only specific data that meets the regulations to go to a table. To
put it simply, only if the data meets the constraint’s rules, the insert operation
will be successful, or else it will be aborted.

Create constraints in SQL

As mentioned, you can create constraints in SQL using the CREATE TABLE
command while creating a new table or ALTER TABLE command while
altering an existing table. The basic syntax of creating an SQL constraint
using the CREATE TABLE command is:

CREATE TABLE table_name(


column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
….
);
In the above syntax:

 table_name: Name of the table you want to create

 column_name: Name of the column you want to create

 data_type: Data type of the value you want to add to the column

 size: Maximum size (length) of the column

 constraint_name: Name of the constraint you want to create and


implement

You can also create a constraint in SQL using the ALTER TABLE command
through the following syntax:

ALTER TABLE table_name ALTER COLUMN column_name data_type(size)


constraint_name

Types of Constraints

Now that you know the basic syntax of creating a constraint in SQL, let’s
move to the types of constraints. There are a total of six SQL constraints
( NOT NULL, UNIQUE, DEFUALT, CHECK, FOREIGN KEY AND PRIMARY
KEY ) available. In this section, you will look deeply into all the constraints in
SQL and create them

NOT NULL By default, SQL tables can accept null values. But if you want to restrict
columns from taking null values, you can use the NOT NULL constraint in
SQL. Using this constraint will simply prohibit anyone from inserting a new
row in the table while keeping the field for this column null. This is useful in

23 | P a g e
scenarios where you need the user to put input for something necessarily. For
instance, if you want to check age restriction, the user must input age. Thus,
you can use the NOT NULL constraint to the age column.

CREATE TABLE Student1(


ID int NOT NULL,
Name varchar(25) NOT NULL,
Age int
);

UNIQUE As the name gives out, the UNIQUE constraint prohibits any duplicate values
in a column. If a column has a UNIQUE constraint, it will not allow any similar
row entry for that field. You can declare more than one column as UNIQUE in
a table

CREATE TABLE Student1(


ID int NOT NULL,
Name varchar(25) NOT NULL,
Age int,
Email_Id NVARCHAR(50) UNIQUE
);

DEFUALT The DEFAULT constraint in SQL is used to assign a default value to the left
empty fields. Thus, if you neither want a user to enter empty fields nor want to
implement the NOT NULL constraint, DEFAULT constraint can come in
handy. It is also helpful to provide a default value to a field if set to NOT
NULL. This will prevent the constraint error, as the field will be given the
default value and will not remain NULL.

CREATE TABLE VOTING_LIST(


ID int PRIMARY KEY,
Name NVARCHAR(50) NOT NULL,
Age int NOT NULL DEFAULT 18
);

CHECK The CHECK constraint allows you to specify a condition that needs to be met
to insert data into a table successfully. A simple example will be to create a
table for the voting list. It is evident that a person needs to be above 18 years
of age to qualify for voting. Thus, with the CHECK constraint’s help, the
administrator will only enter the list of people above 18 years of age

CREATE TABLE VOTING_LIST(


ID int PRIMARY KEY,
Name NVARCHAR(50) NOT NULL,
Age int NOT NULL CHECK (AGE>=18)
);

24 | P a g e
PRIMARY KEY The PRIMARY KEY constraint is a combination of both NOT NULL and
UNIQUE constraints. This means that when you define a column with
PRIMARY KEY, it will not accept any null or duplicate values. You will create
the Student2 table in the code below and determine the ID column with the
PRIMARY KEY constraint. You will then try to insert the same and null values
in different rows and look at the output.

CREATE TABLE Student2(


Name varchar(25) NOT NULL,
ID int PRIMARY KEY,
Age int,
Email_Id NVARCHAR(50) UNIQUE
);

F0REIGN KEY The FOREIGN KEY constraint in SQL is usually used to build relationships
between tables in a database. It handles foreign affairs by connecting to the
PRIMARY KEY values of another table. But to create this connection, you
need to pass a command, which is:

FOREIGN KEY (column_name_first_table) REFERENCES


(column_name_second_table)

Now, you will use this command in the example below to create a FOREIGN
KEY constraint in SQL.

CREATE TABLE ORDERS(


O_ID int PRIMARY KEY,
ORDER_NO int UNIQUE,
C_ID int,
FOREIGN KEY (C_ID) REFERENCES CUSTOMERS(C_ID)
);

PRELAB WRITING ASSIGNMENT

Fill in the blanks 11. By constraining a SQL statement, we limit the ____________
according to certain conditions or restrictions.
12. constraint in SQL are ________________________
13. ___________ and __________constraints form the core of the
PRIMARY KEY constraint.
14. In columns that are subject to the _____________ constraint, duplicate
values are not allowed.
15. NULL means ___________________

25 | P a g e
Lab 3.1 Lab Tasks

1. Insert the missing statement to get all the columns from the Customers table.

* FROM Customers;

2. Write a statement that will select the City column from the Customers table.

Customers;

3. Select all records where the CustomerID column has the value 32.
SELECT * FROM Customers

CustomerID ;

26 | P a g e
Lab 3.2 Lab Tasks

5. Dr. Adnan Idress is an instructor of the database course and he wants to save the record
of each student present in class. He also wants to avoid duplications and fill the subject
field automatically if it’s null. Write SQL statement to create table by name students with
required fields. Std_id, full_name, phn_num, email, subject. Hint the name is not required
to be unique.

6. Modify question 1 and add the age field in the student table, apply check that student
must be greater than or equal to 18 and less than or equal to 30.

7. Use the question 2 table student and write SQL statement to add at least 5 records
using multiple insert syntax.

8. Write SQL statement to delete the student table.

27 | P a g e
Lesson Set Introduction to Boolean logic and
Between operator syntax
4
Purpose 14. To get basic awareness of Boolean logics
15. To understand the SQL AND, OR, & NOT
16. How and where we can use these Booleans
17. Create new table and use the Boolean logic and between operator

Procedure 13. Students should read the Pre-lab Reading assignment before coming to lab.
14. Students should complete the Pre-lab Writing assignment before coming to
lab.
15. In the lab, students should complete Labs 4.1 through 4.4 in sequence.
Your instructor will give further instructions as to grading and completion of
the lab.
16. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 5

Lab 4

Lab 4.1 Pre-lab reading 30 min 5


Recalling the SQL syntax

Lab 4.2 Awareness of - 6


Lab Tasks Syntax Rules

28 | P a g e
PRE-LAB READING ASSIGNMENT

Boolean Logics

Boolean Logic refers to the words " AND, OR, NOT" and their intended usage
with manipulating databases to either add, include, or subtract populated
information from a data set. In other words, Boolean Logic refers to the logical
approach (AND) instead of the arithmetical approach (+) to retrieve
information from any database that contains data sets. The arithmetical
approach refers to using symbols to convey addition as opposed to the logical
sense which uses words.
The importance of using Boolean Logic when searching through databases is
that it allows you to have control over what information the database will
populate through your search in order to increase the efficiency and relevancy
of your results.

Below you will find examples of each of the instances when you
would use Boolean Logic and the results they would generate.

AND Syntax

SELECT column1, column2, ...


FROM table_name ‫مت‬
WHERE condition1 AND condition2 AND condition3 ...;

OR Syntax

SELECT column1, column2, ...


FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

29 | P a g e
NOT Syntax

SELECT column1, column2, ...


FROM table_name
WHERE NOT condition;

BETWEEN
Operator
The SQL BETWEEN condition allows you to easily test if an expression is
within a range of values (inclusive). The values can be text, date, or numbers.
It can be used in a SELECT, INSERT, UPDATE, or DELETE statement. The
SQL BETWEEN Condition will return the records where expression is within
the range of value1 and value2.

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

IN Operator
IN operator allows you to easily test if the expression matches any value in
the list of values. It is used to remove the need of multiple OR condition in
SELECT, INSERT, UPDATE or DELETE. You can also use NOT IN to
exclude the rows in your list. We should note that any kind of duplicate entry
will be retained.

SELECT column_name(s)
FROM table_name
WHERE column_name IN (list_of_values);

30 | P a g e
PRELAB WRITING ASSIGNMENT

Fill in the blanks 1. The __________ operator selects data if any one condition is true.

2. The SQL ___________ operator selects data if all conditions are true.

3. The SQL _________ operator selects data if the given condition is


false.

4. Between operator can be used with both ___________ and


_______________ values.

5. __________ operator is somehow the alternative of or operative

31 | P a g e
Lab 4.2 Lab Tasks

9. Use the 3.2.1 Database named by Courses and add new column by name fees using Alter
keyword syntax.

10. Write a query to Find all the students having first_name Between “A” and “K”. Using
BETWEEN with Date Values:

11. Write a query to Find the first_name, last_name of the students who have fees equal to
20000, 28000 or 25000.

12. Write a query to fetch all the records from the Student table where NAME is “yourChoice”
OR Age is greater then 17.

13. Write a query to fetch first_name, phone and email from the Student table where Age is 18
AND first_name is “yourChoice” OR “yourChoice”.

14. Write a query to fetch all the records from the Student table where city is NOT equal to
Quetta

32 | P a g e
Lesson Set Introduction to like (wildcards), regular expressions
Order by, Distinct and IS NULL operators
5
Purpose 18. To get basic awareness of like and wildcards
19. To understand the Regular Expressions
20. How and where we can use Distinct and Order by operators
21. Practical of all above operators

Procedure 17. Students should read the Pre-lab Reading assignment before coming to the
lab.
18. Students should complete the Pre-lab Writing assignment before coming to
the lab.
19. In the lab, students should complete Labs 5.1 through 5.4 in sequence.
Your instructor will give further instructions as to grading and completion of
the lab.
20. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 5

Lab 5

Lab 5.1 Pre-lab reading 30 min 5


Recalling the SQL syntax

Lab 5.2 Awareness of - 6


Lab Tasks Syntax Rules

33 | P a g e
PRE-LAB READING ASSIGNMENT

MySQL Wildcards

MySQL Wildcards are characters that help search data matching complex criteria.
Wildcards are used in conjunction with the LIKE comparison operator or with the NOT
LIKE comparison operator.

Why use Wildcards?


If you are familiar with using SQL, you may think that you can search for any complex
data using SELECT and WHERE clauses. Then why use Wildcards?

Before we answer that question, let’s look at an example. Suppose that the marketing
department of Myflix video library carried out marketing promotions in the city of Texas
and would like to get some feedback on the number of members

that registered from Texas, you can use the following SELECT statement together with
the WHERE clause to get the desired information.

SELECT * FROM members WHERE postal_address = 'Austin , TX' OR


postal_address = Dallas , TX OR postal_address = Iola,TX OR postal_adress =
Houston ,TX';

LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that start with "a"

WHERE CustomerName LIKE '%a' Finds any values that end with "a"

WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2 characters in
length

WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3 characters in
length

WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"

Regular Expressions

Regular Expressions help search data matching complex criteria. We looked at


wildcards in the previous tutorial. If you have worked with wildcards before, you may be
asking why to learn regular expressions when you can get similar results using
wildcards. Because, compared to wildcards, regular expressions allow us to search for
data matching even more complex criteria.

Basic syntax
The basic syntax for a regular expression is as follows

SELECT statements... WHERE fieldname REGEXP 'pattern';

34 | P a g e
Order
by The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Is Null The IS NULL command is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:

Example:
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

35 | P a g e
PRELAB WRITING ASSIGNMENT

Fill in the blanks 6. ______________ are characters that help search data matching
complex criteria.
7. The _________ keyword is used to avoid duplication while fetching
records.

8. We can search for material that matches even more complicated


criteria using _____________.

9. By default, the order by fetch the records in __________ order

10. Is Null operator will fetch data if the data is __________ in the table

36 | P a g e
Lab 5.2 Lab Tasks

15. Use the 4.2.1 Database and write a query to fetch the data that displays all the name end with
“khan” or “ullah.

16. Write a query to find all the students having “a” in the second place of the name using Like
keyword.

17. Write a query to find the all the cities using the Distinct syntax.

18. Write a query to fetch all the records from the student table where the email matches any of
the expressions. [@], ‘com$’, ‘@ | gmail | com’

19. Write a query to display the name of the student in descending order.

20. Write a query to fetch all the records from the student table where phone IS NULL

37 | P a g e
Lesson Set Introduction to limit & offset, Aggregate functions and
Delete specific data in the table.
6
Purpose 22. To get a basic awareness limit & offset
23. To understand the Aggregate function
24. How and where we can use count, max, min, sum, and avg
25. Delete specific data from the table

Procedure 21. Students should read the Pre-lab Reading assignment before coming to the
lab.
22. Students should complete the Pre-lab Writing assignment before coming to
the lab.
23. Students should complete Labs 6.1 through 6.2 in sequence in the lab. Your
instructor will give further instructions on grading and completing the lab.
24. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 5

Lab 6

Lab 6.1 Pre-lab reading 30 min 5


Recalling the SQL syntax

Lab 6.2 Awareness of - 6


Lab Tasks Syntax Rules

38 | P a g e
PRE-LAB READING ASSIGNMENT

Limit & Offset

The limit keyword is used to limit the number of rows returned in a query result.
It can be used in conjunction with the SELECT, UPDATE OR DELETE commands
LIMIT keyword syntax.

Getting a list of ten (10) members only from the database


Let’s suppose that we want to get a list of the first 10 registered members from the
Myflix database. We would use the following script to achieve that.

SELECT * FROM members LIMIT 10;

Using the OFFSET in the LIMIT query


The offset value is also most often used together with the LIMIT keyword. The
OFFSET value allows us to specify which row to start from retrieving data
Let’s suppose that we want to get a limited number of members starting from the
middle of the rows, we can use the LIMIT keyword together with the offset value to
achieve that. The script shown below gets data starting in the second row and limits
the results to 2.
SELECT * FROM `members` LIMIT 1, 2.

Aggregate Functions
Aggregate functions in SQL Server are used to perform calculations on one or more
values and return the result in a single value. In SQL Server, all aggregate functions
are built-in functions that avoid NULL values except for COUNT (*). We mainly use
these functions with the GROUP BY and HAVING clauses of the SELECT statements
in the database query languages.
DBA generally used these functions for summarizing their data. When aggregate
functions are invoked with a particular set of input values multiple times, they always
return the same value. Therefore, they are also called deterministic functions. It is
noted that the aggregate functions cannot be nested, and the expression cannot be a
subquery.

Various types of SQL aggregate functions are:

Count ()
The COUNT () function returns the number of rows in a database table.
SELECT COUNT (*) AS total employees FROM employee.

Sum ()
The SUM () function returns the total sum of a numeric column.
SELECT SUM (*) AS total employees FROM employee.

Avg ()
The AVG () function calculates the average of a set of values.
SELECT AVG (*) AS total employees FROM employee.

Min ()
The MIN () aggregate function returns the lowest value (minimum) in a set of non-
NULL values.
SELECT MIN (*) AS total employees FROM employee.

Max ()

39 | P a g e
The MAX () aggregate function returns the highest value (maximum) in a set of non-
NULL values.
SELECT MAX (*) AS total employees FROM employee.

Delete The SQL DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows,
otherwise, all the records would be deleted.

Syntax
The basic syntax of the DELETE query with the WHERE clause is as follows −
DELETE FROM table name
WHERE [condition].

If you want to DELETE all the records from the CUSTOMERS table, you do not need
to use the WHERE clause and the DELETE query would be as follows –

DELETE FROM CUSTOMERS.

40 | P a g e
PRE-LAB WRITING ASSIGNMENT

Fill in the blanks 1. _____________ functions in SQL Server are used to perform
calculations on one or more values and return the result in a single
value.
2. The SQL ________ Query is used to delete the existing records from a
table.

3. The _______ function calculates the average of a set of values.

4. The _____ keyword is used to _______ the number of rows returned in


a query result.

5. The __________ value allows us to specify which row to start from


retrieving data

41 | P a g e
Lab 6.2 Lab Tasks

21. Create a new table with the named employee and add 5 columns with constraints. The column
should be id, name, age, gender, and salary.

22. Write a query to find the first 3 employees with a where clause to find only male employees

23. Write a query to total all the employee’s salary display them.

24. Write a query to fetch the highest salary holder.

25. Write a query to the record of the employee who has the lowest salary.

NOTE: This question is out of topic you need to learn this by yourself. First, understand what is
commit and rollback in SQL and then perform this question.

26. Roll back only the last changes you made in the database.

42 | P a g e
Lesson Set Introduction to Primary key and foreign key,
create diagram from the database
7
Purpose 26. To get a basic awareness primary key
27. To understand the usage of primary key
28. How and where we can use foreign key
29. Create Diagram from the existing database

Procedure 25. Students should read the Pre-lab Reading assignment before coming to the
lab.
26. Students should complete the Pre-lab Writing assignment before coming to
the lab.
27. Students should complete Labs 7.1 through 7.2 in sequence in the lab. Your
instructor will give further instructions on grading and completing the lab.
28. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 6

Lab 7

Lab 7.1 Pre-lab reading 30 min 6


Recalling the SQL syntax

Lab 7.2 Awareness of - 7


Lab Tasks Syntax Rules

43 | P a g e
PRE-LAB READING ASSIGNMENT

Primary key

A primary key is a field in a table which uniquely identifies each row/record in a


database table. Primary keys must contain unique values. A primary key column
cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields.
When multiple fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records
having the same value of that field(s).

Note − You would use these concepts while creating database tables.

Create Primary Key


Here is the syntax to define the ID attribute as a primary key in a CUSTOMERS table.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

To create a PRIMARY KEY constraint on the "ID" column when the CUSTOMERS
table already exists, use the following SQL syntax −

ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);

Foreign key
A foreign key is a key used to link two tables together. This is sometimes also called as
a referencing key. A Foreign Key is a column or a combination of columns whose
values match a Primary Key in a different table.

The relationship between 2 tables matches the Primary Key in one of the tables
with a Foreign Key in the second table.

If a table has a primary key defined on any field(s), then you cannot have two records
having the same value of that field(s).

Example
Consider the structure of the following two tables.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),

44 | P a g e
PRIMARY KEY (ID)
);

CREATE TABLE ORDERS (


ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT double,
PRIMARY KEY (ID)
);

If the ORDERS table has already been created and the foreign key has not yet been
set, the use the syntax for specifying a foreign key by altering a table.

ALTER TABLE ORDERS ADD FOREIGN KEY (Customer_ID)


REFERENCES CUSTOMERS (ID);

DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL syntax.

ALTER TABLE ORDERS DROP FOREIGN KEY;

Database Diagram
It is helpful to have a visual representation when designing a database. MySQL
Workbench allows you to create entity relationship diagrams (ERDs) with relationships
between the tables (one to one, one to many) and rearrange them as needed. Below
we cover how to create an ERD from a downloaded SQL file.

Step1: open your workbench application and navigate to the database menu.

Step2: click the reverse engineer and you will get new window and just click the next
button below.

Step3: when you click the next button you will get popup window for the password, to
verify that you are the owner of this server. Just type password and click ok.

45 | P a g e
Step4: when you click ok in password popup window you will get new window to select
the database that you want to view the diagram of that database just select database
and click next>next>password and execute to finish and view the diagram.

46 | P a g e
PRE-LAB WRITING ASSIGNMENT

Fill in the blanks 1. The relationship between 2 tables matches the ________ in one
of the tables with __________ in the second table.

2. It is helpful to have a __________ when designing a database.

3. A foreign key is a key used to link ________ together.

4. A primary key column cannot have ________ values.

47 | P a g e
Lab 7.2 Lab Tasks

27. Create a new table with the named City and add two columns, city_id and city_name and
make the city_id column as primary key and auto_increment.

28. Add at least 5 records to the city table.

29. Alter the LAB_6 student table and make the std_id column as primary key and the city column
as foreign key.

NOTE: You can take guide from the pre_reading section that how you can make diagram.

30. Create diagram from the existing database and paste and export as PNG and paste in the
given box below.

48 | P a g e
Lesson Set Introduction to Diagrams, why DFDs,
Elements of DFDs and ERD
8
Purpose 30. To get a basic data flow diagram
31. To understand the usage entity relationship diagram
32. How and where we can use dfds
33. Create Diagram and convert into the database

Procedure 29. Students should read the Pre-lab Reading assignment before coming to the
lab.
30. Students should complete the Pre-lab Writing assignment before coming to
the lab.
31. Students should complete Labs 8.1 through 8.2 in sequence in the lab. Your
instructor will give further instructions on grading and completing the lab.
32. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 5

Lab 8

Lab 8.1 Pre-lab reading 30 min 5


Recalling the SQL syntax

Lab 8.2 Awareness of - 6


Lab Tasks Syntax Rules

49 | P a g e
PRE-LAB READING ASSIGNMENT

Data flow Diagram

DFD is the abbreviation for Data Flow Diagram. The flow of data of a system or a process is
represented by DFD. It also gives insight into the inputs and outputs of each entity and the
process itself. DFD does not have control flow and no loops or decision rules are present.
Specific operations depending on the type of data can be explained by a flowchart. Data Flow
Diagram can be represented in several ways. The DFD belongs to structured-analysis modeling
tools. Data Flow diagrams are very popular because they help us to visualize the major steps and
data involved in software-system processes.

Components of DFD
The Data Flow Diagram has 4 components:
 Process
Input to output transformation in a system takes place because of process function. The
symbols of a process are rectangular with rounded corners, oval, rectangle, or a circle.
The process is named a short sentence, in one word or a phrase to express its essence.
 Data Flow
Data flow describes the information transferring between different parts of the systems.
The arrow symbol is the symbol of data flow. A relatable name should be given to the
flow to determine the information which is being moved. Data flow also represents
material along with information that is being moved. Material shifts are modeled in
systems that are not merely informative. A given flow should only transfer a single type of
information. The direction of flow is represented by the arrow which can also be bi-
directional.
 Warehouse
The data is stored in the warehouse for later use. Two horizontal lines represent the
symbol of the store. The warehouse is simply not restricted to being a data file, rather it
can be anything like a folder with documents, an optical disc, a filing cabinet. The data
warehouse can be viewed independent of its implementation. When the data flows from
the warehouse it is considered as data reading and when data flows to the warehouse it
is called data entry or data updation.
 Terminator
The Terminator is an external entity that stands outside of the system and communicates
with the system. It can be, for example, organizations like banks, groups of people like
customers or different departments of the same organization, which is not a part of the
model system and is an external entity. Modeled systems also communicate with
terminators.

Levels of DFDs with university admission system example

50 | P a g e
Level 1:

Level 2:

Entity Relationship Diagram


ER Diagram stands for Entity Relationship Diagram, also known as ERD, is a diagram that
displays the relationship of entity sets stored in a database. In other words, ER diagrams help to
explain the logical structure of databases. ER diagrams are created based on three basic

51 | P a g e
concepts: entities, attributes and relationships.

ER Diagrams contain different symbols that use rectangles to represent entities, ovals to define
attributes and diamond shapes to represent relationships.
At first look, an ER diagram looks very similar to the flowchart. However, ER Diagram includes
many specialized symbols, and its meanings make this model unique. The purpose of ER
Diagram is to represent the entity framework infrastructure.

52 | P a g e
Pre-lab writing assignment

Fill in the blanks 1. DFD is the abbreviation _______________

2. The symbols of a process are ____________ with rounded


corners,

3. The data is stored in the ______________ for later use.

4. diagram that displays the relationship of entity sets stored in a


database called as ______________

5. Data flow describes the information transferring between


different __________ of the systems.

53 | P a g e
Lab 8.2 Lab Tasks

31. Create a new level 0 Data Flow Diagram of student attendance system.

32. Modify level 0 to level 1 Data Flow Diagram of student attendance system.

33. Modify level 1 to level 2 Data Flow Diagram of student attendance system.

34. Create a new Entity Relationship diagram of student attendance system at workbench and
forward engineer that diagram or model into database.

54 | P a g e
Lesson Set Inner, Left, Right, cross and
Multiple Join
9
Purpose 34. To get a basic awareness of Joins
35. To understand the usage of inner and left join
36. How and where we can use cross and multiple join
37. To practice and use these joins in workbench

Procedure 33. Students should read the Pre-lab Reading assignment before coming to the
lab.
34. Students should complete the Pre-lab Writing assignment before coming to
the lab.
35. Students should complete Labs 9.1 through 9.2 in sequence in the lab. Your
instructor will give further instructions on grading and completing the lab.
36. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 5

Lab 9

Lab 9.1 Pre-lab reading 30 min 5


Recalling the SQL syntax

Lab 9.2 Awareness of - 6


Lab Tasks Syntax Rules

55 | P a g e
PRE-LAB READING ASSIGNMENT

INNER JOIN

INNER JOIN in SQL is the most common and important type of join which allows users
to access matching data from two or more database tables.
When the join condition is met between the tables, then it returns all the common rows
from them.
The Venn diagram of INNER JOIN is shown in the following picture. The shaded
region of the Venn diagram shows the intersection values of two tables:

Syntax of INNER JOIN in SQL


SELECT * FROM Table_Name1
INNER JOIN Table_Name2
ON Table_Name1.Column_Name = Table_Name2.Column_Name;

LEFT JOIN

The Left Join in MySQL is used to query records from multiple tables. This clause is
similar to the Inner Join clause that can be used with a SELECT statement
immediately after the FROM keyword. When we use the Left Join clause, it will return
all the records from the first (left-side) table, even no matching records found from the
second (right side) table. If it will not find any matches record from the right side table,
then returns null.
In other words, the Left Join clause returns all the rows from the left table and matched
records from the right table or returns Null if no matching record found. This Join can
also be called a Left Outer Join clause. So, Outer is the optional keyword to use with
Left Join.
We can understand it with the following visual representation where Left Joins returns
all records from the left-hand table and only the matching records from the right side
table:

MySQL LEFT JOIN Syntax


SELECT * FROM customers

56 | P a g e
LEFT JOIN orders ON customers.customer_id = orders.customer_id;

RIGHT JOIN

The Right Join is used to joins two or more tables and returns all rows from the right-
hand table, and only those results from the other table that fulfilled the join condition. If
it finds unmatched records from the left side table, it returns Null value. It is similar to
the Left Join, except it gives the reverse result of the join tables. It is also known as
Right Outer Join. So, Outer is the optional clause used with the Right Join.
We can understand it with the following visual representation where Right Outer Join
returns all records from the left-hand table and only the matching records from the
other table:

RIGHT JOIN Syntax


SELECT * FROM customers
RIGHT JOIN orders ON customers.customer_id = orders.customer_id

ORDER BY customer_id;

CROSS JOIN

MySQL CROSS JOIN is used to combine all possibilities of the two or more tables and
returns the result that contains every row from all contributing tables. The CROSS
JOIN is also known as CARTESIAN JOIN, which provides the Cartesian product of all
associated tables. The Cartesian product can be explained as all rows present in the
first table multiplied by all rows present in the second table. It is similar to the Inner
Join, where the join condition is not available with this clause.
We can understand it with the following visual representation where CROSS JOIN
returns all the records from table1 and table2, and each row is the combination of rows
of both tables.

MySQL CROSS JOIN Syntax


SELECT * FROM customers
CROSS JOIN contacts;

57 | P a g e
58 | P a g e
PRE-LAB WRITING ASSIGNMENT

Fill in the blanks 1. When the join condition is met between the tables, then it returns all
the common rows from them is called ______________.

2. The _________ clause returns all the rows from the left table and
matched records from the right table or returns Null if no matching
record found.

3. The _________ clause returns all the rows from the right table and
matched records from the left table or returns Null if no matching
record found.

4. Cross Join is also called ___________________

59 | P a g e
Lab 9.2 Lab Tasks

35. Use the Lab 7 database and write query to show all the data exist in student table and
matching data in city table.

36. Use the Lab 7 database and write query to show all the data exist in city table and matching
data in student table.

37. Create a new table with the named courses and add two columns, course_id and
course_name and make the city_id column as primary key and auto_increment.

38. Modify the student table, add new column with named course with datatype INT and also
make this column as foreign key

39. Write query for multiple join to join all the student, city, and courses table

60 | P a g e
Lesson Set Group by, Having, Subquery with Exist,
Union and Union all
10
Purpose 38. To get a basic awareness Group by clause
39. To understand the usage of having clause
40. How and where we can use subquery with exist and not exist
41. To practice and use union and union all with two tables

Procedure 37. Students should read the Pre-lab Reading assignment before coming to the
lab.
38. Students should complete the Pre-lab Writing assignment before coming to
the lab.
39. Students should complete Labs 10.1 through 10.2 in sequence in the lab.
Your instructor will give further instructions on grading and completing the
lab.
40. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 5

Lab 10

Lab 10.1 Pre-lab reading 30 min 5


Recalling the SQL syntax

Lab 10.2 Awareness of - 6


Lab Tasks Syntax Rules

61 | P a g e
PRE-LAB READING ASSIGNMENT

Group By

The GROUP BY clause is a SQL command that is used to group rows that have the
same values. The GROUP BY clause is used in the SELECT statement. Optionally it is
used in conjunction with aggregate functions to produce summary reports from the
database.
That’s what it does, summarizing data from the database.
The queries that contain the GROUP BY clause are called grouped queries and only
return a single row for every grouped item.

SQL GROUP BY Syntax


SELECT emp_name, MAX (working_hours) AS "Minimum working ho
ur"
FROM employees
GROUP BY emp_name;

Having clause

The HAVING Clause enables you to specify conditions that filter which group results
appear in the results.
The WHERE clause places conditions on the selected columns, whereas the HAVING
clause places conditions on groups created by the GROUP BY clause.

Syntax
The HAVING clause must follow the GROUP BY clause in a query and must also
precede the ORDER BY clause if used. The following code block has the syntax of the
SELECT statement including the HAVING clause −
SELECT column1, column2
FROM table1, table2
WHERE conditions
GROUP BY column1, column2
HAVING conditions
ORDER BY column1, column2

Subquery

A subquery in MySQL is a query, which is nested into another SQL query and
embedded with SELECT, INSERT, UPDATE or DELETE statement along with the
various operators. We can also nest the subquery with another subquery. A subquery
is known as the inner query, and the query that contains subquery is known as
the outer query. The inner query executed first gives the result to the outer query, and
then the main/outer query will be performed. MySQL allows us to use subquery
anywhere, but it must be closed within parenthesis. All subquery forms and operations
supported by the SQL standard will be supported in MySQL also.

The following are the rules to use subqueries:


 Subqueries should always use in parentheses.
 If the main query does not have multiple columns for subquery, then a
subquery can have only one column in the SELECT command.
 We can use various comparison operators with the subquery, such as >, <, =,
IN, ANY, SOME, and ALL. A multiple-row operator is very useful when the
subquery returns more than one row.
 We cannot use the ORDER BY clause in a subquery, although it can be used

62 | P a g e
inside the main query.
 If we use a subquery in a set function, it cannot be immediately enclosed in a
set function.

The following are the advantages of using subqueries:


 The subqueries make the queries in a structured form that allows us to isolate
each part of a statement.
 The subqueries provide alternative ways to query the data from the table;
otherwise, we need to use complex joins and unions.
 The subqueries are more readable than complex join or union statements.
 AD

MySQL Subquery Syntax


The following is the basic syntax to use the subquery in MySQL:
SELECT column_list (s) FROM table_name
WHERE column_name OPERATOR
(SELECT column_list (s) FROM table_name [WHERE])

Union & Union All

Union:
Union means joining two or more data sets into a single set. In SQL Server, Union is
used to combine two queries into a single result set using the select statements. Union
extracts all the rows that are described in the query.

Syntax
SELECT City FROM student
UNION
SELECT City FROM student2
ORDER BY City;

Union All:
A union is used for extracting rows using the conditions specified in the query while
Union All is used for extracting all the rows from a set of two tables.

Syntax
SELECT City FROM student
UNION
SELECT City FROM student2
ORDER BY City;

63 | P a g e
PRE-LAB WRITING ASSIGNMENT

Fill in the blanks 5. summarizing data from the database is called ______________.

6. The Having clause is placed after ______________

7. A subquery is known as the _____________ query, and the query that


contains subquery is known as the ____________ query.

8. Union is used to combine _________ queries into a single result set


using the _________ statements

64 | P a g e
Lab 10.2 Lab Tasks

40. Use the Lab 9 database and write query to show the number of students coming from each
city.

41. Use the Lab 9 database and write query to show the number of students that enrolled in
database course.

42. Write a query to display the total number of students that belongs to Quetta. Use Aliases to
make table more meaningful.

43. Create new table with name lecturer and add 3 columns (id, name, city) with constraints.

44. Write a query to show id, name, city from both student table and lecturer table.

65 | P a g e
s

Lesson Set Entity Relationship


Diagram
11
Purpose 42. To get a basic awareness ERD
43. To understand the usage of ERD
44. How and where we can use diagrams
45. To practice and make new diagrams of the problem

Procedure 41. Students should read the Pre-lab Reading assignment before coming to the
lab.
42. Students should complete the Pre-lab Writing assignment before coming to
the lab.
43. Students should complete Labs 11.1 through 11.2 in sequence in the lab.
Your instructor will give further instructions on grading and completing the
lab.
44. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 4

Lab 11

Lab 11.1 Pre-lab reading 30 min 4


Recalling the concept

Lab 11.2 Awareness of - 5


Lab Tasks Syntax Rules

66 | P a g e
PRE-LAB READING ASSIGNMENT

Entity Relationship Diagram

ER Diagram stands for Entity Relationship Diagram, also known as ERD, is a diagram
that displays the relationship of entity sets stored in a database. In other words, ER
diagrams help to explain the logical structure of databases. ER diagrams are created
based on three basic concepts: entities, attributes and relationships.

ER Diagrams contain different symbols that use rectangles to represent entities, ovals
to define attributes and diamond shapes to represent relationships.
At first look, an ER diagram looks very similar to the flowchart. However, ER Diagram
includes many specialized symbols, and its meanings make this model unique. The
purpose of ER Diagram is to represent the entity framework infrastructure.

We can convert this diagram into the tables easily:

Student
stuId firstName lastName Major credits

Class
classNumber Schedule room

67 | P a g e
PRE-LAB WRITING ASSIGNMENT

Lab 11.1.1: Analyze the table carefully and make new ER Diagram from it.

Lab 11.1.2: Analyze the table carefully and make new ER Diagram from it.

68 | P a g e
Lab 11.2 Lab Tasks

45. Read All the lab (1,2,3…10) tasks and think on the database we made till now and create
ERD.
Hint: tables we have student, courses, city, and lecturer

69 | P a g e
Lab Manual Master Solution:
This comprehensive solution covers various aspects of database management, SQL
queries, data flow diagrams, and entity relationship diagrams. Here's a summary of what
you've accomplished:
Database Management:
 Explored the fundamentals of Relational Database Management Systems (RDBMS) and their
importance in storing and managing data.
 Learned about different types of databases, such as MySQL and MS Access
 Explored concepts like queries, forms, reports, constraints, and data manipulation in SQL.
SQL Queries:
 Created databases and tables, defined primary keys and foreign keys, and applied
constraints to ensure data integrity.
 Performed various operations like inserting, updating, and deleting records in tables.
 Learned about different SQL clauses, such as WHERE, GROUP BY, HAVING, and ORDER BY, to
filter, aggregate, and sort data.
 Practiced joining tables using different types of joins like INNER JOIN and LEFT JOIN.
Data Flow Diagrams (DFD):
 Explored the concept of DFDs and their significance in visualizing data flow and system
processes.
 Created level 0, level 1, and level 2 DFDs for a student attendance system, demonstrating
the flow of data within the system.
Entity Relationship Diagrams (ERD):
 Developed an ERD for the student attendance system using Workbench.
 Modeled relationships between entities, including tables for students, cities, and courses.
 Forward-engineered the ERD to create the corresponding database schema.
Lab 9 Database Queries:
 Utilized the Lab 9 database to perform advanced queries, such as aggregating data, counting
records, and using aliases.
 Demonstrated proficiency in retrieving data based on specific conditions, joining multiple
tables, and displaying results.
Overall, your Lab Manual Master Solution showcases your expertise in database
management, SQL querying. By successfully completing these tasks, you have developed
essential skills for working with databases and gained a solid understanding of concepts like
normalization, constraints, and data manipulation.

70 | P a g e
Introduction to Database system and
Lesson Set Tools for Database system and their Installation
1

Fill in the 1. RDBMS is a Relational Database Management System.


2. MS Access is a relational database management system
blanks (RDBMS).
3. In a database, data is stored in a structured form.
4. MongoDB is a type of NoSQL database.
5. Flicker, Pinterest, and Wikipedia are using a combination of
different technologies for storing and retrieving data.

Lab 1.2 Lab Task


1. Create a Database with your name and make a table by name Friend List. The field should
be ID, First Name, Last Name, Phone Number, Email Address, Picture. And then add
records minimum 5.

2. Define the Terms:


 Queries: In the context of databases, queries are requests for specific information or
actions performed on a database. They are used to retrieve, manipulate, or modify
data in the database based on specified criteria or conditions.
 Forms: Forms are user interfaces that allow users to input and interact with data in a
database. They provide a structured way to enter, edit, and view data, typically using
fields and controls such as text boxes, dropdown menus, checkboxes, and buttons.
 Reports: Reports are generated documents that present data from a database in a
formatted and organized manner. They are used to summarize, analyze, and present
data in a visually appealing and informative way, often including tables, charts, and
graphs.

3. Modify the code to create a txt file. The file name should be your name. Add all the data to
the file (ID, First Name, Last Name, Phone Number, Email Address). Now you need to
read the email address in the file exist.
#include <iostream>
#include <fstream>

71 | P a g e
#include <string>
using namespace std;

int main() {
string ID, first_name, last_name, phone_number, email_address;
fstream username;
username.open("your_name.txt", ios::out); // Replace "your_name"
with your actual name
if (!username) {
cout << "File not created!";
}
else {
cout << "File created successfully! Now enter the fields to insert
in the file" << endl;
cout << "ID: "; cin >> ID;
cout << "First Name: "; cin >> first_name;
cout << "Last Name: "; cin >> last_name;
cout << "Phone Number: "; cin >> phone_number;
cout << "Email Address: "; cin >> email_address;

// Write data to the file


username << "ID: " << ID << endl;
username << "First Name: " << first_name << endl;
username << "Last Name: " << last_name << endl;
username << "Phone Number: " << phone_number << endl;
username << "Email Address: " << email_address << endl;

username.close(); // Close the file after writing

// Read the file and check if the email address exists


ifstream file("your_name.txt"); // Replace "your_name" with your
actual name
string line;
bool emailExists = false;

while (getline(file, line)) {


if (line.find("Email Address: " + email_address) !=
string::npos) {
emailExists = true;
break;
}
}

file.close(); // Close the file after reading

if (emailExists) {
cout << "Email address exists in the file." << endl;
}
else {
cout << "Email address does not exist in the file." << endl;
}
}

return 0;
}

72 | P a g e
Introduction to MySQL
Lesson Set Workbench
2

Fill in the 1. The purpose of a standard database is to store and organize


data.
blanks 2. MySQL works on many operating systems and with many
languages including PHP, PERL, C, C++, JAVA, etc.
3. NoSQL is not a relational database.
4. The database types are:
 Relational databases (e.g., MySQL, PostgreSQL, Oracle)
 NoSQL databases (e.g., MongoDB, Cassandra, Redis)
 Object-oriented databases
 Hierarchical databases
 Network databases
5. RDBMS stands for Relational Database Management System.
6. A relational database uses tables for storing, manipulating, as
well as maintaining the data.

Lab 1.2 Lab Task


1. Write SQL statement to create database by your name.

CREATE DATABASE your_name;

2. Write SQL statement to create table by name courses. It should have two fields,
course_id and course_name. The course_id should be the primary key.

CREATE TABLE courses (


course_id INT PRIMARY KEY,
course_name VARCHAR(255)
);

3. Write SQL statement to add data into the courses table.

INSERT INTO courses (course_id, course_name)


VALUES (1, 'Mathematics'), (2, 'History'), (3, 'Science');

4. Write SQL statement to show all data where course_id is equal to the 3.

SELECT * FROM courses WHERE course_id = 3;

73 | P a g e
Lesson Set Introduction to SQL constraints and why
we are using it
3

Fill in the 1. By constraining a SQL statement, we limit the result set


according to certain conditions or restrictions.
blanks 2. Constraints in SQL are rules and conditions.
3. The PRIMARY KEY constraint in SQL consists of two core
constraints: the NOT NULL constraint and the UNIQUE
constraint form the core of the PRIMARY KEY constraint.
4. In columns that are subject to the UNIQUE constraint, duplicate
values are not allowed.
5. NULL means the absence of a value or the unknown value.

Lab 3.2 Lab Task


1. Dr. Adnan Idress is an instructor of the database course and he wants to save the record
of each student present in class. He also wants to avoid duplications and fill the subject
field automatically if it’s null. Write SQL statement to create table by name students with
required fields. Std_id, full_name, phn_num, email, subject. Hint the name is not required
to be unique.

CREATE TABLE students (


Std_id INT PRIMARY KEY,
full_name VARCHAR(255),
phn_num VARCHAR(15),
email VARCHAR(255),
subject VARCHAR(255) DEFAULT 'Unknown'
);

2. Modify question 1 and add the age field in the student table, apply check that student
must be greater than or equal to 18 and less than or equal to 30.

CREATE TABLE students (


Std_id INT PRIMARY KEY,
full_name VARCHAR(255),
phn_num VARCHAR(15),
email VARCHAR(255),
subject VARCHAR(255) DEFAULT 'Unknown',
age INT CHECK (age >= 18 AND age <= 30)
);

3. Use the question 2 table student and write SQL statement to add at least 5 records using

74 | P a g e
multiple insert syntax.

INSERT INTO students (Std_id, full_name, phn_num, email, subject, age)


VALUES
(1, 'John Doe', '123456789', '[email protected]', 'Mathematics', 20),
(2, 'Jane Smith', '987654321', '[email protected]', 'Science', 25),
(3, 'David Johnson', '456789123', '[email protected]', 'English',
22),
(4, 'Emily Davis', '321654987', '[email protected]', 'History', 28),
(5, 'Michael Wilson', '789123456', '[email protected]', 'Geography', 23);

4. Write SQL statement to delete the student table.

DROP TABLE students;

75 | P a g e
Lesson Set Introduction to Boolean logic and
Between operator syntax
4

Fill in the 1. The OR operator selects data if any one condition is true.
2. The AND operator selects data if all conditions are true.
blanks 3. The NOT operator selects data if the given condition is false.
4. The BETWEEN operator can be used with both numeric and
date/time values.
5. The XOR (Exclusive OR) operator is somehow the alternative of
the OR operator. It returns true if only one of the conditions is
true, but not both.

Lab 4.2 Lab Task


1. Use the 3.2.1 Database named by Courses and add new column by name fees using Alter
keyword syntax.

ALTER TABLE Courses


ADD fees DECIMAL(10, 2);

2. Write a query to Find all the students having first_name Between “A” and “K”. Using
BETWEEN with Date Values:

SELECT *
FROM students
WHERE first_name BETWEEN 'A' AND 'K';

3. Write a query to Find the first_name, last_name of the students who have fees equal to 20000,
28000 or 25000.

SELECT first_name, last_name


FROM students
WHERE fees IN (20000, 28000, 25000);

4. Write a query to fetch all the records from the Student table where NAME is “yourChoice”
OR Age is greater then 17.

SELECT *
FROM Student
WHERE NAME = 'yourChoice' OR Age > 17;

5. Write a query to fetch first_name, phone and email from the Student table where Age is 18
AND first_name is “yourChoice” OR “yourChoice”.

SELECT first_name, phone, email

76 | P a g e
FROM Student
WHERE Age = 18 AND (first_name = 'yourChoice' OR first_name =
'yourChoice');

6. Write a query to fetch all the records from the Student table where city is NOT equal to
Quetta

SELECT *
FROM Student
WHERE city <> 'Quetta';

77 | P a g e
Lesson Set Introduction to like (wildcards), regular expressions
Order by, Distinct and IS NULL operators
5

Fill in the 1. Wildcards are characters that help search data matching
complex criteria.
blanks 2. The DISTINCT keyword is used to avoid duplication while
fetching records.
3. We can search for material that matches even more complicated
criteria using advanced filtering techniques such as subqueries
or joins.
4. By default, the ORDER BY clause fetches the records in
ascending order.
5. The IS NULL operator will fetch data if the data is NULL in the
table.

Lab 5.2 Lab Task


1. Use the 4.2.1 Database and write a query to fetch the data that displays all the name end with
“khan” or “ullah.

SELECT *
FROM your_table_name
WHERE name LIKE '%khan' OR name LIKE '%ullah';

2. Write a query to find all the students having “a” in the second place of the name using Like
keyword.

SELECT *
FROM students
WHERE name LIKE '_a%';

3. Write a query to find the all the cities using the Distinct syntax.

SELECT DISTINCT city


FROM your_table_name;

4. Write a query to fetch all the records from the student table where the email matches any of
the expressions. [@], ‘com$’, ‘@ | gmail | com’

SELECT *
FROM student
WHERE email LIKE '%[@]%' OR email LIKE '%com$%' OR email LIKE '%@%'
OR email LIKE '%gmail%' OR email LIKE '%com%';

78 | P a g e
5. Write a query to display the name of the student in descending order.

SELECT name
FROM student
ORDER BY name DESC;

6. Write a query to fetch all the records from the student table where phone IS NULL

SELECT *
FROM student
WHERE phone IS NULL;

79 | P a g e
Lesson Set Introduction to limit & offset, Aggregate functions and
Delete specific data in the table.
6

Fill in the 7. Scalar functions in SQL Server are used to perform calculations
on one or more values and return the result in a single value.
blanks 8. The SQL DELETE Query is used to delete the existing records
from a table.
9. The AVG function calculates the average of a set of values.
10. The LIMIT keyword is used to limit the number of rows returned
in a query result.
11. The OFFSET value allows us to specify from which row to start
retrieving data.

Lab 6.2 Lab Task


1. Create a new table with the named employee and add 5 columns with constraints. The column
should be id, name, age, gender, and salary.

CREATE TABLE employee (


id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT CHECK (age >= 18),
gender VARCHAR(10) CHECK (gender IN ('Male', 'Female')),
salary DECIMAL(10, 2) DEFAULT 0 CHECK (salary >= 0)
);

2. Write a query to find the first 3 employees with a where clause to find only male employees

SELECT *
FROM employee
WHERE gender = 'Male'
LIMIT 3;

3. Write a query to total all the employee’s salary display them.

SELECT SUM(salary) AS total_salary


FROM employee;

4. Write a query to fetch the highest salary holder.

SELECT *
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee);

80 | P a g e
5. Write a query to the record of the employee who has the lowest salary.

SELECT *
FROM employee
WHERE salary = (SELECT MIN(salary) FROM employee);

NOTE: This question is out of topic you need to learn this by yourself. First, understand what is
commit and rollback in SQL and then perform this question.

6. Roll back only the last changes you made in the database.

ROLLBACK;

81 | P a g e
Lesson Set Introduction to Primary key and foreign key,
create diagram from the database
7

Fill in the 1. The relationship between 2 tables matches the primary key in
one of the tables with the foreign key in the second table.
blanks 2. It is helpful to have a database schema when designing a
database.
3. A foreign key is a key used to link tables together.
4. A primary key column cannot have duplicate values.

Lab 7.2 Lab Task


1. Create a new table with the named City and add two columns, city_id and city_name and
make the city_id column as primary key and auto_increment.

CREATE TABLE City (


city_id INT PRIMARY KEY AUTO_INCREMENT,
city_name VARCHAR(255) NOT NULL
);

2. Add at least 5 records to the city table.

INSERT INTO City (city_name) VALUES


('New York'),
('London'),
('Tokyo'),
('Paris'),
('Sydney');

3. Alter the LAB_6 student table and make the std_id column as primary key and the city column
as foreign key.

NOTE: You can take guide from the pre_reading section that how you can make diagram.

4. Create diagram from the existing database and paste and export as PNG and paste in the
given box below.

ALTER TABLE LAB_6


ADD PRIMARY KEY (std_id),
ADD FOREIGN KEY (city) REFERENCES City(city_id);

Lesson Set Introduction to Diagrams, why DFDs,


Elements of DFDs and ERD

82 | P a g e
8

Fill in the 1. DFD is the abbreviation for "Data Flow Diagram."


2. The symbols of a process are rectangular with rounded corners.
blanks 3. The data is stored in the database for later use.
4. A diagram that displays the relationship of entity sets stored in a
database is called an "Entity-Relationship Diagram" (ERD).
5. Data flow describes the information transferring between
different components or subsystems of the systems.

Lab 8.2 Lab Task


1. Create a new level 0 Data Flow Diagram of student attendance system.

2. Modify level 0 to level 1 Data Flow Diagram of student attendance system.

3. Modify level 1 to level 2 Data Flow Diagram of student attendance system.

4. Create a new Entity Relationship diagram of student attendance system at workbench and
forward engineer that diagram or model into database.

83 | P a g e
Lesson Set Inner, Left, Right, cross and
Multiple Join
9

Fill in the 1. When the join condition is met between the tables, then it returns
all the common rows from them is called an "inner join".
blanks 2. The "LEFT JOIN" clause returns all the rows from the left table
and matched records from the right table or returns Null if no
matching record is found.
3. The "RIGHT JOIN" clause returns all the rows from the right table
and matched records from the left table or returns Null if no
matching record is found.
4. Cross Join is also called a "Cartesian Join" or "Cross Product".

Lab 9.2 Lab Task


1. Use the Lab 7 database and write query to show all the data exist in student table and
matching data in city table.

SELECT *
FROM student
INNER JOIN city ON student.city_id = city.city_id;

2. Use the Lab 7 database and write query to show all the data exist in city table and matching
data in student table.

SELECT *
FROM city
INNER JOIN student ON city.city_id = student.city_id;

3. Create a new table with the named courses and add two columns, course_id and course_name
and make the city_id column as primary key and auto_increment.

CREATE TABLE courses (


course_id INT PRIMARY KEY AUTO_INCREMENT,
course_name VARCHAR(255)
);

4. Modify the student table, add new column with named course with datatype INT and also make

84 | P a g e
this column as foreign key

ALTER TABLE student


ADD COLUMN course INT,
ADD CONSTRAINT fk_course
FOREIGN KEY (course)
REFERENCES courses(course_id);

5. Write query for multiple join to join all the student, city, and courses table

SELECT *
FROM student
JOIN city ON student.city_id = city.city_id
JOIN courses ON student.course = courses.course_id;

85 | P a g e
Lesson Set Group by, Having, Subquery with Exist,
Union and Union all
10

Fill in the 1. Summarizing data from the database is called "aggregation".


2. The Having clause is placed after the "Group By" clause.
blanks 3. A subquery is known as the "inner" query, and the query that
contains the subquery is known as the "outer" query.
4. Union is used to combine "multiple" queries into a single result
set using the "Union" statements.

Lab 10.2 Lab Task


1. Use the Lab 9 database and write query to show the number of students coming from each
city.

SELECT city, COUNT(*) AS num_students


FROM student
GROUP BY city;

2. Use the Lab 9 database and write query to show the number of students that enrolled in
database course.

SELECT COUNT(*) AS num_students


FROM student
WHERE course = 'Database';

3. Write a query to display the total number of students that belongs to Quetta. Use Aliases to
make table more meaningful.

SELECT COUNT(*) AS total_students


FROM student
WHERE city = 'Quetta';

4. Create new table with name lecturer and add 3 columns (id, name, city) with constraints.

CREATE TABLE lecturer (


id INT PRIMARY KEY,
name VARCHAR(255),
city VARCHAR(255)
);

5. Write a query to show id, name, city from both student table and lecturer table.

SELECT id, name, city


FROM student
UNION

86 | P a g e
SELECT id, name, city F ROM lecturer;

87 | P a g e

You might also like