DB Lab Manuals
DB Lab Manuals
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.
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.
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.
Lab 1
7|Page
PRE-LAB READING ASSIGNMENT
MS Access
File Processing
8|Page
PRELAB WRITING ASSIGNMENT
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.
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):
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!
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.
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.
Lab 2
15 | P a g e
PRE-LAB READING ASSIGNMENT
Database Systems
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.
16 | P a g e
use.
MySQL sever works client/server or embedded system
Integrated
Environments
17 | P a g e
PRE LAB-WRITING ASSIGNMENT
18 | P a g e
Lab 2
Lab 2.1
Installing MySQL for
database
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
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.
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.
Lab 3
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.
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:
data_type: Data type of the value you want to add to the column
You can also create a constraint in SQL using the ALTER TABLE command
through the following syntax:
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.
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
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.
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
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.
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:
Now, you will use this command in the example below to create a FOREIGN
KEY constraint in SQL.
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.
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.
Lab 4
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
OR Syntax
29 | P a g e
NOT Syntax
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.
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.
Lab 5
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.
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.
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
Basic syntax
The basic syntax for a regular expression is as follows
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.
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.
Lab 6
38 | P a g e
PRE-LAB READING ASSIGNMENT
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.
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.
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 –
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.
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.
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.
Lab 7
43 | P a g e
PRE-LAB READING ASSIGNMENT
Primary key
Note − You would use these concepts while creating database tables.
To create a PRIMARY KEY constraint on the "ID" column when the CUSTOMERS
table already exists, use the following SQL syntax −
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.
44 | P a g e
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.
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.
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.
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.
Lab 8
49 | P a g e
PRE-LAB READING ASSIGNMENT
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.
50 | P a g e
Level 1:
Level 2:
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
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.
Lab 9
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:
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:
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:
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.
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.
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.
Lab 10
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.
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.
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.
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 ______________.
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
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.
Lab 11
66 | P a g e
PRE-LAB READING ASSIGNMENT
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.
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
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;
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
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.
4. Write SQL statement to show all data where course_id is equal to the 3.
73 | P a g e
Lesson Set Introduction to SQL constraints and why
we are using it
3
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.
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.
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.
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.
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”.
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.
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.
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.
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;
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.
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.
82 | P a g e
8
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".
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.
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
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
2. Use the Lab 9 database and write query to show the number of students that enrolled in
database course.
3. Write a query to display the total number of students that belongs to Quetta. Use Aliases to
make table more meaningful.
4. Create new table with name lecturer and add 3 columns (id, name, city) with constraints.
5. Write a query to show id, name, city from both student table and lecturer table.
86 | P a g e
SELECT id, name, city F ROM lecturer;
87 | P a g e