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

Dbms Lab 1 To 9 My Muneer

The document provides instructions for installing Microsoft SQL Server and SQL Server Management Studio. It outlines 7 steps for installing SQL Server which include selecting the installation type, accepting license terms, selecting the installation location, and verifying a successful installation. It then describes 4 steps for installing SQL Server Management Studio to manage the SQL Server database. The purpose of the lab is to learn how to install these applications and understand the basic system requirements.

Uploaded by

Muneer King
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Dbms Lab 1 To 9 My Muneer

The document provides instructions for installing Microsoft SQL Server and SQL Server Management Studio. It outlines 7 steps for installing SQL Server which include selecting the installation type, accepting license terms, selecting the installation location, and verifying a successful installation. It then describes 4 steps for installing SQL Server Management Studio to manage the SQL Server database. The purpose of the lab is to learn how to install these applications and understand the basic system requirements.

Uploaded by

Muneer King
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 85

LAB MANUAL : [ DATABASE management SYSTEM ]

LAB NO. 01 DATE: __/__/2023


INSTALLATION OF MICROSOFT SQL SERVER AND SQL SERVER
MANAGEMENT STUDIO

Lab outcomes:

After completing this lab, students will be able to:

 Know about Microsoft SQL server.


 Know about SQL server management studio.
 Learned about the installation of Microsoft SQL server, and SQL server management
studio.

Corresponding CLO and PLO:

 CLO-1, PLO-3(Design and Development solutions)

SOFTWARE REQUIRED:

 Microsoft SQL server


 SQL server management studio

Theory:

Microsoft SQL server:


SQL Server is a relational database management system (RDBMS) developed by Microsoft.
It is primarily designed and developed to compete with MySQL and Oracle database. SQL
Server supports ANSI SQL, which is the standard SQL (Structured Query Language)
language.
SQL server management studio:

SQL Server Management Studio (SSMS) is a windows software or a client tool used to
connect and work with our SQL Server from a graphical interface instead of using the
command line. it allows DBAs and database developers to configure, manage,
and administer all components within SQL Server. Its main functionality is to create
databases and tables, execute SQL queries for inserting, updating, and deleting data, creating
and managing stored procedures, triggers, views, and cursors. It also enables us to set
privileges (securities) on databases and their objects.

1|Page SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Installation of Microsoft SQL server and SQL server management studio:

1. Go to the Microsoft SQL server setup folder and then double click on the setup of
SQLserver.

Figure 1 setup folder


2. Once you open the Microsoft
SQL server setup file so three option will be apper BASIC,
CUSTOM, and DOWNLOAD MEDIA as you can see. So click on then click on the
BASIC option.

Figure 2 installation type

2|Page SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

3. NEXT, when you click on the basic, so Microsoft SQL server license terms’ screen
appear leave it as it is and click on the ACCEPT.

Figure 3 SQL server license terms


4. When you accept the agreement so then a new window will apper in which you can
change the installation location, but I leave it as default location and click on
INSTALL.

Figure 4SQL server installation location

3|Page SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

5. Once you click on install so downloading and installing progress screen will apper,
first the downloading of SQL server will start after the completion of downloading the
system will start installation.

Figure 5 Downloading and installation


6. So then installation has completed successfully’ screen will appear, here the instance
name is set as default.

Figure 6 installation completed

4|Page SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

7. Now to check that SQL server installed correctly so click on connect now if it
generate that notification its mean SQL server installed correctly.

Figure 7 SQL CMD


8. Now to install SQL server management studio click on the install SSMS so a new
window will apper then click on ‘install’ to install SSMS in the system.

Figure 8 SSMS installation

5|Page SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

9. Once you start the installation of the SSMS then wait until packages progress and overall progress not
complete.

Figure 9 SSMS installation progress


10. Now the setup is completed and click on CLOSE.

Figure 10 SSMS installed

6|Page SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

11. Now connect the management studion to the server by browsing the servername and
then laver the other things as default and then click on connect.

Figure 11 SQL server connect to SSMS


Now I will just show the server name by using Query.

Figure 12 SS

Observations:

In conclusion, this lab has equipped us with the knowledge and practical skills required to
install Microsoft SQL Server and SQL Server Management Studio. Understanding the system
requirements, installation steps, and security considerations is essential for anyone who
intends to work with SQL Server databases.

7|Page SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Rubrics:

Report not Plagiarized Requirements Observations Appropriate Correctly


submitted content are listed and are recorded computation drawn
presented or experimental along with s or conclusion
Laboratory incomplete procedure is detailed numerical with
Reports submission or presented procedure analysis is exact results
late performed and complete
report in all
respects
Category Ungraded Very Poor Poor Fair Good Excellent
Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

Absent Student failed Student Student Student Student


to develop a developed a developed a developed a excelled in
functional partially mostly fully developing
code or functional functional functional fully
complete the code and code and met code and functional
lab objective struggled to the lab met the lab code,
within the accomplish objective objective exceeding
simulation the lab within the within the expected
environment. objective simulation simulation results within
They exhibit within the environment, environment simulation
inadequate simulation achieving , achieving environment.
understanding environment. satisfactory expected They
Demonstrat
in They results. They results. demonstrate
ion
configuring, demonstrate exhibit They mastery in
operating, and minimal moderate demonstrate independently
executing the understanding proficiency in proficiency configuring,
simulation in configuring, in operating and
independently configuring, operating, and configuring, executing the
. operating, and executing the operating, simulation.
executing the simulation and
simulation independently executing
independently . the
. simulation
independent
ly.
Category Ungraded Very Poor Poor Fair Good Excellent

Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

8|Page SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

LAB NO: 02 DATE: __/__/2023


Introduction to DDL and DML

Lab outcomes:

After completing this lab, students will be able to:

 Understand DML and DDL

Corresponding CLO and PLO:

 CLO-1, PLO-3(Design and Development of Solutions)

SOFTWARE REQUIRED:

 SQL server and SSMS

Theory:

DDL:

It is used to communicate with database. DDL is used to:

 Create an object

 Alter the structure of an object

 To drop the object created. The commands used are:

DDL 1. Create

2. Alter

3. Drop

4. Truncate

9|Page SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

It is used to create a table


Syntax:
Create table tablename (column_name1 data_ type constraints,
column_name2 data_ type constraints …)
Example:
CREATE TABLE Emp (EmpNo int, EName VarChar(15), Job
Char(10) UNIQUE, primary key(EmpNo) );
Rules:

1. SQL reserved words cannot be used.


Create Table
2. Underscore, numerals, letters are allowed but not blank
space.

3. Maximum length for the table name is 30 characters.

4. 2 different tables should not have same name.

5. We should specify a unique column name.

6. We should specify proper data type along with width.

7. We can include “not null” condition when needed. By


default it is ‘null’.

Alter command is used to:

1. Add a new column.

2. Modify the existing column definition.


ALTER TABLE 3. To include or drop integrity constraint

Syntax: alter table tablename add/modify (attribute


datatype(size));
Example:

1. Alter table emp add phone_no char (20);

2. ALTER TABLE Persons ALTER COLUMN


DateOfBirth year;

3. ALTER TABLE EMP ADD CONSTRAINT Pkey1


PRIMARY KEY (EmpNo)

10 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

4. ALTER TABLE emp DROP COLUMN age;

It will delete the table structure provided the table


DROP TABLE
Example: drop table prog20; Here prog20 is table name

If there is no further use of records stored in a table and the


structure has to be retained, then the records alone can be deleted.
TRUNCATE TABLE
Syntax: TRUNCATE TABLE <TABLE NAME>;
Example: Truncate table customer;

An integrity constraint is a mechanism used by RDBMS to


prevent invalid data entry into the table. It has enforcing the rules
for the columns in a table.
INTEGRITY
The types of the integrity constraints are:
CONSTRAINT
a) Domain Integrity

b) Entity Integrity

c) Referential Integrity

This constraint sets a range and any violations that takes place will
prevent the user from performing the manipulation that caused the
breach. It includes:
Not Null constraint:
While creating tables, by default the rows can have null value. the
enforcement of not null constraint in a table ensure that the table
contains values.
Example: Create table cust(custid number(6) not null, name
char(10)); Alter table cust modify (name not null);
This command will ensure that the user enters a value for the
Domain Integrity custid, name columns on the cust table, failing which it returns an
error message.
Check Constraint
Check constraint can be defined to allow only a particular range of
values. when the manipulation violates this constraint, the record
will be rejected.
Example:
Create table student (regno number (6), mark number (3)
11 | P a g e SUBMITTED TO: Mr. Rehmat
LAB MANUAL : [ DATABASE management SYSTEM ]

constraint b check
(mark >=0 and mark <=100));
Alter table student add constraint b2 check (length(regno<=4));

12 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Maintains uniqueness in a record. An entity represents a


table and each row of a table represents an instance of that
entity. To identify each row in a table uniquely we need to
use this constraint. There are 2 entity constraints:

Entity Integrity a) Unique key constraint

It is used to ensure that information in the column for each


record is unique, as with telephone or driver’s license
numbers. It prevents the duplication of value with rows of a
specified column in a set of column. A column defined with
the constraint can allow null value.
Example:
Create table cust(custid number(6) constraint uni unique,
name char(10));
PRIMARY KEY CONSTRAINT

b) A primary key avoids duplication of rows and does not


allow null values. It is used to uniquely identify each row
in a table. These values should never be changed and
should never be null.
A table should have only one primary key.
Example;
Create table stud(regno number(6) constraint primary key,
name char(20));
Referential Integrity
It enforces relationship between tables. To establish parent-
child relationship between 2 tables having a common
Entity Integrity
column definition, we make use of this constraint. To
implement
this, we should define the column in the parent table as
primary key and same column in the child table as foreign
key referring to the corresponding parent entry.
Example:
CREATE TABLE Orders (
OrderID int NOT NULL, OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),

13 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

FOREIGN KEY (PersonID) REFERENCES


Persons(PersonID)
);

DML:
What Does Data Manipulation Language (DML) Mean?
A data manipulation language (DML) is a family of computer languages including commands
permitting users to manipulate data in a database. This manipulation involves inserting data
into database tables, retrieving existing data, deleting data from existing tables and modifying
existing data. DML is mostly incorporated in SQL databases.

DML resembles simple English language and enhances efficient user interaction with the
system. The functional capability of DML is organized in manipulation commands like
SELECT, UPDATE, INSERT INTO and DELETE FROM, as described below:

 SELECT: This command is used to retrieve rows from a table. The syntax is
SELECT [column name(s)] from [table name] where [conditions]. SELECT is the
most widely used DML command in SQL.
 UPDATE: This command modifies data of one or more records. An update command
syntax is UPDATE [table name] SET [column name = value] where [condition].
 INSERT: This command adds one or more records to a database table. The insert
command syntax is INSERT INTO [table name] [column(s)] VALUES [value(s)].
 DELETE: This command removes one or more records from a table according to
specified conditions. Delete command syntax is DELETE FROM [table name] where
[condition].

14 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Lab Task No.01


Q: Create the following tables
1. Client Master
Column Data type
Client No. Varchar2
Name Varchar2
Address Varchar2
City Varchar2
Province Varchar2
Contact No. Number / Int
Pin code Int

Data for Client Master

No. Name Address City Province Contact Pin code


0001 Ahmed ABC Quetta Balochistan +9322-4400054 87300
0002 Ali XYZ Quetta Balochistan +9332-3311231 87300
0003 Umer ETC Karachi Sindh +9233-1673215 47003
0004 Naveen ETC Islamabad Punjab +9234-5613674 36002
0005 Rizwan ETC Multan KPK +9233-0432454 35532
2. Product Master

Column Data type


Product_no Varchar2
Description Varchar2
Profit_percent Varchar2
Unit_measure Number / Int
Qty_on_hand Number / Int
Sell_price Number / Int
Cost_price Number / Int
Data for Product Master:

Product no Description Unit measure Qty_on_hand Cost Price Sell Price Profit %
P00001 1.44floppies 100 20 500 525 5
P03453 Monitors 10 3 11200 12000 6
P06734 Mouse 20 5 500 1050 5
P07865 1.22 floppies 100 20 500 525 5
P07868 Keyboards 10 3 3050 3150 2
P07885 CD Drive 10 3 5100 5250 2.5

Implement the following tables in new Query and attached screenshot of your code and
output
Clint Master:

15 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 13 Client Master Query

Figure 14 Client Master TBL


Product Master:

Figure 15 Product Master Query

Figure 16 Product Master TBL

16 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Lab Task No.02


On the basis of above two tables of DML answer the following Questions.
1. Find out the names of all the clients.
Select C_Name from table_name
2. Retrieve the list of names and cities of all the clients.
Select C_Name, C_City from table_name
3. List the various products available from the product master table.
Select Description from table_name where QTY_ON_HAND >1
4. List all the clients who are located in Quetta.
Select C_Name from table_name where C_city = ‘Quetta’
5. Display the information for client no 0001 and 0002.
Select C_num = 0001, C_num = 0002 from table_name
6. Find the products with description as ‘1.44 drives’ and ‘1.22 Drive’.
Select description = 1.44 drive, description = 1.22 drive from table_name
7. Find all the products whose sell price is greater than 5000.
Select description from table_name where sell_price > 5000
8. Find the list of all clients who stay in in city ‘Karachi’ or city Islamabad’.
Select C_Name form table_name where C_City = ‘Karachi’ or C_City = ‘Islamabad’
9. Find the product whose selling price is greater than 2000 and less than or equal to
5000.
Select description from table_name where sell_price > 200 and sell_price <= 5000
10. List the name, city and province of clients not in the province of ‘Balochistan’.
Select C_Name, city, Province from table_name where Province != ‘Balochistan’

Conclusion:

In conclusion, understanding the distinction between DDL and DML is fundamental for
anyone working with relational databases and SQL. DDL is the language for defining and
managing the database structure, while DML is used for interacting with the data itself. Both
are essential tools in the world of database management, and a solid grasp of these concepts
is crucial for designing, maintaining, and working with databases effectively. This lab has
provided a strong foundation for further exploration and practical application of DDL and
DML in the context of database management.

17 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Rubrics:

Report not Plagiarized Requirements Observations Appropriate Correctly


submitted content are listed and are recorded computation drawn
presented or experimental along with s or conclusion
Laboratory incomplete procedure is detailed numerical with
Reports submission or presented procedure analysis is exact results
late performed and complete
report in all
respects
Category Ungraded Very Poor Poor Fair Good Excellent
Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

Absent Student failed Student Student Student Student


to develop a developed a developed a developed a excelled in
functional partially mostly fully developing
code or functional functional functional fully
complete the code and code and met code and functional
lab objective struggled to the lab met the lab code,
within the accomplish objective objective exceeding
simulation the lab within the within the expected
environment. objective simulation simulation results within
They exhibit within the environment, environment simulation
inadequate simulation achieving , achieving environment.
understanding environment. satisfactory expected They
Demonstrat
in They results. They results. demonstrate
ion
configuring, demonstrate exhibit They mastery in
operating, and minimal moderate demonstrate independently
executing the understanding proficiency in proficiency configuring,
simulation in configuring, in operating and
independently configuring, operating, and configuring, executing the
. operating, and executing the operating, simulation.
executing the simulation and
simulation independently executing
independently . the
. simulation
independent
ly.
Category Ungraded Very Poor Poor Fair Good Excellent

Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

18 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

19 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

LAB NO: 03 DATE: __/__/2023


HOW TO CREATE TABLE IN MS SQL SERVER

Lab outcomes:

After completing this lab, students will be able to:

 Know about Microsoft SQL server


 Know about SQL server management studio
 Create table in SQL server

Corresponding CLO and PLO:

 CLO-1, PLO-3(Design and Development solutions)

SOFTWARE REQUIRED:

 Microsoft SQL server


 SQL server management studio

Theory:

In Microsoft SQL Server, a database table is a structured object that stores data in a tabular
format. Tables are the fundamental building blocks of a relational database system, and they
play a crucial role in organizing and storing data efficiently. In this lab, you will learn how to
create tables in MS SQL Server, define their structure, and set constraints to ensure data
integrity.
Table Structure:
Before you create a table, it's essential to understand the structure of a table and its
components:
1. Table Name: Each table in SQL Server must have a unique name within the
database. The table name should be descriptive and indicative of the data it will store.
2. Columns (Fields): Tables consist of one or more columns, also known as fields. Each
column defines the type of data it can hold (e.g., text, numbers, dates) and can have
various constraints such as NOT NULL, unique, or primary key constraints.
3. Data Types: SQL Server provides a wide range of data types to define the kind of
data that can be stored in each column, such as INT, VARCHAR, DATETIME, etc.
4. Constraints: Constraints are rules that you can apply to columns to maintain data
integrity. Common constraints include PRIMARY KEY, FOREIGN KEY, UNIQUE,
and CHECK constraints.

20 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 17 Simple table queries


 table_name: The name of the table you want to create.
 column1, column2, etc.: The names of the columns in the table.
 datatype: The data type for each column.
 constraint: Optional constraints for each column.

Figure 18 Example table


In this example, we create a table named "Students" with columns for student ID, first name,
last name, birth date, and email. We've applied various constraints to ensure data integrity.
Creating tables is a fundamental skill when working with SQL Server databases. It forms the
basis for organizing and storing data effectively. In this lab, you will practice creating tables
with different column types and constraints to gain a better understanding of this essential
database operation.

Creating Tables:
To create a table in MS SQL Server, you will typically use the CREATE TABLE statement.
Here is the basic syntax:
Syntax
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype );

21 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

CREATE TABLE is the keyword telling the database system what you want to do. In this
case, you want to create a new table. The unique name or identifier for the table follows the
CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data type it
is. The syntax becomes clearer with the following example.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement. You can check the complete details at Create Table
Using another Table.

 1st we will create table using create command then insert in the bractkets the data
type of all the columns in the table.

Figure 01: columns of table

 Then put the value into the tables using insert and set command.

22 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 02: inserting values to table


 As the table is created check it using SELECT command either the inserted values
are lies in the column or not

Figure 03: use of select command

23 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Lab Task 1

Figure 19 table Form

Figure 20 script form

Lab Task 2
Create two tables one for Employee (EmpID, EmpName, EmpSalary, EmpEmail,
EmpDateOfBirth, EmpDepartment) and Second for department (DepID, DepName, DepHod,
DepEmail) insert data into each table and take screenshots. Set the data types and also apply
constraints:
Employee Table:

Figure 21 Employee table

24 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 22 Inserting Values in Employee table


Department Table:

Figure 23 Department table

25 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Conclusion:

In conclusion, the ability to create tables in Microsoft SQL Server is a fundamental skill for
anyone working with relational databases. This lab has equipped you with the knowledge and
practical experience needed to define table structures, choose data types, and establish
constraints. Understanding the SQL syntax for table creation and the importance of data
integrity mechanisms is essential for successful database design and management. This lab
serves as a solid foundation for further exploration of database development and
administration in SQL Server.

26 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Rubrics:

Report not Plagiarized Requirements Observations Appropriate Correctly


submitted content are listed and are recorded computation drawn
presented or experimental along with s or conclusion
Laboratory incomplete procedure is detailed numerical with
Reports submission or presented procedure analysis is exact results
late performed and complete
report in all
respects
Category Ungraded Very Poor Poor Fair Good Excellent
Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

Absent Student failed Student Student Student Student


to develop a developed a developed a developed a excelled in
functional partially mostly fully developing
code or functional functional functional fully
complete the code and code and met code and functional
lab objective struggled to the lab met the lab code,
within the accomplish objective objective exceeding
simulation the lab within the within the expected
environment. objective simulation simulation results within
They exhibit within the environment, environment simulation
inadequate simulation achieving , achieving environment.
understanding environment. satisfactory expected They
Demonstrat
in They results. They results. demonstrate
ion
configuring, demonstrate exhibit They mastery in
operating, and minimal moderate demonstrate independently
executing the understanding proficiency in proficiency configuring,
simulation in configuring, in operating and
independently configuring, operating, and configuring, executing the
. operating, and executing the operating, simulation.
executing the simulation and
simulation independently executing
independently . the
. simulation
independent
ly.
Category Ungraded Very Poor Poor Fair Good Excellent

Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

27 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

LAB NO: 04 DATE: __/__/2023


HOW TO CREATE PRIMARY and FOREIGN KEYS IN MS SQL
SERVER

Lab outcomes:

After completing this lab, students will be able to:

 Know about Microsoft SQL server


 Know about SQL server management studio
 Create table in SQL server
 Create primary and foreign keys

Corresponding CLO and PLO:

 CLO-1, PLO-3(Design and Development solutions)

SOFTWARE REQUIRED:

 Microsoft SQL server


 SQL server management studio

Theory:

What is a Primary Key in SQL?

A Primary key is a unique column we set in a table to easily identify and locate data in
queries. A table can have only one primary key. The primary key column has a unique value
and doesn’t store repeating values. A Primary key can never take NULL values.
For example, in the case of a student when identification needs to be done in the class, the
roll number of the student plays the role of Primary key.
Similarly, when we talk about employees in a company, the employee ID is functioning as
the Primary key for identification.
Let us now understand the Syntax of creating the table with the Primary key specified.
Syntax:

CREATE TABLE tableName (


col1 int NOT NULL,
col2 varchar(50) NOT NULL,
col3 int,
…………….
PRIMARY KEY (col1) );

28 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

What is a Foreign key in SQL?


A Foreign key is beneficial when we connect two or more tables so that data from both can
be put to use parallel. A foreign key is a field or collection of fields in a table that refers to the
Primary key of the other table. It is responsible for managing the relationship between the
tables.
The table which contains the foreign key is often called the child table, and the table whose
primary key is being referred by the foreign key is called the Parent Table.
For example: When we talk about students and the courses they have enrolled in, now if we
try to store all the data in a single table, the problem of redundancy arises.
To solve this table, we make two tables, one the student detail table and the other department
table. In the student table, we store the details of students and the courses they have enrolled
in.
And in the department table, we store all the details of the department. Here the courseId acts
as the Primary key for the department table whereas it acts as the Foreign key in the student
table.
Syntax:

CREATE TABLE childTable (


col1 int NOT NULL,
col2 int NOT NULL,
col3 int,
………...
PRIMARY KEY (col1),
FOREIGN KEY (col3) REFERENCES parentTable(parent_Primary_key)
);

Creation of Parent Table DataFlair

Query:
CREATE TABLE DataFlair(

emp_id varchar(5) NOT NULL,

name varchar(50),

location varchar(50),

experience int,

PRIMARY KEY(emp_id));

29 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Output:

Lab Task
Create a Primary Key and Foreign Key for two tables i.e. Student’s Table and Subject’s
Table also add the procedure (query) and output screenshots with the lab task.

Figure 24 Student & Subject table

30 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 25 Relation B/w Student and Subject

Figure 26 Result of Student and Subject

Conclusion:

In conclusion, understanding how to create primary and foreign keys is essential for anyone
working with Microsoft SQL Server and relational databases. These keys are fundamental
tools for maintaining data integrity, establishing relationships between tables, and ensuring
the accuracy and consistency of data. This lab provides a solid foundation for further
exploration of database design, management, and optimization within SQL Server. By
implementing primary and foreign keys effectively, you are better equipped to build robust
and reliable database systems.

31 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Rubrics:
Report not Plagiarized Requirements Observations Appropriate Correctly
submitted content are listed and are recorded computation drawn
presented or experimental along with s or conclusion
Laboratory incomplete procedure is detailed numerical with
Reports submission or presented procedure analysis is exact results
late performed and complete
report in all
respects
Category Ungraded Very Poor Poor Fair Good Excellent
Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

Absent Student failed Student Student Student Student


to develop a developed a developed a developed a excelled in
functional partially mostly fully developing
code or functional functional functional fully
complete the code and code and met code and functional
lab objective struggled to the lab met the lab code,
within the accomplish objective objective exceeding
simulation the lab within the within the expected
environment. objective simulation simulation results within
They exhibit within the environment, environment simulation
inadequate simulation achieving , achieving environment.
understanding environment. satisfactory expected They
Demonstrat
in They results. They results. demonstrate
ion
configuring, demonstrate exhibit They mastery in
operating, and minimal moderate demonstrate independently
executing the understanding proficiency in proficiency configuring,
simulation in configuring, in operating and
independently configuring, operating, and configuring, executing the
. operating, and executing the operating, simulation.
executing the simulation and
simulation independently executing
independently . the
. simulation
independent
ly.
Category Ungraded Very Poor Poor Fair Good Excellent

Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

32 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

LAB NO: 05 DATE: __/__/2023


SQL Queries – part 1(Select, select Distinct, where, AND, Or, NOT, Order
By, insert into)

Lab outcomes:

After completing this lab, students will be able to:


 Learn about different Queries such as Select, select Distinct, where, AND, Or, NOT, Order By,
insert into

Corresponding CLO and PLO:

 CLO-1, PLO-3(Design/Development of Solutions)

SOFTWARE REQUIRED:

 Microsoft SQL server


 SQL server management studio

Theory:

Queries
Select statement:

The SELECT statement is used to select data from a database. The data returned is stored in a
result table, called the result-set.

Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If
you want to select all the fields available in the table, use the following syntax:
Example:
select name from student;

Figure 27Select statement


33 | P a g e SUBMITTED TO: Mr. Rehmat
LAB MANUAL : [ DATABASE management SYSTEM ]

Select distinct
The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only want
to list the different (distinct) values.

Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
Example
select DISTINCT city from student;

Figure 28 Select distinct

Where

The WHERE clause is used to filter records. It is used to extract only those records that fulfill a
specified condition.

Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
select name from student
where
city = 'quetta';

Figure 29 Where
34 | P a g e SUBMITTED TO: Mr. Rehmat
LAB MANUAL : [ DATABASE management SYSTEM ]

AND, OR, NOT operators:

The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one condition:

 The AND operator displays a record if all the conditions separated by AND are
TRUE.
 The OR operator displays a record if any of the conditions separated by OR is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.

AND syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
Example
select name from student
where
city = 'quetta' AND grade = 'A';

Figure 30 AND syntax

OR syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
Example;
select name from student
where
city = 'quetta' OR grade = 'A' OR city = 'karachi';

Figure 31 OR syntax
35 | P a g e SUBMITTED TO: Mr. Rehmat
LAB MANUAL : [ DATABASE management SYSTEM ]

NOT syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Example
select * from student
where
NOT city = 'quetta';

Figure 32 NOT syntax

Order by

The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.

Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Example
select * from student
ORDER BY name;

Figure 33 Order by
36 | P a g e SUBMITTED TO: Mr. Rehmat
LAB MANUAL : [ DATABASE management SYSTEM ]

Insert into
The INSERT INTO statement is used to insert new records in a table.
Syntax

It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query. However, make sure the order of the values is in the same
order as the columns in the table. Here, the INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Example:
insert into student
values (50347,'khan',20,'afghwanistan', 'kabul', 'A');

Figure 34 Insert into

Create the above table in SSMS in the give answer to each task.

LAB TASK 1
Q: Make a table for employees with the columns: Employees Id, Name, Age,
Department, City, DateOfBirth, and Salary filled with some values. Use the SQL
queries listed above, and attached the screenshots of your code and outputs.
Table:

37 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 35 Employee Table

Result:

Figure 36 Result of Employee table

LAB TASK 2
Let's start by grabbing all of the data in one table. We have a table
called family_members that is shown below. In order to grab all of that data, please run
the following command: SELECT * FROM family_members;
Table:

38 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 37 Family Members Table


Result:

Figure 38 Family Member Result


LAB TASK 3
SELECT * grabs all fields (called columns) in a table. If we only wanted to see the name
and num_books_read columns, we would type
SELECT name, num_books_read FROM family_members;
Table:

39 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 39 Table
Result:

Figure 40 Result

LAB TASK 4
SELECT * FROM family_members WHERE species = 'human';
Note that the quotes have to be around the word human, as it is an explicit value, unlike
a keyword such as WHERE.

Table:

40 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 41 Species
Result:

Figure 42 Result

LAB TASK 5
SQL accepts various inequality symbols, including:
= "equal to"
> "greater than"
< "less than"
>= "greater than or equal to"
<= "less than or equal to"
Result:

Figure 43 Result:

LAB TASK 6

41 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Can you return all rows in family_members where num_books_read is a value greater
or equal to 150?

Figure 44 Table
Result:

Figure 45 Result

LAB TASK 7
Can you find all of Pickles' friends that are dogs or under the height of 45cm?
Table:

Figure 46 Command

Result:

42 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 47 Result

LAB TASK 8
Can you run a query that sorts the friends_of_pickles by height_cm in descending order?
Table:

Figure 48 descending Command


Result:

Figure 49 Result:

Conclusion:

In this lab I have learned how to retrieve and filter data using the `SELECT` statement,
including the use of `SELECT DISTINCT` to obtain unique values. The `WHERE` clause
helps us filter data based on specific conditions, and logical operators like `AND`, `OR`, and
`NOT` allow us to create complex conditions. Sorting of results was demonstrated using the
`ORDER BY` clause.

43 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Rubrics

Report not Plagiarized Requirements Observations Appropriate Correctly


submitted content are listed and are recorded computation drawn
presented or experimental along with s or conclusion
Laboratory incomplete procedure is detailed numerical with
Reports submission or presented procedure analysis is exact results
late performed and complete
report in all
respects
Category Ungraded Very Poor Poor Fair Good Excellent
Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

Absent Student failed Student Student Student Student


to develop a developed a developed a developed a excelled in
functional partially mostly fully developing
code or functional functional functional fully
complete the code and code and met code and functional
lab objective struggled to the lab met the lab code,
within the accomplish objective objective exceeding
simulation the lab within the within the expected
environment. objective simulation simulation results within
They exhibit within the environment, environment simulation
inadequate simulation achieving , achieving environment.
understanding environment. satisfactory expected They
Demonstrat
in They results. They results. demonstrate
ion
configuring, demonstrate exhibit They mastery in
operating, and minimal moderate demonstrate independently
executing the understanding proficiency in proficiency configuring,
simulation in configuring, in operating and
independently configuring, operating, and configuring, executing the
. operating, and executing the operating, simulation.
executing the simulation and
simulation independently executing
independently . the
. simulation
independent
ly.
Category Ungraded Very Poor Poor Fair Good Excellent

Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

44 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

45 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Lab No. 07 Date: __/__/2023


SQL Queries – part 2 (Null values, update, delete, select top, Min, Max,
count, avg, sum, Like, wildcards)

Lab outcomes:

After completing this lab, students will be able to:


 Learn about different Queries such as Null values, update, delete, select top, Min,
Max, count, avg, sum, Like, wildcards

Corresponding CLO and PLO:

 CLO-1, PLO-3(Design/Development of Solutions)

SOFTWARE REQUIRED:

 Microsoft SQL Server Management studio.

Theory:

Queries
Null values:

A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a record without
adding a value to this field. Then, the field will be saved with a NULL value.

Syntax
We will have to use the IS NULL and IS NOT NULL operators
Is NULL syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;

Is NOT NULL syntax

46 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

SELECT column_names
FROM table_name

Example:
select name, city, grade
from student
where grade IS NOT NULL;

Update:

The UPDATE statement is used to modify the existing records in a table.

Update syntax

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example
UPDATE student
SET name = 'khan kakar', City= 'peshawar'
WHERE StudentID = 50348;

Delete statement:

47 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

The DELETE statement is used to delete existing records in a table.

Delete syntax

DELETE FROM table_name WHERE condition;


Example:
delete from student
where city = 'quetta';

Select top statement

The SELECT TOP clause is used to specify the number of records to return.

The SELECT TOP clause is useful on large tables with thousands of records. Returning a large
number of records can impact performance.

Select top syntax


SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
Example
select TOP 2 * from student;

48 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

MIN() and MAX function()

The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

MIN() syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Example:
SELECT MIN(age) AS Smallestage
FROM student;

MAX() syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Example;
SELECT MAX(age) AS largestage
FROM student;

Count() function
The COUNT() function returns the number of rows that matches a specified criterion.
Count syntax

49 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Example:
SELECT COUNT(StudentID)
FROM student;

AVG() function
The AVG() function returns the average value of a numeric column.
AVG() syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

Example:
SELECT AVG(age)
FROM student;

SUM() function
The SUM() function returns the total sum of a numeric column.
SUM syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Example:
SELECT SUM(age)

50 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

FROM student;

LIKE operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards often used in conjunction with the LIKE operator:

 The percent sign (%) represents zero, one, or multiple characters


 The underscore sign (_) represents one, single character

Like Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

Example:
SELECT * FROM student
WHERE name LIKE 'k%';

Wildcard characters:

A wildcard character is used to substitute one or more characters in a string.

Wildcard characters are used with the LIKE operator. The LIKE operator is used in
a WHERE clause to search for a specified pattern in a column.

Example:
SELECT * FROM student

51 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

WHERE city LIKE '%or%';

Lab Task:
1. Null Values:
 Task: Create a table named "Students" with columns for
"StudentID" (INT), "FirstName" (VARCHAR), and "LastName"
(VARCHAR). Insert a few records where some students have a
NULL value for their last name.
 Query: Write a SQL query to select all students with NULL last
names.

Figure 50 Task 1 code

52 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 51 Task 1 output

Figure 52 Task 1 condition

Figure 53 Task condition


2. Update:
 Task: Create a table named "Employees" with columns for
"Employee_ID" (INT) and "Salary" (DECIMAL). Update the
salary of an employee with a specific Employee_ID.
 Query: Write a SQL query to update the salary of an employee
with a given Employee_ID.

Figure 54 Task 2 code

53 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 55 Task 2 Output


3. Delete:
 Task: Create a table named "Customers" with columns for
"CustomerID" (INT) and "Name" (VARCHAR). Delete a customer
with a specific CustomerID.
 Query: Write a SQL query to delete a customer with a given
CustomerID.

Figure 56 Task 3 coding

Figure 57 Task 3 output

54 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 58 Task 3 output after delete command


4. Select Top:
 Task: Create a table named "Products" with columns for
"ProductID" (INT), "ProductName" (VARCHAR), and "Price"
(DECIMAL). Retrieve the top 5 most expensive products.
 Query: Write a SQL query to select the top 5 most expensive
products.

Figure 59 Task 4 coding

Figure 60 Task 4 coding part 2

55 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 61 Product TBL

Figure 62 Selecting Top 5 Expensive Products


5. Min and Max:
 Task: Create a table named "Orders" with columns for "OrderID" (INT) and
"TotalAmount" (DECIMAL). Find the minimum and maximum total order
amounts.
 Query: Write SQL queries to find the minimum and maximum total order
amounts.

Figure 63 Task 5 Queries

56 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 64 Orders TBL

Figure 65 Minimum order

Figure 66 Maximum order


6. Count, Avg, and Sum:
 Task: Create a table named "Sales" with columns for "ProductID" (INT) and
"QuantitySold" (INT). Calculate the total sales quantity, average sales
quantity, and the number of sales records.
 Query: Write SQL queries to calculate the total sales quantity, average sales
quantity, and the number of sales records.

Figure 67 Sales TBL

57 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 68 Sales TBL Queries

Figure 69 Output of Sales TBL

Figure 70 Queries output of Sales TBL


7. Like and Wildcards:
 Task: Create a table named "Products" with a "ProductName" column
(VARCHAR). Insert product names with various patterns (e.g., "Apple
iPhone," "Samsung Galaxy," "Dell Laptop").
 Query: Write SQL queries using the LIKE operator and wildcards to retrieve
products that match specific patterns (e.g., all products containing "iPhone").

58 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 71 Product TBL

Figure 72 Product TBL Queries

Figure 73 Product TBL and Queries Output


Conclusion:
The lab introduced us to the concepts of handling null values using the `IS NULL` and `IS
NOT NULL` conditions. We learned how to modify existing data in a database table using
the `UPDATE` statement. The DELETE statement was explored for removing records from a
table. The lab covered the `SELECT TOP` clause, allowing us to limit the number of rows
returned by a query. We gained an understanding of common aggregate functions such as
`MIN`, `MAX`, `COUNT`, `AVG`, and `SUM`. These functions are used to perform
calculations on data sets, enabling us to extract valuable insights from large datasets. The lab
introduced the `LIKE` operator and wildcards, such as `%` and `_`, which facilitate pattern
matching in SQL queries.

59 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Rubrics

Report not Plagiarized Requirements Observations Appropriate Correctly


submitted content are listed and are recorded computation drawn
presented or experimental along with s or conclusion
Laboratory incomplete procedure is detailed numerical with
Reports submission or presented procedure analysis is exact results
late performed and complete
report in all
respects
Category Ungraded Very Poor Poor Fair Good Excellent
Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

Absent Student failed Student Student Student Student


to develop a developed a developed a developed a excelled in
functional partially mostly fully developing
code or functional functional functional fully
complete the code and code and met code and functional
lab objective struggled to the lab met the lab code,
within the accomplish objective objective exceeding
simulation the lab within the within the expected
environment. objective simulation simulation results within
They exhibit within the environment, environment simulation
inadequate simulation achieving , achieving environment.
understanding environment. satisfactory expected They
Demonstrat
in They results. They results. demonstrate
ion
configuring, demonstrate exhibit They mastery in
operating, and minimal moderate demonstrate independently
executing the understanding proficiency in proficiency configuring,
simulation in configuring, in operating and
independently configuring, operating, and configuring, executing the
. operating, and executing the operating, simulation.
executing the simulation and
simulation independently executing
independently . the
. simulation
independent
ly.
Category Ungraded Very Poor Poor Fair Good Excellent

Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

60 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

61 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Lab No. 07 Date: __/__/2023


Joins in SQL

Lab outcomes:

After completing this lab, students will be able to:

 Know about “Join” in SQL Server.


 Be familiar with several types of "Joins"
 How to implement it using query.
 Why we use “Joins” in SQL Server.

Corresponding CLO and PLO:

 CLO-1, PLO-3(Design and Development solutions)

SOFTWARE REQUIRED:

 Microsoft SQL server


 SQL server management studio

Theory:

Join:
SQL Join statement is used to combine data or rows from two or more tables based on a
common field between them.
Inner Join:
An inner join is the one in which only those tuples are included that satisfy some conditions.
In this article, we will be using SQL Server to demonstrate the working of SQL Inner Join.

Figure 74

62 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Syntax of Inner Join:

Figure 75
How the INNER JOIN works:
1. Two or more tables are specified in the SQL query.
2. A condition is defined in the ON clause, which specifies the column(s) that should
match between the tables.
3. The tables are joined based on the matching column(s), and only the rows with
matching values are returned in the result set.
4. If there are multiple matching rows, the join returns a combination of those rows.
5. INNER JOIN can be used with additional conditions in the WHERE clause to further
filter the result set.
Left Join:
This join returns all rows from the table to the left of the join and matches rows from the
table to the right of the join. The result-set will contain null for rows for which there is no
matching row on the right side. LEFT OUTER JOIN is another name for LEFT JOIN.

Figure 76
Syntax of Left Join:

Figure 77
How the LEFT JOIN works:
1. The query begins by selecting the desired columns from the “table1” and “table2”.

63 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

2. It then specifies the LEFT JOIN clause to indicate that it'll be performing a LEFT
JOIN operation.
3. The ON keyword is used to specify the condition for joining the tables. It defines the
matching column(s) between the “table1” and “table2”.
4. The query executes the join operation by matching the values of the specified
column(s) in both tables.
5. If there is a match, the result set will contain the combined row with values from both
tables.
6. If there is no match, the result set will still include all rows from the table1, with
NULL values for the columns from the “table2”.
RIGHT JOIN:
In SQL, a right join returns all the records from the right table as well as the matching records
from the left table based on the join condition. It is also referred to as a right outer join.
According to one theory, the right join in SQL is most commonly used when we want to
prioritize the records from the right table while also including any matching records from the
left table. This means that even if there is no matching record in the left table, the result of a
right join will always include all of the records from the right table. The result will contain
NULL values for non-matching records from the left table.

Figure 78
Syntax of RIGHT JOIN:

Figure 79
How the RIGHT JOIN works:
1. Start by identifying the two tables you want to join. Let's call them Table 1 and Table
2.
2. Specify the join condition using the ON keyword. It determines how the records
should be matched between the two tables. For example, if you want to join based on
a common column called "id", the join condition could be "Table1.id = Table2.id".

64 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

3. Begin the SQL query with the SELECT statement, listing the columns you want to
include in the final result. You can include columns from both tables.
4. Next, include the FROM clause to indicate the tables you want to join. For example,
"FROM Table1" followed by "RIGHT JOIN Table2".
5. Use the ON keyword to specify the join condition created in step 2. For example, "ON
TableA.id = TableB.id".
6. Optionally, you can add additional conditions using the WHERE clause to further
filter the result set.
7. Complete the query with any additional clauses you need, such as GROUP BY,
ORDER BY, or LIMIT.
8. Execute the SQL query, and the database will perform the right join operation.
9. The result set will contain all the records from Table 2 (right table) and the matched
records from Table 1 (left table) based on the join condition.
10. If no match is found for a record in Table B, the columns from Table A will have
NULL values in the result set.
FULL JOIN:
The result-set is created by combining the results of both LEFT JOIN and RIGHT JOIN. The
result set will include all rows from both tables. The result-set will contain NULL values for
rows where there is no match. FULL JOIN can potentially return very large result-sets!

Figure 80

65 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Syntax of FULL JOIN:

Figure 81
How FULL JOIN works:
1. When a Full Join is performed, the output will include all of the rows from both tables.
2. If the related columns match, the corresponding columns from both tables will be
displayed in a single row.
3. If there is no match, NULL values will be displayed in the table columns where no
corresponding record exists.

SELF JOIN:
A self-join is a join procedure in which a table is attached to itself. To put it another way, it is
a method of combining rows from the same table. This is very handy for comparing or
analyzing data inside the same table.
Syntax of SELF JOIN:

Figure 82
How SELF JOIN works:
1. SELECT columns: With the help of this we specify the columns you want to retrieve
from the self-joined table.
2. FROM table AS alias1: With the help of this we specify the name of the table you want to
join with itself.
3. JOIN table AS alias2: In this we use the JOIN keyword to show that we are performing a
SELF JOIN on the same table.

Tasks:

Task – 1: Inner Join:

66 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

 Tables: Students and Departments.


 Scenario: Imagine you're managing student enrollments at a school. You want to create a
list of students along with their respective departments (like Math, Science, etc.).
 Task: Write an SQL query using an INNER JOIN to list all students' names and their
department names.
Query:

Figure 83 Student TBL Query

Figure 84 Departments TBL Query

Figure 85 INNER JOIN Query

Output:

67 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Task – 2: Left Join:

 Tables: Students and Departments


 Scenario: You need to generate a report of all students and the departments they belong
to. Some students might not have chosen any department yet, but you want to include
them.
 Task: Write an SQL query using a LEFT JOIN to list student names along with their
department names (if they have chosen one).
 Scenario- 2: Office Departments
Query:

Figure 86 Student TBL Query

Figure 87 Department TBL Query and LEFT JOIN Query


Output:

Figure 88 LEFT JOIN OUTPUT


Task - 3: Right Join:

 Tables: Departments and Students

68 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

 Scenario: Think of an office where you want to create a report of all departments and the
employees (students) in each department. Some departments might have no employees,
and some students may not be assigned to any department.
 Task: Write an SQL query using a RIGHT JOIN to list department names and student
names for all departments, including those without students.
Query:

Figure 89 Department TBL Query

Figure 90 Students TBL and RIGHT JOIN Query


Output:

Figure 91 RIGHT JOIN OUTPUT


Task – 4: Full Join:

 Tables: Departments and Students


 Scenario: You need to create a complete report showing all students and the departments
they are in. This report should also include students who are not in any department and
departments with no students.

69 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

 Task: Write an SQL query using a FULL JOIN to list student names and department
names for all students and departments.
 Scenario 3: Student Advisors
Query:

Figure 92 Department TBL Query

Figure 93 Student TBL Query

Figure 94 FULL JOIN Query


Output:

Figure 95 FULL JOIN OUTPUT


Task – 5: Self Join:

 Table: Students
 Scenario: In a school, each student might have another student as their advisor. You want
to create a list of students and their respective advisors.

70 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

 Task: Write an SQL query using a SELF JOIN to list each student's name and
their advisor's name.
Query:

Figure 96 Student TBL and SELF JOIN Query


Output:

Figure 97 SELF JOIN OUTPUT

Conclusion:

In this lab I have learned the SQL joins, SQL join are a fundamental tool for working with
relational databases, allowing us to bring together related data from multiple tables to answer
complex questions and extract valuable insights. Understanding the various types of joins and
when to use them is crucial for anyone working with SQL and database management. This
lab has provided a solid foundation for using joins effectively in real-world database queries
and applications.

71 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Rubrics:

Report not Plagiarized Requirements Observations Appropriate Correctly


submitted content are listed and are recorded computation drawn
presented or experimental along with s or conclusion
Laboratory incomplete procedure is detailed numerical with
Reports submission or presented procedure analysis is exact results
late performed and complete
report in all
respects
Category Ungraded Very Poor Poor Fair Good Excellent
Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

Absent Student failed Student Student Student Student


to develop a developed a developed a developed a excelled in
functional partially mostly fully developing
code or functional functional functional fully
complete the code and code and met code and functional
lab objective struggled to the lab met the lab code,
within the accomplish objective objective exceeding
simulation the lab within the within the expected
environment. objective simulation simulation results within
They exhibit within the environment, environment simulation
inadequate simulation achieving , achieving environment.
understanding environment. satisfactory expected They
Demonstrat
in They results. They results. demonstrate
ion
configuring, demonstrate exhibit They mastery in
operating, and minimal moderate demonstrate independently
executing the understanding proficiency in proficiency configuring,
simulation in configuring, in operating and
independently configuring, operating, and configuring, executing the
. operating, and executing the operating, simulation.
executing the simulation and
simulation independently executing
independently . the
. simulation
independent
ly.
Category Ungraded Very Poor Poor Fair Good Excellent

Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

72 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

73 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

LAB NO: 08 DATE: __/__/2023


File I/O (Stream Writer and Reader)

Lab outcomes:

After completing this lab, students will be able to:


 Learn about the Stream Reader and Stream Writer Functions of C# in the file system

Corresponding CLO and PLO:

 CLO-1, PLO-3(Design/Development of Solutions)

SOFTWARE REQUIRED:

 Microsft Visual Studio.

Theory:

File A file is basically a system object stored in the memory at a particular given directory
with a proper name and extension. In C#, we call a file as stream if we use it for writing or
reading data.
C# FileStream:
File stream offers a path for performing file operations. It is mainly used for reading and
writing data into the files.
C# StreamWriter:
The StreamWriter class in C# is used for writing characters to a stream. It uses the
TextWriter class as a base class and provides the overload methods for writing data into a
file.
C# StreamReader:
The StreamReader is used for reading string or large sentences from a file. The StreamReader
also uses the TextReader class as its base class and then offers methods like Reading and
ReadLine to read data from the stream.

Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{

74 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

class Program
{
static void Main(string[] args)
{
while (true)
{
Student S = new Student();
Console.WriteLine("Enter The value");
Console.WriteLine("Enter 1 for Add a new student \nEnter 2 to get all students\
nEnter 3 to search a specific student");
int n;
n = int.Parse(Console.ReadLine());
Console.WriteLine("You Entered " + n);
if (n == 1)
{
Console.WriteLine("Enter no of student u want to add");
int no_of_student = int.Parse(Console.ReadLine());
for (int i = 0; i < no_of_student; i++)
{
Console.WriteLine("Add new Student");
Console.WriteLine("Enter student name");
S.Name = Console.ReadLine();
Console.WriteLine("Enter CMS ID");
S.CMS_ID = int.Parse(Console.ReadLine());
Console.WriteLine("Enter student GPA");
S.gpa = float.Parse(Console.ReadLine());
Console.WriteLine("Enter department name");
S.Department = (Console.ReadLine());
using (StreamWriter sw = new StreamWriter("D:\\Studentdata.txt", true))
{
sw.WriteLine(S.Name + " " + S.CMS_ID + " " + S.gpa + " " +
S.Department + " ");
}
Console.Clear();
}
}
else if (n == 2)
{
Console.WriteLine("Get all students");
using (StreamReader sr = new StreamReader("D:\\Studentdata.txt"))
{
string line = sr.ReadLine();
while (line != null)
{
Console.WriteLine(line);
line = sr.ReadLine();
}
}
}
else if (n == 3)

75 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

{
Console.WriteLine("Search a student");

Console.WriteLine("Enter CMS ID");


int id = int.Parse(Console.ReadLine());
using (StreamReader sr = new StreamReader("D:\\Studentdata.txt"))
{
string line = sr.ReadLine();
while (line != null)
{
int CMS_ID = int.Parse(line.Split(' ')[1]);
line = sr.ReadLine();
if (CMS_ID == id)
{
Console.WriteLine(line);
}
}
}
}
else
{
Console.WriteLine("you entered a wrong value");
}
}
}
class Student
{
public string Name { get; set; }
public int CMS_ID { get; set; }
public string Department { get; set; }
public string Semester { get; set; }
public float gpa { get; set; }
}
}
}
Output:

76 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Stored Output view:

LAB TASK
Q: Use StreamWriter to create a new text file and write your name, cms, dept, and
faculty to the file & use StreamReader to read the data. Attach the screenshot of your
code and your output.

Figure 98 C# output one

77 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 99 C# output 2

Figure 100 File output


Conclusion:
In this lab I have learned about the “Stream writer and reader” Stream writers and readers are
essential components in handling data streams in programming. Writers facilitate the efficient
output of data to a stream, while readers enable the systematic input of data from a stream.
Together, they form a dynamic duo, allowing seamless communication between a program
and external data sources or destinations. The versatility and efficiency of stream writers and
readers make them integral for tasks such as file handling, network communication, and data
processing in various programming contexts.

78 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Rubrics:

Report not Plagiarized Requirements Observations Appropriate Correctly


submitted content are listed and are recorded computation drawn
presented or experimental along with s or conclusion
Laboratory incomplete procedure is detailed numerical with
Reports submission or presented procedure analysis is exact results
late performed and complete
report in all
respects
Category Ungraded Very Poor Poor Fair Good Excellent
Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

Absent Student failed Student Student Student Student


to develop a developed a developed a developed a excelled in
functional partially mostly fully developing
code or functional functional functional fully
complete the code and code and met code and functional
lab objective struggled to the lab met the lab code,
within the accomplish objective objective exceeding
simulation the lab within the within the expected
environment. objective simulation simulation results within
They exhibit within the environment, environment simulation
inadequate simulation achieving , achieving environment.
understanding environment. satisfactory expected They
Demonstrat
in They results. They results. demonstrate
ion
configuring, demonstrate exhibit They mastery in
operating, and minimal moderate demonstrate independently
executing the understanding proficiency in proficiency configuring,
simulation in configuring, in operating and
independently configuring, operating, and configuring, executing the
. operating, and executing the operating, simulation.
executing the simulation and
simulation independently executing
independently . the
. simulation
independent
ly.
Category Ungraded Very Poor Poor Fair Good Excellent

Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

79 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

80 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

LAB NO. 09 DATE: __/__/2023


File I/O Windows Form

Lab outcomes:

After completing this lab, students will be able to:


 Learn about the Reading and Writing data from the file within the system through
windows form using C#.

Corresponding CLO and PLO:

 CLO-1, PLO-3(Design/Development of Solutions)

SOFTWARE REQUIRED:

 Microsft Visual Studio.

Theory:

Windows Form: Windows Forms is a Graphical User Interface(GUI) class library which is
bundled in .Net Framework. Its main purpose is to provide an easier interface to develop the
applications for desktop, tablet, PCs. It is also termed as the WinForms. The applications
which are developed by using Windows Forms or WinForms are known as the Windows
Forms Applications that runs on the desktop computer. WinForms can be used only to
develop the Windows Forms Applications not web applications. WinForms applications can
contain the different type of controls like labels, list boxes, tooltip etc.
C# FileStream:
File stream offers a path for performing file operations. It is mainly used for reading and
writing data into the files.
C# StreamWriter:
The StreamWriter class in C# is used for writing characters to a stream. It uses the
TextWriter class as a base class and provides the overload methods for writing data into a
file.
C# StreamReader:
The StreamReader is used for reading string or large sentences from a file. The StreamReader
also uses the TextReader class as its base class and then offers methods like Reading and
ReadLine to read data from the stream.

Program
using System;
using System.IO;

81 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)

private void savebutton_Click(object sender, EventArgs e)


{
string path = @"D:\student\student.txt";
using (StreamWriter sw = new StreamWriter(path, true))
{
sw.WriteLine("CMS ID = " + cmstextBox.Text + ", Name = " +
NametextBox.Text + ", Department = " + depttextBox.Text +
", Semister = " + smstertextBox.Text + ", GPA = " + gpatextBox.Text);
}
}

private void showdetailbutton_Click(object sender, EventArgs e)


{
string path = @"D:\student\student.txt";
using (StreamReader sr = new StreamReader(path))
{

List<Student> students = new List<Student>();


string line = sr.ReadLine();
while (line != null)
{
string[] data = line.Split(',');
string cmsID = data[0].Split('=')[1];
string Name = data[1].Split('=')[1];
string Semister = data[2].Split('=')[1];
string Dept = data[3].Split('=')[1];
string gpa = data[4].Split('=')[1];
Student std = new Student()
{
CMSID = cmsID,

82 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

semister = Semister,
Department = Dept,
name = Name,
Gpa = float.Parse(gpa.Trim())

};
students.Add(std);
line = sr.ReadLine();

}
dataGridView1.DataSource = students;
}
}
}
}
Output:

LAB TASK
Q: Create a Windows form for Coffee shop and utilize StreamWriter & StreamReader
in your code. Attached the screenshot of your code and output.

83 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Figure 101 Window Form Output

Figure 102 File Output


Conclusion:
In this lab I have learned how to use stream Writer and stream Reader in window form of C#.
And how to show the input and output of window form in a file, so that I have successfully
show the output and input in the files which show in the above image (Fig: 102). These
classes are crucial for creating updating and retrieving information form external files.

84 | P a g e SUBMITTED TO: Mr. Rehmat


LAB MANUAL : [ DATABASE management SYSTEM ]

Rubrics:

Report not Plagiarized Requirements Observations Appropriate Correctly


submitted content are listed and are recorded computation drawn
presented or experimental along with s or conclusion
Laboratory incomplete procedure is detailed numerical with
Reports submission or presented procedure analysis is exact results
late performed and complete
report in all
respects
Category Ungraded Very Poor Poor Fair Good Excellent
Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

Absent Student failed Student Student Student Student


to develop a developed a developed a developed a excelled in
functional partially mostly fully developing
code or functional functional functional fully
complete the code and code and met code and functional
lab objective struggled to the lab met the lab code,
within the accomplish objective objective exceeding
simulation the lab within the within the expected
environment. objective simulation simulation results within
They exhibit within the environment, environment simulation
inadequate simulation achieving , achieving environment.
understanding environment. satisfactory expected They
Demonstrat
in They results. They results. demonstrate
ion
configuring, demonstrate exhibit They mastery in
operating, and minimal moderate demonstrate independently
executing the understanding proficiency in proficiency configuring,
simulation in configuring, in operating and
independently configuring, operating, and configuring, executing the
. operating, and executing the operating, simulation.
executing the simulation and
simulation independently executing
independently . the
. simulation
independent
ly.
Category Ungraded Very Poor Poor Fair Good Excellent

Marks 0 1 2 3 4 5

Date Total Marks Instructor’s Signature

85 | P a g e SUBMITTED TO: Mr. Rehmat

You might also like