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

DBMS LAB MANUAL

The document is a lab manual for a Database Management System course, detailing objectives, policies, and practical exercises for students. It includes guidelines for lab assessments, report formats, and practical tasks focused on database concepts and SQL. The manual is structured to facilitate hands-on learning and application of database technologies, with a focus on developing practical skills in database management and application development.

Uploaded by

Musaddaq Khawer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DBMS LAB MANUAL

The document is a lab manual for a Database Management System course, detailing objectives, policies, and practical exercises for students. It includes guidelines for lab assessments, report formats, and practical tasks focused on database concepts and SQL. The manual is structured to facilitate hands-on learning and application of database technologies, with a focus on developing practical skills in database management and application development.

Uploaded by

Musaddaq Khawer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Database Management

System
Department of Computer Science
Table of Contents
VERSION HISTORY ………………………………………………………………………………………………..A
LAB ASSESSMENTRUBRICS…………………………………………………………………………………...…B
FOREWORD................................................................................................................................................................. 1
DATA STRUCTURE LAB OBJECTIVE ................................................................................................................................................... 1
LAB POLICY ................................................................................................................................................................ 3
GROUPS ............................................................................................................................................................................................. 3
LAB REPORTS .................................................................................................................................................................................... 3
REPORT FORMAT............................................................................................................................................................................... 3
PRACTICAL’S................................................................................................................................................................................. 5
PRACTICAL 1 ..................................................................................................................................................................................... 5
BASIC DATABASE CONCEPTS & DATABASE APPROACH VS FILE-BASED SYSTEM ..................................................................................................... 5
PRACTICAL 2 ................................................................................................................................................................................... 14
BASIC DATABASE CONCEPTS & DATABASE APPROACH VS FILE-BASED SYSTEM ............................................................................................ 14
PRACTICAL 3 ................................................................................................................................................................................... 16
Introduction to Structured Query Language(SQL)……………………………………………………………………………………………………………………. 16

PRACTICAL 4 …………………………………………………………………………………………………………………………
Relational Data Model……………………………………………………………………………………………………………………………………………..
........................................................................................................................................................................................................ 18
........................................................................................................................................................................................................ 18
PRACTICAL 5 ………………………………………………………………………………………………………………………
ENTITY RELATIONSHIP MODEL AND ENTITY-RELATIONSHIP DIAGRAMS ................................................................................................. 19
........................................................................................................................................................................................................ 19
PRACTICAL 6 ………………………………………………………………………………………………………………………
Relational algebra………………………………………………………………………………………………………………………………………………….
........................................................................................................................................................................................................ 20
........................................................................................................................................................................................................ 20
PRACTICAL 7 ………………………………………………………………………………………………………………………
Joins and sub-queries in SQL…………………………………………………………………………………………………………………………………..
........................................................................................................................................................................................................ 21
........................................................................................................................................................................................................ 21
PRACTICAL 8 ………………………………………………………………………………………………………………………
Grouping and aggregation in SQL……………………………………………………………………………………………………………………………
........................................................................................................................................................................................................ 22
........................................................................................................................................................................................................ 22
PRACTICAL 9 ………………………………………………………………………………………………………………………
Functional dependencies……………………………………………………………………………………………………………………………………….
........................................................................................................................................................................................................ 23
........................................................................................................................................................................................................ 23
PRACTICAL 10 ………………………………………………………………………………………………………………………
Normalization………………………………………………………………………………………………………………………………………………………….
........................................................................................................................................................................................................ 30
........................................................................................................................................................................................................ 30
PRACTICAL 11 ………………………………………………………………………………………………………………………
Concurrency control………………………………………………………………………………………………………………………………………………..
c|Page

........................................................................................................................................................................................................ 32
........................................................................................................................................................................................................ 32
PRACTICAL 12 ................................................................................................................................................................................. 34
........................................................................................................................................................................................................ 34
PRACTICAL 13 ................................................................................................................................................................................. 36
........................................................................................................................................................................................................ 36
PRACTICAL 14 ................................................................................................................................................................................. 39
........................................................................................................................................................................................................ 39
PRACTICAL 15 ................................................................................................................................................................................. 41
........................................................................................................................................................................................................ 41
PRACTICAL 16 ................................................................................................................................................................................. 46
........................................................................................................................................................................................................ 46

Department of Computer Science Database Management System Lab Manual


A|Page

Version History

Title Database Lab Manual

Description
Dr. Mussadiq Abdul Rahim
Created By

Date of Creation March 2021


Maintained By
Changes Made Updated By Updating Status
Version No.
Date
Rubrics Dr. Mussadiq 16-03-2021 ---
v-1.0
Abdul Rahim
Practical’s Additions Tabinda Nasir 16-03-2021 ---
v-1.1

Practical Review Dr. Mussadiq 16-03-2021 Active


v-1.2
Abdul Rahim
B|Page

LAB ASSESSMENT RUBRICS


In-Lab Assessment Rubrics

I. Accepts
Defensive, can’t Positive ,willing to Proactive, provides self-
Willingness to Refuses to respond, argumentive criticism/direction, needs
understand, makes integrate feedback into criticism , makes their own
respond style help formulating in
excuses or withdraws learning improvement plan
5% improvement plan
Student recognizes
Student’s work shows Student’s work shows
II. Student’s work shows Student’s work shows potential conflicts b/t
understanding of complete understanding of
Understanding of incomplete understanding of slight understanding of requirements and seeks
problem and most problem and all
concept 5% problem and/or requirements problem and requirements clarification from
requirements requirements
client/user
Program Code is copied Algorithm is copied but Program code is developed
III. Task
with changes in modified with respect to by student oneself, with a Program code is solely
Originality Program Code is entirely copied
nomenclature of different inputs and little help from prohibited developed by the student
5%
components scenario sources

Post-Lab Assessment Rubrics


Application does not
Application compiles Application compiles with
I. compile or compiles Application compiles with no Application compiles with no
and runs without few or no warnings.
Application but crashes. warnings. Robust operation warnings. Results are well
crashing. Some attempt Consideration given to
Functionality Confusing. Little or no of the application, with good formatted. Program structure is
at detecting and unusual conditions with
10% error detection or recovery exemplary and can be re-used
correcting errors. reasonable recovery
correction.
No use of ADTs No use of ADTs
II. Selected No use of ADTs (aggregate Use of ADTs; all are Uses advanced ADTs that
(aggregate data (aggregate data
concept 6% data types/structures) appropriate for task improves program performance
types/structures) types/structures)
Program Code is copied Algorithm is copied but Program code is developed
III. Task
Program Code is with changes in modified with respect to by student oneself, with a Program code is solely
Originality
entirely copied nomenclature of different inputs and little help from prohibited developed by the student
6%
components scenario sources
IV. Timeliness The code was more The code was within a The program was delivered The program was delivered The program was delivered in
3% than 2 days overdue. day after the due date. within the due date. in Lab. Lab.
C|Page

Open Ended Lab Assessment Rubrics

I. No use of ADTs No use of ADTs


No use of ADTs (aggregate Use of ADTs; all are Uses advanced ADTs that
Selected concept (aggregate data (aggregate data
data types/structures) appropriate for task improves program performance
5% types/structures) types/structures)

Program Code is copied Program code is developed


II. Algorithm is copied but
Program Code is with changes in by student oneself, with a Program code is solely
Code Originality modified with respect to
entirely copied nomenclature of little help from prohibited developed by the student
5% different inputs and scenario
components sources
C|Page

Foreword
Database Lab Objective:
The major objective of this lab is to provide a strong formal foundation in database concepts, technology and practice to the students to groom them into
well-informed database application developers. It enables them to gain knowledge in practical applications of database.

Course Outcomes:
At the end of this lab session, the student will be able to solve real world problems using database concepts and technology. They will have practical
knowledge on the applications of database.
ii | P a g e

Lab Structure:
Provided lab manual is organized in such a way that the students can directly use it in the laboratory. Each laboratory exercise comprises of
1. Statement of the problem

2. Solution

3. Results

4. Conclusion

Student must follow this sequence to conduct any database experiment in the lab and write your report accordingly. The lab is divided into 3 stages.
Each stage exemplifies various concepts. At each stage there is database examples that can be an example of how your database should look like.
Pre-Lab: At this stage student will come with a proposed solution of the problem given. When the Lab starts after lab demonstration the problem
task of each individual student will be assessed

In-Lab: At this stage student will go through multiple scenarios and practice their subject knowledge in it. Group practice is integrated at this stage
where student in group of two perform lab tasks on respective software/tools

Post Lab: After Lab is completed at this level student will perform given problems at home to further strengthen their concepts and impart their
creative skills. The nature of problem given at this stage will be more intricate.

Department of Computer Science Database Lab Manual


iii | P a g e

Lab Policy
Groups:
Students will be formed into groups / syndicates of two or three on the first lab day. This pair programming approach may vary depending upon the
experiment nature. However, once a student has signed up with a group in term project, he may not change groups without prior approval of the
instructor.
Lab Reports:
Students will perform the Experiment/Practical in group (optional), and turn in individual laboratory reports on the assigned date of deadline
mentioned at the beginning of each lab experiment detailed document. Your report should be self-contained, i.e. a computer scientist should be able
to perform the experiment and duplicate your results by reading your report. DO NOT "adjust" your data to make them fit what you believe to be
an acceptable value. Plagiarism is strictly forbidden in individual reports. Those Students who found in such activities will be awarded no credits
plus re-submission will not be entertained. For each Lab Task maintain screenshots of results along with all the program files as a record in separate
lab folder with name of student id or group id. Task Screenshots should be shown along with program source code as evidence of task
implementation. In order to achieve the expected results do not “adjust” your actual results instead explain the discrepancies.
Report Format:
The report must be typewritten. A report should include the following in order.
A title page, which includes the following information, in given format:

Department of Computer Science Database Lab Manual


iv | P a g e

Database Management Systems Lab


Lab Code:

Subject/Course Name
Database Lab

Department Registration Number/Name Semester/Section

Computer Science

Date Instructor’s Name Instructor’s Signature

Department of Computer Science Database Lab Manual


v|Page

B. Objective or purpose and scope of the experiment work.


C. Theoretical aspect of the experiment.
D. Experimental procedure that explains briefly the pseudocode or algorithm used to carry out the experiment by utilizing the equipment and data
provided.
E. Experimental and /or calculated results. (Include all data (screenshots, numeric) you have taken, a sample calculation, and the results). All
results should be documented as well as maintained in electronic form. Hand written results or source code will not be accepted
F. Discussion of results in light of the theoretical “predictions”. Include an error analysis. Quantify the errors whenever possible.
G. Conclusions, wherein you write what you learned from the experiment. Your conclusions must summarize your report and must be based on
your experimental results.

Department of Computer Science Database Lab Manual


vi | P a g e

Practical’s

Practical 1
Basic database concepts & database approach vs file-based system
Objectives
Data is a collection of raw facts and figures processed to obtain useful information to assist organization in making decisions. Database is an organized collection
of related data. In order to manage the databases, DBMS offers sets of program and tools
Learning Outcomes
After performing this lab student should be able to
 Install required software

 Explore given tables in sql management studio.

 Explore SQL

 Explore Structure of tables in a database.

 Create Database.

Department of Computer Science Database Lab Manual


vii | P a g e

Activity Time Boxing


Task Activity Name Total
No. Time
1 Concept Deliverance 30
2 Setting Up SQL Server 2019 Developer 10
SQL Server Management Studio

5 Evaluation/Marking 60
Total Time: 180

Tools and Reading Resources


 Book: Object Oriented Programming in C++ by Robert Lafore, Chap 2

 Install SQL Server 2019 Developer

 SQL Server Management Studio

Theoretical Explanation

Microsoft SQL Server


It is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of
storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across
a network (including the Internet).

Department of Computer Science Database Lab Manual


viii | P a g e
Installation Steps

Step 1: Run Installed Application

Step 2: Select Custom Installation

Step 3: Choose Installation

After all of the packages have downloaded, a new page as illustrated below will follow. Click on “Installation “

Step 4: Choose New SQL Server standalone

After Step 3, choose the first option in the list and proceed to the next step.

Step 5: Specify Edition

This step depends on whether you need “Developer “, “Evaluation” or “Express “. Their differences are described in the window. Since we are
installing the “Developer” edition, let us proceed with that option. Click “Next “

Department of Computer Science Database Lab Manual


ix | P a g e

Step 6: Accept License Terms, Microsoft Update, Install Rules, Feature Selection

Step 7: Instance Configuration, Server Configuration

Step 8: Ready to Install

Step 9: Finish up

SQL Server Management Studio (SSMS)

It is an integrated environment for managing any SQL infrastructure, from SQL Server to Azure SQL Database. SSMS provides tools to configure,

monitor, and administer instances of SQL Server and databases. Use SSMS to deploy, monitor, and upgrade the data-tier components used by your

applications, and build queries and scripts.

 Once downloaded we will get a .exe file named as "SSMS-Setup-ENU.exe." Double click on it
 Below window will appear. Click on 'Install' button to install SQL Server Management Studio (SSMS) on your system

Department of Computer Science Database Lab Manual


x|Page

Department of Computer Science Database Lab Manual


xi | P a g e

 Installation will begin. Below screen will show Packages progress and Overall Progress.

 Once Completed, SSMS Setup will show the below screen with "Setup Completed" message.

Department of Computer Science Database Lab Manual


xii | P a g e

How to access "Management Studio


Now, we're ready to open "Management Studio. Go to Start Menu>Programs>Microsoft SQL Server Tools 18> Microsoft SSMS 18.
Below 'Connect to Server' screen will appear. Server Name defaults to the name selected while installing MS SQL server.

Department of Computer Science Database Lab Manual


xiii | P a g e

In-Lab

Practice Tasks

Practice Task #1: [Expected Time= 25 mins]


Install and Configure SQL Server 2019 Developer and SQL Server Management Studio on your computers.

Practice Task #2: [Expected Time= 25 mins]


Explore the system databases and list following with evidence for each database. Table, Fields, Number of Records, Type of Data stored

Evaluation Criteria:
As defined in Lab Rubrics.

Department of Computer Science Database Lab Manual


xiv | P a g e

Post-Lab

Task #1:

Develop C# Form application to demonstrate file-based I/O operations. A unique data must be written to file, the input should be given by the user.
The unique data must be read back to the program and shown to the user.

Department of Computer Science Database Lab Manual


xv | P a g e
Practical 2
Basic database concepts & database approach vs file-based system
Objective
In this Lab students will learn about basic database concepts & database approach vs file-based system.

Introduction
Basic concepts of DBMS
Database Management System or DBMS in short refers to the technology of storing and retrieving usersí data with utmost efficiency
along with appropriate security measures. This tutorial explains the basics of DBMS such as its architecture, data models, data
schemas, data independence, E-R model, relation model, relational database design, and storage and file structure and much more.
Why to Learn DBMS?
Traditionally, data was organized in file formats. DBMS was a new concept then, and all the research was done to make it overcome the deficiencies in traditional
style of data management. A modern DBMS has the following characteristics −
 Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For
example, a school database may use students as an entity and their age as an attribute.
 Relation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by
looking at the table names.
 Isolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive,
on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process.
 Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normal-
ization is a mathematically rich and scientific process that reduces data redundancy.
 Consistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt
of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-
processing systems.
 Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many
and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used.

Department of Computer Science Database Lab Manual


xvi | P a g e

Database approach vs file-based system

S.NO. File System DBMS

File system is a software that manages and organizes the files DBMS is a software for managing the data-
1. in a storage medium within a computer. base.

2. Redundant data can be present in a file system. In DBMS there is no redundant data.

It provides backup and recovery of data even


3. It doesn’t provide backup and recovery of data if it is lost. if it is lost.

4. There is no efficient query processing in file system. Efficient query processing is there in DBMS.

There is more data consistency because of


5. There is less data consistency in file system. the process of normalization.

It has more complexity in handling as com-


6. It is less complex as compared to DBMS. pared to file system.

DBMS has more security mechanisms as


7. File systems provide less security in comparison to DBMS. compared to file system.

Department of Computer Science Database Lab Manual


xvii | P a g e

S.NO. File System DBMS

It has a comparatively higher cost than a file


8. It is less expensive than DBMS. system.

In-Lab

Task #1:
Explore Microsoft SQL Server using SQL Server Management Studio.

Task #2:
Using guidelines: https://docs.microsoft.com/en-us/sql/relational-databases/backup-/back-up-a-transaction-log-sql-server?view=sql-server-ver15 perform
following.
 Create a backup of msdb system database.

 Restore the database from the back up created.

 Provide description and screenshot for each step performed in above tasks.

Department of Computer Science Database Lab Manual


xviii | P a g e

Post-Lab

Task #1:

Explain how a three-tier client-server architecture can be established using Microsoft SQL Server and a Window Form based application.

Department of Computer Science Database Lab Manual


xix | P a g e

Practical 3
Introduction to Structured Query Language (SQL)

Objective
In this Lab students will learn about Introduction to Structured Query Language (SQL).

Introduction

SQL
o SQL stands for Structured Query Language. It is used for storing and managing data in relational database management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to create, read, update and delete relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as their standard database language.
o SQL allows users to query the database in a number of ways, using English-like statements.

Rules:
SQL follows the following rules:

o Structure query language is not case sensitive. Generally, keywords of SQL are written in uppercase.
o Statements of SQL are dependent on text lines. We can use a single SQL statement on one or multiple text line.

Department of Computer Science Database Lab Manual


xx | P a g e
o Using the SQL statements, you can perform most of the actions in a database.
o SQL depends on tuple relational calculus and relational algebra.

SQL process:
o When an SQL command is executing for any RDBMS, then the system figure out the best way to carry out the request and the SQL engine determines
that how to interpret the task.
o In the process, various components are included. These components can be optimization Engine, Query engine, Query dispatcher, classic, etc.
o All the non-SQL queries are handled by the classic query engine, but SQL query engine won't handle logical files.

Department of Computer Science Database Lab Manual


xxi | P a g e

In-Lab

Task #1: [Expected Time= 25 mins]


Create a database in Microsoft SQL Server Management Studio 18 namely Lab3<Your First Name>DB

Task #2:
• Write a query to
• Create a table with name Student
• Having these attributes: Registration No, Full Name, Department, Batch, Semester, ClearedCreditHours, CurrentCreditHours, CGPA,
Scholarship Status, ScholarshipType
• Assign appropriate data types to each of the attributes
• Insert one record in the created table with your details
• Select the stored record
• Remove Columns Semester, CurrentCreditHours, Scholarship Status, ScholarshipType
• Add Columns Enrollment Status
• Update your record (use WHERE Clause) with Enrollment Status as True

Department of Computer Science Database Lab Manual


xxii | P a g e

Post-Lab

Post Lab Task 1:


Write a report on all steps taken to achieve above task with screenshots of each step and query code.

Department of Computer Science Database Lab Manual


xxiii | P a g e

Practical 4
Relational Data Model

Objective
In this Lab students will learn about relational data model.
Introduction
What is Relational Model?
Relational Model (RM) represents the database as a collection of relations. A relation is nothing but a table of values. Every row in the table represents a
collection of related data values. These rows in the table denote a real-world entity or relationship.
The table name and column names are helpful to interpret the meaning of values in each row. The data are represented as a set of relations. In the relational model,
data are stored as tables. However, the physical storage of the data is independent of the way the data are logically organized.
Relational Model Concepts

1. Attribute: Each column in a Table. Attributes are the properties which define a relation. e.g., Student_Rollno, NAME, etc.
2. Tables – In the Relational model the, relations are saved in the table format. It is stored along with its entities. A table has two properties: rows and
columns. Rows represent records and columns represent attributes.
3. Tuple – It is nothing but a single row of a table, which contains a single record.
4. Relation Schema: A relation schema represents the name of the relation with its attributes.
5. Degree: The total number of attributes which in the relation is called the degree of the relation.
6. Cardinality: Total number of rows present in the Table.
7. Column: The column represents the set of values for a specific attribute.
8. Relation instance – Relation instance is a finite set of tuples in the RDBMS system. Relation instances never have duplicate tuples.
9. Relation key - Every row has one, two or multiple attributes, which is called relation key.
10. Attribute domain – Every attribute has some predefined value and scope which is known as attribute domain

Department of Computer Science Database Lab Manual


xxiv | P a g e

Department of Computer Science Database Lab Manual


xxv | P a g e

In-Lab

Task 1
 Create a database in Microsoft SQL Server Management Studio 18 namely Lab4<Your First Name>DB
 Identify entities, attributes and relations for given organization.
 Write a query to
 Transform the above in to a database and results must be reflected in Lab4<Your First Name>DB.
 Insert dummy data, such that it’s sufficient enough to prove your design as valid.

Post-Lab

Task 1
 Write a report on all steps taken to achieve above task with screenshots of each step and query code. Report must include how you were able to
identify entities, attributes and relations.

Department of Computer Science Database Lab Manual


xxvi | P a g e

Practical 5
Entity relationship model and entity-relationship diagrams

Objective
In this Lab students will learn about Entity relationship model and entity-relationship diagrams.

Introduction
Entity Relationship Model (ER Modelling) is a graphical approach to database design. It is a high-level data model that defines data elements and their
relationship for a specified software system. An ER model is used to represent real-world objects.

What is ER 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.

Department of Computer Science Database Lab Manual


xxvii | P a g e

Department of Computer Science Database Lab Manual


xxviii | P a g e

ER Diagrams Symbols & Notations


Entity Relationship Diagram Symbols & Notations mainly contains three basic symbols which are rectangle, oval and diamond to represent relationships
between elements, entities and attributes. There are some sub-elements which are based on main elements in ERD Diagram. ER Diagram is a visual
representation of data that describes how data is related to each other using different ERD Symbols and Notations.
Following are the main components and its symbols in ER Diagrams:

 Rectangles: This Entity Relationship Diagram symbol represents entity types


 Ellipses: Symbol represent attributes
 Diamonds: This symbol represents relationship types
 Lines: It links attributes to entity types and entity types with other relationship types
 Primary key: attributes are underlined
 Double Ellipses: Represent multi-valued attributes

ER Diagram Symbols

Crows foot notation guide


https://www.vertabelo.com/blog/crow-s-foot-notation/

Department of Computer Science Database Lab Manual


xxix | P a g e

In-Lab

Task 1
 Identify entities, attributes and relations for a given organization.
 Design complete Entity-relationship diagram, which reflects the design you made for Lab4<Your First Name>DB in Lab 4.
 Create the ERD using https://draw.io (use New 🡪 Basic 🡪 Entity Relationship Diagram). Use Crow’s Foot notation only.
 Submit your diagram in
 The. drawio file (can be generated using Save)
 The PNG file (can be generated using Export as 🡪 PNG)

Post-Lab

Task 1
 Write a report on all steps taken to achieve the above task with screenshots of each step and query code. Report must include the final ERD that is
submitted in PNG form.

Department of Computer Science Database Lab Manual


xxx | P a g e

Practical 6
Relational algebra

Objective
In this lab students will learn about relational algebra in detail.

Relational Algebra

Relational algebra is a procedural query language, which takes instances of relations as input and yields instances of relations as output. It uses operators to
perform queries. An operator can be either unary or binary. They accept relations as their input and yield relations as their output. Relational algebra is per-
formed recursively on a relation and intermediate results are also considered relations.
The fundamental operations of relational algebra are as follows −

 Select
 Project
 Union
 Set different
 Cartesian product
 Rename

Department of Computer Science Database Lab Manual


xxxi | P a g e

Basic SQL Relational Algebra Operations

Relational Algebra divided in various groups


Unary Relational Operations

 SELECT (symbol: σ)
 PROJECT (symbol: π)
 RENAME (symbol: ρ)

Relational Algebra Operations from Set Theory

 UNION (υ)
 INTERSECTION (),
 DIFFERENCE (-)
 CARTESIAN PRODUCT (x)

Binary Relational Operations

 JOIN
 DIVISION

Department of Computer Science Database Lab Manual


xxxii | P a g e

SELECT (σ)

The SELECT operation is used for selecting a subset of the tuples according to a given selection condition. Sigma(σ)Symbol denotes it. It is used as an expression
to choose tuples which meet the selection condition. Select operator selects tuples that satisfy a given predicate.

σ (r)
p

σ is the predicate

r stands for relation which is the name of the table

p is prepositional logic

Example 1

σ topic = "Database" (Tutorials)

Output - Selects tuples from Tutorials where topic = 'Database'.

rejection(π)

The projection eliminates all attributes of the input relation but those mentioned in the projection list. The projection method defines a relation that contains a
vertical subset of Relation.

This helps to extract the values of specified attributes to eliminates duplicate values. (pi) symbol is used to choose attributes from a relation. This operator helps
you to keep specific columns from a relation and discards the other columns.

Department of Computer Science Database Lab Manual


xxxiii | P a g e

Example of Projection:

Consider the following table

CustomerID CustomerName Status

1 Google Active

2 Amazon Active

3 Apple Inactive

4 Alibaba Active

Department of Computer Science Database Lab Manual


xxxiv | P a g e

Here, the projection of CustomerName and status will give

Π CustomerName, Status (Customers)


CustomerName Status

Google Active

Amazon Active

Apple Inactive

Alibaba Active

Department of Computer Science Database Lab Manual


xxxv | P a g e

Union operation (υ)

UNION is symbolized by ∪ symbol. It includes all tuples that are in tables A or in B. It also eliminates duplicate tuples. So, set A UNION set B would be
expressed as:
The result <- A ∪ B
For a union operation to be valid, the following conditions must hold -

 R and S must be the same number of attributes.


 Attribute domains need to be compatible.
 Duplicate tuples should be automatically removed.

Example
Consider the following tables.

Table A Table B

column 1 column 2 column 1 column 2

1 1 1 1

1 2 1 3

A ∪ B gives

Table A ∪ B

Department of Computer Science Database Lab Manual


xxxvi | P a g e
column 1 column 2

1 1

1 2

1 3

Set Difference (-)

- Symbol denotes it. The result of A - B, is a relation which includes all tuples that are in A but not in B.

 The attribute name of A has to match with the attribute name in B.


 The two-operand relations A and B should be either compatible or Union compatible.
 It should be defined relation consisting of the tuples that are in relation A, but not in B.

Example
A-B
Table A - B

column 1 column 2

1 2

Department of Computer Science Database Lab Manual


xxxvii | P a g e

Intersection

An intersection is defined by the symbol ∩

A∩B

Defines a relation consisting of a set of all tuple that are in both A and B. However, A and B must be union-compatible.

Visual Definition of Intersection

Example:

A∩B
Table A ∩ B

column 1 column 2

1 1

Department of Computer Science Database Lab Manual


xxxviii | P a g e

In-Lab

Task 1

 For the given database (Lab6DB) , find the following using relational algebra operators.
 Customers from Portland
 Customer first name and last name, for all customers.
 Union on Order.CustomerId and Customer.Id for all entity occurrences in Order and Customer
 Intersect on Order.CustomerId and Customer.Id for all entity occurrences in Order and Customer
 Product on customer first name and last name
 Inner Join on Customer.Id and Order.Id

Post-Lab

Task 1
 Write a report on all steps taken to achieve the above task with screenshots of each step and query code.

Department of Computer Science Database Lab Manual


xxxix | P a g e
Practical 7
Joins and subqueries in SQL

Joins
A join is a query that combines records from two or more tables. A join will be performed whenever multiple tables appear in the FROM clause of the query. The
select list of the query can select any columns from any of these tables. If the join condition is omitted or invalid, then a Cartesian product is formed. If any two
of these tables have a column name in common, then must qualify these columns throughout the query with table or table alias names to avoid ambiguity. Most
join queries contain at least one join condition, either in the FROM clause or in the WHERE clause.
Subquery
A Subquery or Inner query or Nested query is a query within SQL query and embedded within the WHERE clause. A Subquery is a SELECT statement that is
embedded in a clause of another SQL statement. They can be very useful to select rows from a table with a condition that depends on the data in the same or
another table. A Subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. The subquery can be
placed in the following SQL clauses they are WHERE clause, HAVING clause, FROM clause.

Advantages of Joins:
 The advantage of a join includes that it executes faster.
 The retrieval time of the query using joins almost always will be faster than that of a subquery.
 By using joins, you can maximize the calculation burden on the database i.e., instead of multiple queries using one join query. This means you can make
better use of the database’s abilities to search through, filter, sort, etc.

Advantages of Subquery:
 Subqueries divide the complex query into isolated parts so that a complex query can be broken down into a series of logical steps.
 It is easy to understand and code maintenance is also at ease.
 Subqueries allow you to use the results of another query in the outer query.
 In some cases, subqueries can replace complex joins and unions.

Department of Computer Science Database Lab Manual


xl | P a g e

SQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the
right side, if there is no match.
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

SQL RIGHT JOIN Keyword


The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records from the left table (table1). The result is 0 records from
the left side, if there is no match.
RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Department of Computer Science Database Lab Manual


xli | P a g e

In-Lab

Tasks 1
 For the given database (Lab6DB) find out following using join and subqueries as required
o Left Join on Product and OrderItem
o Right Join on Product and OrderItem
o Distinct ProductName for the products which were order with at least 7 items in any order

Post-Lab

Tasks 1
 Write a report on all steps taken to achieve the above task with screenshots of each step and query code. Highlight differences between results of Left
and Right Join queries, if any.

Department of Computer Science Database Lab Manual


xlii | P a g e

Practical 8
Grouping and aggregation in SQL

Objective

In this Lab students will learn about grouping and aggregation in SQL

Introduction

SQL GROUPING
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has same values in
different rows then it will arrange these rows in a group.
Important Points
 GROUP BY clause is used with the SELECT statement.
 In the query, GROUP BY clause is placed after the WHERE clause.
 In the query, GROUP BY clause is placed before ORDER BY clause if used any.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
ORDER BY column1, column2;

SQL Aggregation
In database management an aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single
value of more significant meaning.

Department of Computer Science Database Lab Manual


xliii | P a g e

Various Aggregate Functions


1) Count ()
2) Sum ()
3) Avg ()
4) Min ()
5) Max ()

Now let us understand each Aggregate function with an example:


Id Name Salary
-----------------------
1 A 80
2 B 40
3 C 60
4 D 70
5 E 60
6 F Null

Count ():
Count (*): Returns total number of records. i.e 6
Count(salary): Return number of Non Null values over the column salary. i.e 5.
Count(Distinct Salary): Return number of distinct Non Null values over the column salary .i.e 4

Sum ():
sum(salary): Sum all Non Null values of Column salary i.e., 310
sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.

Avg ():
Avg(salary) = Sum(salary) / count(salary) = 310/5
Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4

Department of Computer Science Database Lab Manual


xliv | P a g e

Min ():
Min(salary): Minimum value in the salary column except NULL i.e., 40.
Max(salary): Maximum value in the salary i.e., 80.

Department of Computer Science Database Lab Manual


xlv | P a g e

In-Lab

Tasks 1

 For the given database (Lab6DB) find out following using aggregation and grouping as required
o Order ID, Total Amount without using Order table.
o Order ID and average Total Amount using Order table.

 ID of the customers among first 20 customers along with their minimum order value, who have spent at least 200 or more on a single order

Post-Lab

Tasks 1

 Write a report on all steps taken to achieve above task with screenshots of each step and query code. Indicate logic behind the query written i.e., how
did you achieve by writing the specific query.

Department of Computer Science Database Lab Manual


xlvi | P a g e

Practical 9
Functional dependencies
Objective
In this lab students will learn about functional dependencies in database.
Introduction
Functional Dependency
Functional Dependency (FD) is a constraint that determines the relation of one attribute to another attribute in a Database Management System (DBMS).
Functional Dependency helps to maintain the quality of data in the database. It plays a vital role to find the difference between good and bad database design.
A functional dependency is denoted by an arrow "→". The functional dependency of X on Y is represented by X → Y. Let's understand Functional Dependency
in DBMS with example.
Example:

Employee number Employee Name Salary City


1 Ali 50000 Islamabad
2 Hamza 30000 Karachi
3 Rida 25000 Lahore

In this example, if we know the value of Employee number, we can obtain Employee Name, city, salary, etc. By this, we can say that the city, Employee Name,
and salary are functionally depended on Employee number.

Rules of Functional Dependencies


Below are the Three most important rules for Functional Dependency in Database:

 Reflexive rule –. If X is a set of attributes and Y is_subset_of X, then X holds a value of Y.


 Augmentation rule: When x -> y holds, and c is attribute set, then ac -> bc also holds. That is adding attributes which do not change the basic dependencies.
 Transitivity rule: This rule is very much similar to the transitive rule in algebra if x -> y holds and y -> z holds, then x -> z also holds. X -> y is called as
functionally that determines y.

Department of Computer Science Database Lab Manual


xlvii | P a g e
Types of Functional Dependencies in DBMS
There are mainly four types of Functional Dependency in DBMS. Following are the types of Functional Dependencies in DBMS:

 Multivalued Dependency
 Trivial Functional Dependency
 Non-Trivial Functional Dependency
 Transitive Dependency

Multivalued Dependency in DBMS


Multivalued dependency occurs in the situation where there are multiple independent multivalued attributes in a single table. A multivalued dependency is a
complete constraint between two sets of attributes in a relation. It requires that certain tuples be present in a relation. Consider the following Multivalued
Dependency Example to understand.
Example:
Car_model maf_year Color
H001 2017 Metallic
H001 2017 Green
H005 2018 Metallic
H005 2018 Blue
H010 2015 Metallic
H033 2012 Gray

In this example, maf_year and color are independent of each other but dependent on car_model. In this example, these two columns are said to be multivalue
dependent on car_model.
This dependence can be represented like this:
car_model -> maf_year
car_model-> colour
Trivial Functional Dependency in DBMS
The Trivial dependency is a set of attributes which are called a trivial if the set of attributes are included in that attribute.
So, X -> Y is a trivial functional dependency if Y is a subset of X. Let's understand with a Trivial Functional Dependency Example.
For example:
Emp_id Emp_name
Department of Computer Science Database Lab Manual
xlviii | P a g e
AS555 Harry
AS811 George
AS999 Kevin

Consider this table of with two columns Emp_id and Emp_name.


{Emp_id, Emp_name} -> Emp_id is a trivial functional dependency as Emp_id is a subset of {Emp_id,Emp_name}.
Non Trivial Functional Dependency in DBMS
Functional dependency which also known as a nontrivial dependency occurs when A->B holds true where B is not a subset of A. In a relationship, if attribute B
is not a subset of attribute A, then it is considered as a non-trivial dependency.
Company CEO Age
Microsoft Satya Nadella 51
Google Sundar Pichai 46
Apple Tim Cook 57

Example:
(Company} -> {CEO} (if we know the Company, we know the CEO name)
But CEO is not a subset of Company, and hence it's non-trivial functional dependency.
Transitive Dependency in DBMS
A Transitive Dependency is a type of functional dependency which happens when t is indirectly formed by two functional dependencies. Let's understand with
the following Transitive Dependency Example.
Example:
Company CEO Age
Microsoft Satya Nadella 51
Google Sundar Pichai 46
Apple Tim Cook 57
{Company} -> {CEO} (if we know the company, we know its CEO's name)
{CEO} -> {Age} If we know the CEO, we know the Age
Therefore, according to the rule of rule of transitive dependency:
{Company} -> {Age} should hold, that makes sense because if we know the company name, we can know his age.
Department of Computer Science Database Lab Manual
xlix | P a g e
Note: You need to remember that transitive dependency can only occur in a relation of three or more attributes.

Advantages of Functional Dependency

 Functional Dependency avoids data redundancy. Therefore, same data do not repeat at multiple locations in that database
 It helps you to maintain the quality of data in the database
 It helps you to defined meanings and constraints of databases
 It helps you to identify bad designs
 It helps you to find the facts regarding the database design

Department of Computer Science Database Lab Manual


l|Page

In-Lab

Tasks 1
 Functional dependencies for FirstName (determinant) in Customer relation.
 Full functional dependencies in Customer relation, if exists. If does not exist, explain in detail, how it does not exist.
 All possible functional and full functional dependencies that exist in OrderItem relation.

Post-Lab

Tasks 1
 Write a detailed report for the in-lab tasks along with all steps taken to achieve above task.

Department of Computer Science Database Lab Manual


li | P a g e

Practical 10
Normalization
Objective
In this lab students will learn about Normalization in database.
Introduction
Normalization is the process of organizing data in a database. This includes creating tables and establishing relationships between those tables according to rules
designed both to protect the data and to make the database more flexible by eliminating redundancy and inconsistent dependency.
Redundant data wastes disk space and creates maintenance problems. If data that exists in more than one place must be changed, the data must be changed in
exactly the same way in all locations. A customer address change is much easier to implement if that data is stored only in the Customers table and nowhere else
in the database.
What is an "inconsistent dependency"? While it is intuitive for a user to look in the Customers table for the address of a particular customer, it may not make
sense to look there for the salary of the employee who calls on that customer. The employee's salary is related to, or dependent on, the employee and thus should
be moved to the Employees table. Inconsistent dependencies can make data difficult to access because the path to find the data may be missing or broken.
There are a few rules for database normalization. Each rule is called a "normal form." If the first rule is observed, the database is said to be in "first normal form."
If the first three rules are observed, the database is considered to be in "third normal form." Although other levels of normalization are possible, third normal form
is considered the highest level necessary for most applications.
As with many formal rules and specifications, real world scenarios do not always allow for perfect compliance. In general, normalization requires additional
tables and some customers find this cumbersome. If you decide to violate one of the first three rules of normalization, make sure that your application anticipates
any problems that could occur, such as redundant data and inconsistent dependencies.

Department of Computer Science Database Lab Manual


lii | P a g e

The following descriptions include examples.


First normal form
 Eliminate repeating groups in individual tables.
 Create a separate table for each set of related data.
 Identify each set of related data with a primary key.
Do not use multiple fields in a single table to store similar data. For example, to track an inventory item that may come from two possible sources, an inventory
record may contain fields for Vendor Code 1 and Vendor Code 2.
What happens when you add a third vendor? Adding a field is not the answer; it requires program and table modifications and does not smoothly accommodate
a dynamic number of vendors. Instead, place all vendor information in a separate table called Vendors, then link inventory to vendors with an item number key,
or vendors to inventory with a vendor code key.
Second normal form
 Create separate tables for sets of values that apply to multiple records.
 Relate these tables with a foreign key.
Records should not depend on anything other than a table's primary key (a compound key, if necessary). For example, consider a customer's address in an
accounting system. The address is needed by the Customers table, but also by the Orders, Shipping, Invoices, Accounts Receivable, and Collections tables. Instead
of storing the customer's address as a separate entry in each of these tables, store it in one place, either in the Customers table or in a separate Addresses table.
Third normal form
 Eliminate fields that do not depend on the key.
Values in a record that are not part of that record's key do not belong in the table. In general, anytime the contents of a group of fields may apply to more than a
single record in the table, consider placing those fields in a separate table.
For example, in an Employee Recruitment table, a candidate's university name and address may be included. But you need a complete list of universities for
group mailings. If university information is stored in the Candidates table, there is no way to list universities with no current candidates. Create a separate
Universities table and link it to the Candidates table with a university code key.
EXCEPTION: Adhering to the third normal form, while theoretically desirable, is not always practical. If you have a Customers table and you want to eliminate
all possible interfiled dependencies, you must create separate tables for cities, ZIP codes, sales representatives, customer classes, and any other factor that may
be duplicated in multiple records. In theory, normalization is worth pursuing. However, many small tables may degrade performance or exceed open file and
memory capacities.
It may be more feasible to apply third normal form only to data that changes frequently. If some dependent fields remain, design your application to require the
user to verify all related fields when any one is changed.

Department of Computer Science Database Lab Manual


liii | P a g e

Normalizing an example table


These steps demonstrate the process of normalizing a fictitious student table.

1. Not a Normalized table:

TABLE 1

Student# Advisor Adv-Room Class1 Class2 Class3

1022 Jones 412 101-07 143-01 159-02

4123 Smith 216 101-07 143-01 179-04

2. First normal form: No repeating groups

Tables should have only two dimensions. Since one student has several classes, these classes should be listed in a separate table. Fields Class1, Class2, and
Class3 in the above records are indications of design trouble.
Spreadsheets often use the third dimension, but tables should not. Another way to look at this problem is with a one-to-many relationship, do not put the
one side and the many side in the same table. Instead, create another table in first normal form by eliminating the repeating group (Class#), as shown below:
TABLE 2

Student# Advisor Adv-Room Class#

1022 Jones 412 101-07

1022 Jones 412 143-01

1022 Jones 412 159-02

4123 Smith 216 101-07

4123 Smith 216 143-01

Department of Computer Science Database Lab Manual


liv | P a g e
TABLE 2

Student# Advisor Adv-Room Class#

4123 Smith 216 179-04

3. Second normal form: Eliminate redundant data

Note the multiple Class# values for each Student# value in the above table. Class# is not functionally dependent on Student# (primary key), so this
relationship is not in second normal form.
The following tables demonstrate second normal form:
Students:
TABLE 3

Student# Advisor Adv-Room

1022 Jones 412

4123 Smith 216

Registration:
TABLE 4

Student# Class#

1022 101-07

1022 143-01

1022 159-02

4123 101-07

4123 143-01

Department of Computer Science Database Lab Manual


lv | P a g e
TABLE 4

Student# Class#

4123 179-04

4. Third normal form: Eliminate data not dependent on key

In the last example, Adv-Room (the advisor's office number) is functionally dependent on the Advisor attribute. The solution is to move that attribute from
the Students table to the Faculty table, as shown below:
Students:
TABLE 5

Student# Advisor

1022 Jones

4123 Smith

Faculty:
TABLE 6

Name Room Dept

Jones 412 42

Smith 216 42

Department of Computer Science Database Lab Manual


lvi | P a g e

In-Lab

Task 1
 Normalize given table up to 3NF.

STU_ID COR_ID STU_Name COR_name Grade Faculty Teacher_Phone

1 CS012 Faqeer Database A Hakeem 111

1 CS018 Faqeer Program B Yaqoob 150

2 CS012 Jalil Database A Hakeem 111

3 CS012 Sameer Database B Hakeem 111

4 CS018 Bhola Program A Yaqoob 150

4 CS012 Bhola Database B Hakeem 111

 Create the normalized database namely Lab10DB<YourFirstName> in Microsoft SQL Server at your workstations.
Post-Lab Task

Department of Computer Science Database Lab Manual


lvii | P a g e

Post-Lab

Task 1
Write a detailed report for the in-lab tasks along with all steps taken to achieve above task.

Department of Computer Science Database Lab Manual


lviii | P a g e

Practical 11
Concurrency control
Objective
In this lab students will learn about Concurrency control in database.

Introduction
Concurrency Control in Database Management System is a procedure of managing simultaneous operations without conflicting with each other. It ensures
that Database transactions are performed concurrently and accurately to produce correct results without violating data integrity of the respective Database.
Concurrent access is quite easy if all users are just reading data. There is no way they can interfere with one another. Though for any practical Database, it
would have a mix of READ and WRITE operations and hence the concurrency is a challenge.

DBMS Concurrency Control is used to address such conflicts, which mostly occur with a multi-user system. Therefore, Concurrency Control is the most im-
portant element for proper functioning of a Database Management System where two or more database transactions are executed simultaneously, which require
access to the same data.

Potential problems of Concurrency


Here, are some issues which you will likely to face while using the DBMS Concurrency Control method:

 Lost Updates occur when multiple transactions select the same row and update the row based on the value selected
 Uncommitted dependency issues occur when the second transaction selects a row which is updated by another transaction (dirty read)
 Non-Repeatable Read occurs when a second transaction is trying to access the same row several times and reads different data each time.
 Incorrect Summary issue occurs when one transaction takes summary over the value of all the instances of a repeated data-item, and second transac-
tion update few instances of that specific data-item. In that situation, the resulting summary does not reflect a correct result.

Department of Computer Science Database Lab Manual


lix | P a g e

Why use Concurrency method?


Reasons for using Concurrency control method is DBMS:

 To apply Isolation through mutual exclusion between conflicting transactions


 To resolve read-write and write-write conflict issues
 To preserve database consistency through constantly preserving execution obstructions
 The system needs to control the interaction among the concurrent transactions. This control is achieved using concurrent-control schemes.

Concurrency Control Protocols


Different concurrency control protocols offer different benefits between the amount of concurrency they allow and the amount of overhead that they impose.
Following are the Concurrency Control techniques in DBMS:

 Lock-Based Protocols
 Two Phase Locking Protocol
 Timestamp-Based Protocols
 Validation-Based Protocols

Department of Computer Science Database Lab Manual


lx | P a g e

In-Lab

Task 1
For the given database (Lab6DB)
 Write an SQL Server Transaction for purchase of single product
 Dummy test values first to be stored in temporary variables and the temporary variables be used as input to transaction.
 DECLARE {@LOCAL_VARIABLE data_type [ = value]}
 Necessary changes must be reflected in OrderItem, Order, Customer, and Product, at successful transaction.

Post-Lab

Task 1
Write a report on all steps taken to achieve above task with screenshots of each step and query code.

Department of Computer Science Database Lab Manual

You might also like