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

Lab Mannual DBMS

Uploaded by

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

Lab Mannual DBMS

Uploaded by

Malik Awan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 128

Lab Manual Database Management System: First Edition

(Publisher:???)
Author(s): Prof. Dr. Munir Ahmed ISBN: B IIT
???? Serie

Publication Date: ????


A publication of BIIT Series
Copyrights © Reserved By Authors

Learning Objectives: By the end of the lab work, students should have
following skills; Lab Manual
Databas
Sr. Learning Objective

SQL introduction and basic SELECT


LAB No.
Managem
1
Clause
Arithmetic expressions and column
System
2
alias A simplified practical work book
Use of concatenation operator and Computer Science, Information Te
3
distinct
4 Order by and Where clause

Logical operators (AND, OR, NOT) Student Name:


5

6 Comparison operators _____________________

Use of between, in operator and top


7 Registration No:
clause
8 Selection with like operator _____________________

9 Use of aggregate functions


Section / Semester:
10 Group by and having clause
_____________________
SQL Create, Drop,Alter statement
11 Add and drop constraints Primary key, Submission Date:
Foreign key, Unique, Check
SQL insert, update and delete ______ ______________
12
statements
13 Create update and drop a view Student Signature:

14 SQL Joins _____________________

DBS LAB MANUALS 1


15 SQL Union operator

16 SQL Cross Join

Table of Contents

Lab # 01 .........................................................................................
9
Introduction to SQL ..........................................................................
9
What is SQL? ...................................................................................
9
What Can SQL do? ......................................................................
9
How can we use SQL Server? .......................................................
9
The SQL SELECT Statement .............................................................
17
SQL SELECT Syntax ..................................................................
17
In the syntax: ................................................................................
17
An SQL SELECT Example ............................................................
17
Exercise 1 ......................................................................................
20
Lab # 02 .......................................................................................
21
Arithmetic Expressions and Operators and Column Aliasing ..................
21
Simple addition to a column value ....................................................
21
Simple subtraction to a column value ................................................
22
Simple Multiplication to a column value .............................................
22
Simple Division to a column value ....................................................
22
Addition, Multiplication, Subtraction and Division to a column value ......
23

DBS LAB MANUALS 2


Alias .............................................................................................
24
Syntax: ...................................................................................
24
Exercise 2 ......................................................................................
25
Lab # 03 .......................................................................................
27
Concatenation Operator (+) .............................................................
27
Example ..................................................................................
28
Duplicate Rows...............................................................................
29
Example distinct .......................................................................
29
Exercise 3 ......................................................................................
30
Lab # 04 .......................................................................................
32
Sorting Data (Order by Keyword) .....................................................
32
SQL ORDER BY Syntax ..............................................................
32
Selection (Where Clause) ................................................................
34
SQL WHERE Syntax ...................................................................
35
Quotes around Text Fields ...............................................................
36
For text values: ........................................................................
36
For numeric values: ..................................................................
36 Exercise
4 ......................................................................................37
Lab
#05 ........................................................................................39
Logical Operators ...........................................................................
39
Logical AND ..............................................................................
39

DBS LAB MANUALS 3


AND Syntax .............................................................................
39
Logical OR .....................................................................................
40
OR Syntax ...............................................................................
40
Logical NOT ...................................................................................
41
NOT Syntax ..............................................................................
41
Combining AND, OR and NOT ...........................................................
42
Task 5 ...........................................................................................
42
Exercise 5 ......................................................................................
43
Lab # 06 .......................................................................................
45
Comparison Operators ....................................................................
45
Example Equal Operator: (=) .....................................................
46
Example Greater than: (>) ........................................................
46
Example Less than: (<) .............................................................
46
Example Greater than equal to: (>=) ..........................................
47
Example Less than equal to: (<=) ..............................................
47
Example Not equal: (!=, <>) .....................................................
48
Task 6 ...........................................................................................
48
Exercise 6 ......................................................................................
49
Lab # 07 .......................................................................................
51
Logical Operators ...........................................................................
51

DBS LAB MANUALS 4


The BETWEEN Operator .............................................................
51
SQL IN Operator .............................................................................
52
SQL IN Syntax ..........................................................................
52
Not Null Operator ...........................................................................
54
NOT BETWEEN ...............................................................................
54
Not In Example .........................................................................
55
BETWEEN with IN ...........................................................................
55
SQL TOP CLAUSE ............................................................................
56
SQL Server Syntax ....................................................................
56
Task 7 ...........................................................................................
57
Exercise 7 ......................................................................................
58
Lab #08 ........................................................................................
61 The SQL LIKE
Operator ...................................................................61
SQL LIKE
Syntax .......................................................................61
Task 8 ...........................................................................................
65
Exercise 8 ......................................................................................
65
Lab # 09 .......................................................................................
67
SQL Aggregate Functions .................................................................
67
Useful aggregate functions: ........................................................
67
SQL AVG() Function ..................................................................
67
The AVG () Function .......................................................................
67

DBS LAB MANUALS 5


SQL COUNT () Function .............................................................
68
SQL COUNT () Function .............................................................
68
SQL COUNT (column_name) Example ...............................................
69
The SQL MAX () Functions ..........................................................
70
SQL MIN () Function ..................................................................
70
The MIN () Function ........................................................................
71
SQL SUM () Function .................................................................
71
The SUM () Function .......................................................................
71
Task 9 ...........................................................................................
72
Exercise 9 ......................................................................................
75
Lab # 10 .......................................................................................
76
The SQL GROUP BY Statement .........................................................
76
GROUP BY Syntax .....................................................................
76
GROUP BY More Than One Column ...................................................
77
SQL HAVING Clause ........................................................................
77
The HAVING Clause ........................................................................
77
SQL HAVING Syntax ..................................................................
77
Task 10 .........................................................................................
79
Exercise 10 ....................................................................................
79
Lab # 11 .......................................................................................
81

DBS LAB MANUALS 6


Create Database .............................................................................
81
The CREATE DATABASE Statement ...................................................
81
SQL CREATE DATABASE Syntax ..................................................
81
SQL CREATE TABLE Statement .........................................................
81
The CREATE TABLE Statement .........................................................
81
SQL CREATE TABLE Syntax ........................................................
81
SQL ALTER TABLE Statement ...........................................................
82 ALTER TABLE - ADD Column .......................................................82
ALTER TABLE - DROP COLUMN ...................................................82
ALTER TABLE - ALTER/MODIFY COLUMN ......................................
83
Rename column in table ..................................................................
83
Syntax .....................................................................................
83
Rename table .................................................................................
84
Syntax .....................................................................................
84
Check Constraint ............................................................................
84
SQL CHECK Constraint ....................................................................
84
SQL NOT NULL Constraint ................................................................
84
SQL UNIQUE Constraint ...................................................................
85
SQL UNIQUE Constraint on CREATE TABLE ...................................
85
UNIQUE constraint on multiple columns .......................................
85
SQL CHECK Constraint on CREATE TABLE ....................................
86

DBS LAB MANUALS 7


SQL PRIMARY KEY Constraint ...........................................................
86
SQL PRIMARY KEY on CREATE TABLE ..........................................
86
SQL syntax: .............................................................................
86
SQL PRIMARY KEY on ALTER TABLE .............................................
86
Syntax .....................................................................................
86
PRIMARY KEY constraint on multiple columns on Alter Table ................
86
DROP a PRIMARY KEY Constraint ......................................................
87
SQL FOREIGN KEY Constraint ...........................................................
87
SQL FOREIGN KEY on CREATE TABLE ..........................................
88
FOREIGN KEY constraint on multiple columns ...............................
89
SQL FOREIGN KEY on ALTER TABLE ............................................
89
FOREIGN KEY constraint on multiple columns ...............................
89
DROP a FOREIGN KEY Constraint ................................................
89
SQL CHECK Constraint ....................................................................
89
SQL CHECK on CREATE TABLE ....................................................
90
CHECK constraint on multiple columns .........................................
90
SQL CHECK on ALTER TABLE ......................................................
91
Alter CHECK constraint on multiple columns .................................
91
DROP a CHECK Constraint ..........................................................
91
Task 11 .........................................................................................
91

DBS LAB MANUALS 8


Exercise 11 ....................................................................................
92 Lab
#12 ........................................................................................94
SQL INSERT INTO Statement ...........................................................
94
The INSERT INTO Statement ...........................................................
94
SQL INSERT INTO Syntax ..........................................................
94
Insert Data Only in Specified Columns ...............................................
95
SQL UPDATE Statement ..................................................................
95
The UPDATE Statement ...................................................................
95
SQL UPDATE Syntax ..................................................................
96
SQL DELETE Statement ...................................................................
97
The DELETE Statement ...................................................................
97
SQL DELETE Syntax ..................................................................
97
Delete All Rows ..............................................................................
98
Syntax .....................................................................................
98
The DROP DATABASE Statement ......................................................
98
Syntax .....................................................................................
98
The SQL DROP TABLE Statement ......................................................
98
Syntax .....................................................................................
98
SQL TRUNCATE TABLE ....................................................................
98
Syntax .....................................................................................
99
Task 12 .........................................................................................
99

DBS LAB MANUALS 9


Exercise 12 ....................................................................................
99
Lab #13 ......................................................................................
101
SQL Subqueries ............................................................................
102
Syntax ...................................................................................
103
Examples ................................................................................
103
Lab # 14 .....................................................................................
107
SQL Joins ....................................................................................
107
Different Types of SQL JOINs .........................................................
107
SQL INNER JOIN Keyword ........................................................
108
SQL LEFT JOIN Keyword ..........................................................
109
SQL RIGHT JOIN Keyword ........................................................
110
SQL FULL JOIN Keyword ..........................................................
112
Task 14 .......................................................................................
113
Exercise 14 ..................................................................................
114
LAB #15 ......................................................................................
116
SQL UNION Operator ....................................................................
116 Exercise
15 .................................................................................. 118
Lab # 16 .....................................................................................
118
SQL Cross Join .............................................................................
120
What is Cross Join in SQL? ....................................................... 120
Syntax: .................................................................................. 120
Exercise 16 ..................................................................................
123

DBS LAB MANUALS 10


DBS LAB MANUALS 11
Lab # 01
Introduction to SQL

SQL is a standard language for accessing/retrieving and manipulating


databases.

What is SQL?

• SQL stands for Structured Query Language


• SQL lets you access and manipulate databases
• SQL is an ANSI (American National Standards Institute)
standard

What Can SQL do?

• SQL can execute queries against a database


• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views How

can we use SQL Server (on PC)?

First go to start button file of your system and write SQL Server
Management Studio in search bar or explore all program. Click on SQL
Server Management Studio then its open a new window like this.

DBS LAB MANUALS 12


Clicking on connect button its open new Screen like this.

Now click on New Query Button its open new Screen like this to write
queries.

DBS LAB MANUALS 13


Now you can select your database or create new database. For selecting
database from available database dropdown list that is underline below
screen shots.

For Mobile (Android only)


To use SQL on mobile, go to Play Store and download SQL practice client
and open the app.

DBS LAB MANUALS 14


After

opening the app you will get an interface like this

Benefits of using SQL Practice Client

DBS LAB MANUALS 15


You can use the keywords that
are already added in the app. This
will reduce the time requir ed to
type a query.

You can also use the sample queries.


For this you will need to go to the
sample tab.

Schema/ Meta-data

DBS LAB MANUALS 16


For Student

For Teacher

DBS LAB MANUALS 17


DBS LAB MANUALS 18
For Course

For Allocation

For Enrollment

Writing Basic SQL Select Statement (Selecting All or Specific Columns


In this section we will learn about the SELECT and the SELECT *
statements.
The SQL SELECT Statement

DBS LAB MANUALS 19


The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.
SQL SELECT Syntax
SELECT column_name(s) FROM table_name
And
SELECT * FROM table_name

Note: SQL is not case sensitive. SELECT is the same as select.

In the syntax:
1. SELECT is keyword.
 selects all columns
2. Column_name (s) selects the named column.
3. FROM table specifies the table containing the columns.
An SQL SELECT Example
The "Student" table:
Person table stores the following data of person object; Persons
S_id, fname, lname, city, age, degree, semesterno, section

Example of (*)
Select * From Student

Student

Selecting Specific columns:


Example:
Selecting Student’s FName

Select fname from student

DBS LAB MANUALS 20


Example:
Selecting Multiple columns like Student’s FName, LName, City.

Select fname, lname, city from student

Example:
Selecting Student sid, city, age

Select sid, city, age from student

DBS LAB MANUALS 21


Example:
Selecting fname, age, cgpa, semesterno from student

Select fname, age, cgpa, semesterno from student

Exercise 1
Student table stores the following data of student object;

DBS LAB MANUALS 22


1) Write a query that will display record of all student.

2) Write a query that will display only age of student.

3) Write a query that will display Roll_No and Name of student.

4) Write a query that will retrieve Discipline, Section and CGPA of a


Students.

5) Write a query that will retrieve city, age and Name of a students.

6) Write a Sql Statement that will retrieve all record of Employees.

7) Write a Sql Statement that will retrieve name and Salary of


Employees.

8) Write a Sql Statement that will retrieve Employee_id and Employees.

9) Write a Sql Statement that retrieve Quantity from Sales table.

10) Write a Sql Statement that will retrieve all record of sales.

DBS LAB MANUALS 23


Lab # 02
Arithmetic Expressions and Operators and Column Aliasing
Arithmetic Expression
Arithmetic expressions allow you to modify the way in which data is
displayed, perform
Calculations, or look at what-if scenarios.
Here, we have a Teacher Database named Teacher (Teacher Management
System). In this
Manual, we will use Teacher table with the attributes listed below.
Teacher

Simple addition to a column value


Now Suppose we want to show salary by adding 2000 in salary of Teacher

Select salaray+2000 as [salary] from Teacher

The result would be like this.

Simple subtraction to a column value


Now Suppose we want to show Salary by Subtracting 200 in Salary of

DBS LAB MANUALS 24


Teacher
Select salaray-200 as [salary] from Teacher

The result would like this.

Simple Multiplication to a column value


Now Suppose we want to show t_fname and bonus multiply by 2 of
Teachers

Select t_fname, bonus*2 as [Bonus] from teacher

The result would like this.

Simple Division to a column value


Now Suppose we want to show t_lname, bonus by divided 2 of Teacher

Select t_lname, bonus/2 as [bonus] from teacher

The result would like this.

DBS LAB MANUALS 25


Addition, Multiplication, Subtraction and Division to a column value
Now Suppose we want to show t_fname, t_lname ,salary, salary + 200,
bonus – 9000, salary * 4, bonus /3

Example

Select t_fname, t_lname , salary + 200 as [salary + 200] ,


bonus-9000 as [bonus - 9000], salary * 4 as [salary * 4],
bonus/3 as [Bonus / 3] form teacher

The result would like this.

Defining a Column Alias


Alias
Aliases can be used to create a temporary name for columns or tables.

• Renames a column heading.


• Is useful with calculations.
• Immediately follows column name; optional AS keyword between
column name and Alias.
• Requires single quotation marks if it contains spaces or special
characters or is case sensitive.

DBS LAB MANUALS 26


Syntax:
Column_name [As] Alias_name
Example:
Now suppose we want to show t_fName of teacher as Name
In Above Teacher Table

Select t_fName AS [Name] FROM teacher

Select tid AS [Teacher id] FROM Teacher

Task 2

a. Write a Sql Statement to retrieve all column from Teacher Table.

b. Write a Sql Statement to retrieve any two column from Teacher table.

c. Write a Sql Statement to retrieve more than three column from


Teacher table.

d. Write a Sql Statement to retrieve Age with addition of 5 from Teacher


table.

DBS LAB MANUALS 27


e. Write a Sql Statement to retrieve t_fname column as Teacher Name
from Teacher table.

Exercise 2
Student table stores the following data of student object

Student

1. Write a query that will retrieve lname and age of a students. Age must
be display/retrieve addition by 5.

2. Write a query that will retrieve sid and Cgpa of a student. Cgpa must
be display/retrieve subtraction by 1.0.

3. Write a query that will retrieve age, degree and Section of a student.
Age must be display multiply by 2.

4. Write a query that will retrieve fname, City and Cgpa of a student. Cgpa
must be display division by 2.0.

5. Write a query to show name, age by Addition 10 in age, age by


Subtract 5 in age, age by Multiply 2 in age and age by division 2 in age
of Students.

DBS LAB MANUALS 28


6. Write a query to show fName of a students as a S_Name of a Student.

7. Write a query to display city of a student as a Student_City and age of


a students as a Student_Age.

8. Write a Sql Statement that will display quantaty as Sales_Quantaty


from Sales Table.

9. Write a Sql Statement will retrive quantaty with addation of 7 and


Subtraction of 5 from Sales table.

10. Write a Sql Statement that will retrieve Sales_item, Sales_order,


and quantaty must be division by 2 from sales table.

Lab # 03
Concatenation Operator, Distinct & Duplicate Record
Retrieval

Concatenation Operator (+)


• You can link columns to other columns, arithmetic expressions,
or constant values to create a character expression by using the
concatenation operator (+).
• Columns on either side of the operator are combined to make a
single output column.
Using Concatenation Operator
Consider the Student table as shown with attributes listed
below:
• Sid
• Fname  Lname
• City  Age
• Cgpa
• Degree
• Semesterno
• section

DBS LAB MANUALS 29


Student

Since, the purpose of concatenation operator is to combine two columns


into a single column in the output only; we can concatenate Person First
Name with Last Name and display the Full name in the output.

Example
The query for concatenation of First Name with Last Name of student is as
follows:

Select [FName] + ’ ‘ +[LName] as [Student Name] from Student;

RESULT

Example
The query for concatenation of Degree with section of student is as
follows:

Select Degree + ’ ‘ +Section as [Degree & Section] from


Student;

RESULT

DBS LAB MANUALS 30


Eliminating Duplicate Rows
Duplicate Rows
The default display of queries is all rows, including duplicate rows.
Consider the table shown in Figure 1. In this table, when we retrieve all
the records, we will receive repeated values of degree since more than
one student studies the same degree Select * from Student

Figure 1

If we wish to eliminate these duplicate rows, we can do this using


DISTINCT keyword in the SELECT clause of SQL SELECT

Select distinct degree from student

DBS LAB MANUALS 31


Example distinct

Now we want to select only the distinct values from the column named
"City" from the table above.

We use the following SELECT statement:

SELECT DISTINCT City FROM student

The result-set will look like this:

Task 3

1 Write a Sql Statement to merged fname and lname as Full Name from
Student table.

2 Write a Sql Statement to retrieve distinct lname from student.

3 Write a Sql Statement to retrieve all those student whose age is not
duplicate/repeated.

4 Write a Sql Statement to retrieve sid as student id from student table.

5 Write a Sql Statement to retrieve all those semesterno whose value is


not duplicate.

Exercise 3
Teacher table stores the following data of teacher object;

Teacher

DBS LAB MANUALS 32


1 Write a query to concatenate t_fname and t_lname with city of a
teacher as a Name City.

2 Write a query to merged city with qualification of a teacher as a city


qualification.

3 Write a query to display different name of a teacher from teacher table.

4 Write a query to retrieve different city from teacher table.

5 Write a Sql Statement that will retrieve all those teachers whose age is
distinct from teacher table.

6 Write a Sql Statement that will merge any two columns from teacher
Table.

7 Write a Sql Statement that will merge three or more columns from
teacher table.

8 Write a Sql Statement that will retrieve tid, city and yearsofexp as
Experience from teacher Table.

DBS LAB MANUALS 33


9 Write a Sql Statement that will retrieve all those teachers whose Salary
is not duplicate.

10 Write a Sql Statement that will retrieve all those teachers whose
Salary and bonus is not duplicate.

Lab # 04
Sorting of Data, Selection and Projection
Sorting Data (Order by Keyword)
The ORDER BY keyword is used to sort the result-set by a specified
column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the
DESC keyword.
SQL ORDER BY Syntax

SELECT column_name(s) FROM table_name ORDER BY column_name(s)


ASC|DESC
ORDER BY Example

The "student" table:

DBS LAB MANUALS 34


Now we want to select all the student from the table above, however, we
want to sort the students by their last name.

We use the following SELECT statement:

Select * from student order by lname

The result-set will look like this:

Example 2
Now we want to select all the students from the table above, however, we
want to sort the students by their Age

We use the following SELECT statement:

Select * from student order by age

The result will look like this:

ORDER BY DESC Example 1

DBS LAB MANUALS 35


Now we want to select all the students from the table above, however, we
want to sort the persons descending by their first name.
We use the following SELECT statement:
Select * from student order by fname desc

The result-set will look like this:

ORDER BY DESC Example 2

Now we want to select all the student from the table above, however, we
want to sort the student descending order by their Age.
We use the following SELECT statement:
Select * from student order by age desc

The result-set will look like this:

Selection (Where Clause)


Selection: You can use the selection capability in SQL to choose the rows
in a table that you want returned by a query. You can use various
criteria to selectively restrict the rows that you see using Where clause
in SQL Select statement.

DBS LAB MANUALS 36


The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a
specified criterion.
SQL WHERE Syntax
SELECT column_name(s)FROM table_name WHERE column_name
operator value

Example: 1
The "students" table:

Now we want to select only those student living in the city “Rwp" from the
table above.

We use the following SELECT statement:

SELECT * FROM student WHERE City='Rwp'

The result-set will look like this:

Example: 2

Now we want to select only those students who have age equal to 18 in
student table.

Select * from student where age=18

DBS LAB MANUALS 37


The result-set will look like this:

Example: 3
Now we want to select only those students who have M_Income cgpa =
3.4 from the student table.

Select * from student where cgpa = 3.4

The result-set will look like this:

Quotes around Text Fields

SQL uses single quotes around text values (most database systems will
also accept double quotes).

Although, numeric values should not be enclosed in quotes.


For text values:
This is correct:
SELECT * FROM student WHERE fname='shahid'
This is wrong:
SELECT * FROM student WHERE fname=shahid

For numeric values:


This is correct:
SELECT * FROM student WHERE age=18
This is also correct:
SELECT * FROM student WHERE age=’18’

Task 4
Teacher table stores the following data of teacher object;

Teacher

DBS LAB MANUALS 38


1 Write a query that will age of teachers order by age in descending order
descending.

2 Write a query that will retrieve data of teachers whose bonus is 11000.

3 Write a query that will display yearsofexp of those teachers whose


houseallowence is 22700

4 Write a query that will display all teachers whose tid is 5009.

5 Write a query that will retrieve t_fname and t_fname as full name of
teachers whose qualification is Ph D

Exercise 4

1 Write a query that will retrieve data of all teachers order by t_fname in
ascending order.

2 Write a query that will retrieve data of all teacher order by age in
descending order.

3 Write a query that will display all teacher who live in ‘Rwp’.

4 Write a query that will retrieve all teacher whose t_lname is ‘Iqbal’.

5 Write a query that will retrieve all Teacher whose qualification is ‘Ph D’.

DBS LAB MANUALS 39


6 Write a Sql Statement that will not retrieve duplicate city from teacher
order by city Descending.

7 Write a Sql Statement that will not retrieve duplicate Salary from all
teacher order by name Ascending.

8 Write a Sql Statement that will merge yearsofexp and bonus from
teachers where bonus is equal to 9000

9 Write a Sql Statement that will merge Name and Age as a “Name Age”
from teacher table order by tid descending.

10 Write a Sql Statement that will retrieve distinct name and city from
student table order by name ascending.

Lab #05
Logical Operators and WHERE Clause
Logical Operators
Logical operators are used in SQL Statement’s Where clause.
Logical AND

 The AND operator displays a record if both the first condition and
the second condition is true.
 You can restrict the records displayed in the output by supplying
more than one conditions in the where clause.
 All the records meeting the conditions (Where AND) is displayed in
the output.

DBS LAB MANUALS 40


Consider the Student table as shown with attributes listed below:
• Sid
• Fname  Lname
• City  Age
• Cgpa
• Degree
• Semesterno
• section

AND Syntax
SELECT column1, column2, FROM table_name
WHERE condition1 AND condition2 AND condition3

Example: 1

Now we want to select only those students with the first name equal to
"Ali" AND the last name equal to "ahmad":

We use the following SELECT statement:

SELECT * FROM student WHERE fname='ali' AND lname='ahmad'

The result-set will look like this:

Example: 2

Now we want to select only those students with the first name equal to
"Saad" AND the last name equal to "Amir":

SELECT * FROM student WHERE FName='Saad' AND LName='Khan'

DBS LAB MANUALS 41


The result-set will look like this:

Logical OR
The OR operator displays a record if either the first condition or the
second condition is true.
OR Syntax
SELECT column1, column2 FROM table_name
WHERE condition1 OR condition2 OR condition3

Example: 1

Now we want to select only those students with the first name equal to
"ali" OR the last name equal to "ahmad":

We use the following SELECT statement:

SELECT * FROM student WHERE FName='ali' OR LName='ahmad'

The result-set will look like this:

Example: 2

Now we want to select only those persons with the last name equal to
‘ahmad’ or cgpa=3.4

SELECT * FROM student


WHERE lName='ahmad' OR cgpa=3.4

The result-set will look like this:

DBS LAB MANUALS 42


Logical NOT
 The NOT operator displays a record if the condition(s) is NOT TRUE.
 Logical NOT means exclude the records where the condition is true
and display other records.

NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

Example: 1
The following SQL statement selects all fields from students where city is
NOT ‘rwp’;

Select * from student where not city=’rwp’

The Result will be like this:

Example: 2
Now we want to select all those students where cgpa not equal to 3.4
from the student table.

Select * from student where not cgpa=3.4

The result will look like this

Combining AND, OR and NOT


You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Student" where city is
"rwp" AND age must be 19 OR 21 (use parenthesis to form complex
expressions):

Select * from student where city=’rwp’ and (age=23 or age=24)

DBS LAB MANUALS 43


The result will look like this

Task 5
The tables and the data in the tables from which the queries are written are
given below:
Course

Scenario: select + from + where

Query 1: Write a query that will retrieve all data from course where
category =cs.

Query 2: Write a query that will retrieve title of course where cr_hours is
equal to 10000.

Query 3: write a query that will retrieve cr_hours of course where


category is either cs or maths.

Query 4: write a query that will retrieve all the data from coursewhere cid
is equal to 1010 and category is not cs.

Query 5: retrieve id of all those courses that belong to title ‘networks’.

DBS LAB MANUALS 44


Exercise 5
Student table stores the following data of student object

Assume the following Schema to write following queries that’s given below.

1 Write a query that will display all students whose cgpa is equal to
“1.4” and Section is equal to “A”.

2 Write a query that will display name as a Student Name of all


students whose age is equal 23 and order by name descending.

3 Write a query that will retrieve sid, age and name as Student Name
from students who live in “ISB” or “Rwp” order by city Ascending.

4 write a query that will retrieve sid, Name, age, city and degree
where degree not equal to “MCS” order by age descending.

5 Write a query that will retrieve data of all student whose Discipline is
equal to “BSCS” and city must be “Rwp” or “Multan”.

DBS LAB MANUALS 45


6: write a query that will retrieve all students where age is equal to 10.

7: write a query that will retrieve the cgpa from students where age is
either 18 or 20.

8: Write a Sql Statement to retrieve fname and lname of all students


where age is equal to 18.

9: Write a Sql Statement to retrieve all students where cgpa not equal to
2.4 and 3.4

10: Retrieve all those students whose lname is ali.

/* kainat malik 220-arid-3661*/


/*Write a query that will display all students whose cgpa is equal to “1.4” and
Section is equal to “A”. */
select * from student where cgpa = 1.4 and section ='a'
/*2 Write a query that will display name as a Student
Name of all students whose age is equal 23 and order by name descending. */
select fname+' '+lname as [Student Name] from student where age=23 order
by fname desc
/*Write a query that will retrieve sid, age and
name as Student Name from students who live in “ISB” or “Rwp” order by city
Ascending. */
select convert(char,sid)+' '+fname+' '+lname+' '+convert(char,age) as
[Student Name] from student where city='rwp' or city='isb' order by city asc
/*4 write a query that will retrieve sid, Name, age, city
and degree where degree not equal to “MCS” order by age descending. */

DBS LAB MANUALS 46


select convert(char,sid)+' '+fname+' '+lname+' '+convert(char,age)+'
'+convert(char,degree) as [Student Name] from student where degree!='mcs'
order by age desc
/*5 Write a query that will retrieve data of all student
whose Discipline is equal to “BSCS” and city must be “Rwp” or “Multan”. */
select * from student where degree='bscs' and city='rwp' or city='multan'
/*6: write a query that will retrieve all students where age is equal to 10. */
select * from student where age=10
/*7: write a query that will retrieve the cgpa from students where age is either
18 or 20. */
select cgpa from student where age = 10 or age = 20
/*8: Write a Sql Statement to retrieve fname and lname of all students where
age is equal to 18. */
select fname,lname from student where age=18
/*9: Write a Sql Statement to retrieve all students where cgpa not equal to 2.4
and 3.4 */
select * from student where cgpa!=2.4 and cgpa!=3.4
/*10: Retrieve all those students whose lname is ali. */
select * from student where lname!='ali'

Lab # 06
Comparison Operators
Comparison Operators
 A comparison (or relational) operator is a mathematical symbol which is
used to compare two values.

 Comparison operators are used in conditions that compares one


expression with another. The result of a comparison can be TRUE, FALSE,
or UNKNOWN (an operator that has one or two NULL expressions returns
UNKNOWN).

The following table describes different types of comparison operators –

Operator Description

DBS LAB MANUALS 47


= Equal to.

> Greater than.

< Less than.

>= Greater than equal to.

<= Less than equal to.

<> Not equal to.

Example Equal Operator: (=) The


"student" table:

DBS LAB MANUALS 48


Now we want to select only those students living in the city “Rwp" from
the table above.

We use the following SELECT statement:

SELECT * FROM student where city=’rwp’

The result will look like this:

Example Greater than: (>)

Now we want to select all those Students whose age is greater than 20.

Select * from student where age>20

The result will look like this:

Example Less than: (<)


Now we want to select all those students whose cgpa is less than 2.5

Select * from student where cgpa<2.5

The result will look like this:

Example Greater than equal to: (>=)


Now we want to select all those students whose age is greater than or
equal to 20.

Select * from student where age>=20

The result will look like this:

DBS LAB MANUALS 49


Example Less than equal to: (<=)

Now we want to select all those Students whose cgpa is less than or equal
to 3.4.

Select * from student where cgpa <= 3.4

The result will look like this:

Example Not equal: (!=, <>)


Example: 1(!=)
Now we want to select all those Students whose cgpa is not equal to 3.4.

Select * from student where cgpa != 3.4

The result will look like this:

Example: 2(<>)
Now we want to select all those Students whose city is not equal to rwp.

Select * from student where city<>’rwp’

The result will look like this:

DBS LAB MANUALS 50


Task 6

The tables and the data in the tables from which the queries are written are
given below:
Course

1 Write a query that will retrieve all data from course where category=CS.

2 Write a query that will retrieve title of courses where credit hours are
equal to 4.

3 Write a query that will retrieve category of employees where title is


equal to calculus.

4 Write a query that will retrieve all the data from course where category
is CS and cr_hours is not 3.

5 Retrieve id of all those courses where cid is less than 1005.

DBS LAB MANUALS 51


Exercise 6
Student table stores the following data of student object

Student

1 Write a query that will retrieve data of all students whose enrolled in
Degree “BSCS” and Cgpa greater than 3.3.

2 Write a query that will retrieve sid, Name, Age, degree and Cgpa of
a Students who’s Cgpa less than equal to 3.5 order by age descending.
3 Write a query that will retrieve Name as “Full Name” and degree,
Section as a “Discipline Section” of Students who’s Cgpa greater than
equal to 3.2 order by section descending.

4 Write a query that will display all those students whose age not
equal to 23 and also order by name descending.

5 Write a query that will retrieve data of all students whose age
greater than equal to 24 not living in “Isb” and “Multan”.

DBS LAB MANUALS 52


Teacher

6: Write a query that will retrieve all Teacher where age is greater than
30

7: Write a query that will retrieve the qualification where bonus is either
9000 or 11000

8: Retrieve Name and tid of all teachers whose yearsofexp is greater than
equal to 10

9: Retrieve all Teachers where house allowance is greater than 20000 and
less than 50000

10: Retrieve all those teachers whose qualification is MS

Lab # 07
Logical Operators (BETWEEN, IN, NOT) and Top Clause
Logical Operators
Logical operators test for the truth of some condition. Logical operators, like
comparison operators, return a Boolean data type with a value of TRUE, FALSE,
or UNKNOWN.

DBS LAB MANUALS 53


The BETWEEN Operator
The BETWEEN operator selects a range of data between two values. The
values can be numbers, text, or dates.
SQL BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2

BETWEEN Operator Example: 1 The


Student table:

Now we want to select the Student with a sid between 3 and 6 from the
table above.

We use the following SELECT statement:

Select * from student where sid between 3 and 6

The result will be like this

BETWEEN Operator Example: 2

Now we want to select the Student with Age between 20 and 21 from the
table above.

We use the following SELECT statement:

DBS LAB MANUALS 54


Select * from student where age between 20 and 21

The result will be like this

SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.

SQL IN Syntax
SELECT column_name(s)FROM table_name

WHERE column_name IN (value1,value2,...)

IN Operator Example
The student table

Now we want to select the student fName equal to "Ali" or "Nabeel" from
the table above.

We use the following SELECT statement:

Select * from student where fname in(‘ali’,’nabeel’)

The result will be like this

DBS LAB MANUALS 55


Example: 2

Now we want to select the student with city equal to "Rwp" or "isb" from
the table above.

We use the following SELECT statement:

Select * from student where city in(‘rwp’,’isb’)

The Result will be like this:

Not Null Operator

Now we want to select the students with city is equal to NOT NULL from
the table student.

We use the following SELECT statement:

Select * from student where city is not null

The Result will be like this:

DBS LAB MANUALS 56


NOT BETWEEN
Example

Now we want to select the students whose age is not between 19 and 22.

Select * from student where age not between 19 and 22

The Result will be like this:

Example 2

Now we want to select the students with cgpa not between 3.4 and 4.5
from the table student.

Select * from student where cgpa not between 3.4 and 4.5

The Result will be like this:

Not In Example
Now we want to select the students with sid not in 3,6,8 from student
table

Select * from student where sid not in (3,6,8)

The Result will be like this:

BETWEEN with IN
Example

DBS LAB MANUALS 57


Now we want to select the student with Age BETWEEN 19 and 20. In
addition; do not show student with city in karachi and multan

Select * from student where (age between 19 and 20) and city
not in(‘karachi’,’multan’)

The Result will be like this:

SQL TOP CLAUSE


The TOP clause is used to specify the number of records to return.
The TOP clause can be very useful on large tables with thousands of
records. Returning a large number of records can impact on performance.
Note: Not all database systems support the TOP clause.
SQL Server Syntax
SELECT TOP number|percent column_name(s) FROM
table_name
SQL TOP Example

The "teacher" table:

Now we want to select only 50% of the records from teacher table.

We use the following SELECT statement:

Select top 50 percent * from teacher

The Result will be like this:

DBS LAB MANUALS 58


Example 2

Now we want to select only top 3 of the records from teacher table.

We use the following SELECT statement:

Select top 3 * from teacher

The Result will be like this:

Task 7
Teacher

Use of In
Scenario: select + from + where + in ()

Query 1: Retrieve distinct states where tid is 5001, 5005, 5006.

Query 2: Retrieve distinct salary from teacher where city is Rawalpindi and
Mianwali.

Query 3: Retrieve salary and state where bonus is 11000, 9000 order by
salary.

DBS LAB MANUALS 59


Query 4: Display distinct Full name from teacher where t_lname is abid,
ahmad order by name descending.

Query 5: Retrieve all those teachers whose house allowance is 18000,


20000, 50000

Use of Between
Scenario: select + from + where + between
Query 1: retrieve tid, salary from teacher where salary greater than
36000 and less than 10000.

Query 2: retrieve t_fname from teacher where salary greater than 35000
and less than 6000.

Query 3: retrieve salary, city where tid less than 5003 and greater than
5007.

Query 4: retrieve salary, city from teacher where tid greater than 5005
and less than 5009.

Query 5: retrieve salary, bonus, t_fname from teacher where salary


greater than 108000 and less than 120000.

Exercise 7
Employee table stores the following data of student object

DBS LAB MANUALS 60


Student

1 Write a query to display the name (fName, lName) and age for all students
whose age is not in the range of 19 and 21

2 Write a query to display all the information of students whose cgpa is in the
range of 3.5 to 4.0 and age is not equal to 19.

3 Write a query to display all the information of employees whose city is not in
rwp and isb and age is greater than equal to 20.

4 Write a query to display the full name (first and last name), and city for all
students whose section is not A.

5 Write a query to select all record from students where last name in 'ali',
'ahmed'

DBS LAB MANUALS 61


Teacher

6 Write a query to display the full name (first and last) name, and salary, for all
teachers whose salary is out of the range 100000 and 125000 and make the result
set in descending order by the full name.

7 Write a query to display the full name (first and last), house allowance and
yearsofexp for those teachers who was doing Ph D and make the result set in
ascending order by the age.

8 Write a query that will retrieve top two record from Teachers order by Salary
Ascending.

9 Write a query that will top 50 percent record from teachers table order by
age descending.

10 Write a Sql Statement that will retrieve top 70 percent record from Teachers
whose salary is greater than equal to 120000.

DBS LAB MANUALS 62


Lab #08
Comparison Operators (LIKE, NOT LIKE)
The SQL LIKE Operator
There are two wildcards used in conjunction with the LIKE operator:
• % - The percent sign represents zero, one, or multiple characters
• _ - The underscore represents a single character
SQL LIKE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern

Here are some examples showing different LIKE operators with


'%' and '_' Wildcards:

LIKE Operator Example

The "Student" table:

Example 1(like start)

DBS LAB MANUALS 63


Now we want to select the student living in a city that starts with "R" from
the above table.

We use the following SELECT statement:

Select * from student where city like 'r%'

The Result will be like this:

The "%" sign can be used to define wildcards (missing letters in the
pattern) both before and after the pattern.

Example 2(like end)

Now we want to select the student living in a city that End with "b" from
the above table.

We use the following SELECT statement:

Select * from student where city like ‘%b’

The Result will be like this:

Example 2(like any position)

Now we want to select the students having fname containing "s" at any
position the above table.

We use the following SELECT statement:

Select * from student where fname like ’%s%’

DBS LAB MANUALS 64


The Result will be like this:

Example (2nd position)

SQL statement selects all students with lname that have "a" in the second
position:

Select * from student where lname like ‘_a%’

The Result will be like this:

Example (Like Not Start)

The following SQL statement selects all students with city that does NOT
start with "r":

Select * from student where city not like ‘r%’

The Result will be like this:

Example (Like Start charlist)

The following SQL statement selects all student with fname that start with
"r",”m”,”a” from the persons table.

Select * from student where fname like ‘[rma]%’

DBS LAB MANUALS 65


The Result will be like this:

Example (Like Not Start charlist)

The following SQL statement selects all student with city that Not start
with "r",”i”,”a” from the persons table.

Select * from student where city not like ‘[ria]%’

OR

Select * from student where city like ‘[^ria]%’

The Result will be like this:

Example (like start and at least 4 character)


The following SQL statement selects all student with a FName that starts with
"b" and are at least 4 characters in length:

Select * from student where fname like ‘b_%_%_%_’

The Result will be like this:

Example (like start and end character)


The following SQL statement selects all student with a LName that starts with
"a" and ends with "d":

Select * from student where lname like ‘a%d’

DBS LAB MANUALS 66


The Result will be like this:

Task 8

Teacher

Use of Like

Scenario: select+from+where+like

Query 1: retrieve all those teachers where t_lname first letter is I.

Query 2: retrieve all those teachers where fname starts with T.

Query 3: retrieve full name from teacher whose last letter of t_lname is q.

Query 4: retrieve salary from teachers where 2nd letter of t_fname is a.

Query 5: retrieve all those teachers where t_lname contains ee.

Exercise 8
1 Write a query to display the First Name of all teacher who have both
"b" and "c" in their first name

DBS LAB MANUALS 67


The Result will be like this:

DBS LAB MANUALS 68


2 Write a query to display all Teachers whose Last_Name start with “j” and end
with “d”.

3 Write a query to display the First_Name, Last_Name as Full_Name of all


teachers who’s First_Name Start with “a” or “b” or “c’ order by Last_Name
Descending.

4 Write a query to display the last name of teachers having 'e' as the third
character.

5 Write a query to display the last name of teachers whose names have exactly
6 characters.

6 Write a query to display the Name (First_Name, Last_Name) and salary for all
teachers whose experience is greater than 8.

7 Write a Sql Statement that will retrieve all those teahcers whose city contain
“a” at any position.

8 Write a Sql Statement that will retrieve name of teacher whose t_lname contain
pattern “A”, ”b”, ”d” at any position.

9 Write a Sql Statement that will retrieve name of teacher whose t_lname does
not contain pattern “A”, ”b”, ”d” at any position

10 Write a Sql Statement that will retrieve all teachers whose city not start with
“a” and not end with “d”.

DBS LAB MANUALS 69


Lab # 09
Aggregate function (min, max, avg, count, sum)
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a
column.
Useful aggregate functions:
 AVG() - Returns the average value
 COUNT() - Returns the number of
rows
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum
SQL AVG() Function
The AVG () Function
The AVG () function returns the average value of a numeric column.
SQL AVG() Syntax

SELECT AVG(column_name) FROM table_name

SQL AVG () Example


We have the following "student" table:

Now we want to find the average value of the "cgpa" fields.

We use the following SQL statement:

SELECT AVG(cgpa) AS [CGPA Average] FROM Student

DBS LAB MANUALS 70


The result-set will look like this:

Example 2

Now we want to find the average age of students

We use the following SQL statement:

Select avg (age) as [average age] from student

The result-set will look like this:

SQL COUNT () Function

SQL has many built-in functions for performing calculations on data.

SQL COUNT () Function


The COUNT () function returns the number of rows that matches a specified
criteria.

SQL COUNT (column_name) Syntax

SELECT COUNT(COLUMN_NAME) FROM TABLE_NAME

SQL COUNT (*) Syntax


The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM TABLE_NAME

SQL COUNT (DISTINCT column_name) Syntax


The COUNT (DISTINCT column_name) function returns the number of distinct values
of the specified column:
SELECT COUNT(DISTINCT COLUMN_NAME) FROM TABLE_NAME
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server,
but not with Microsoft Access.

DBS LAB MANUALS 71


SQL COUNT (column_name) Example
We have the following "course" table:

Example 1

Now we want to count the number of titles having cr_hours =3.

We use the following SQL statement:

SELECT COUNT(TITLE) AS [TOTAL TITLES]FROM COURSE WHERE


CR_HOURS=3

The Result will be like this:

SQL COUNT (*) Example


If we omit the WHERE clause, like this:
SELECT COUNT(*) AS [Total Course] FROM Course

The result-set will look like this:

SQL COUNT (DISTINCT column_name) Example


Now we want to count the number of unique categories in the "course" table.
We use the following SQL statement:
SELECT COUNT(DISTINCT CATEGORY) AS [TOTAL CATEGORIES] FROM
COURSE

The result-set will look like this:

DBS LAB MANUALS 72


The SQL MAX () Functions

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

SQL MAX () Syntax


SELECT MAX(COLUMN_NAME) FROM TABLE_NAME

SQL MAX () Example


We have the following "Course" table:

Now we want to find the largest value of the "cid" column.

We use the following SQL statement:

SELECT MAX(CID) AS [MAX COURSE ID] FROM COURSE

The Result will be like this:

SQL MIN () Function


The MIN () Function
The MIN () function returns the smallest value of the selected column.
SQL MIN () Syntax
SELECT MIN(column_name) FROM table_name

SQL MIN () Example


We have the following "Course" table:

DBS LAB MANUALS 73


Now we want to find the smallest value of the "cr_hours" column.

We use the following SQL statement:

SELECT MIN(cr_hours) AS [Min Credit Hours] FROM course

The result-set will look like this:

SQL SUM () Function


The SUM () Function
The SUM () function returns the total sum of a numeric column.

SQL SUM () Syntax


SELECT SUM(column_name) FROM table_name

SQL SUM () Example

Now we want to find the sum of all "Cr_hours" field.

We use the following SQL statement:

SELECT SUM(CR_HOURS) AS [TOTAL HOURS] FROM COURSE

The result-set will look like this:

Task 9
Teacher Table

DBS LAB MANUALS 74


“Functions” 1:“MAX”
Scenario: select+max () +from

Query 1: retrieve max salary from Teacher.

Query 2: retrieve max Bonus from teacher where t_fname starts with S.

Query 3: retrieve max yearsofexp from Teachers where age is in 30 and 35.

Query 4: retrieve max house allowance from teacher where qualification is


MS

Query 5: retrieve max salary where age is greater than 25 and less than 30.

2:“MIN”
Scenario: select + min ()+from

Query 1: retrieve min salary from Teacher.

Query 2: retrieve min Bonus from teacher where t_fname starts with S.

DBS LAB MANUALS 75


Query 3: retrieve min yearsofexp from Teachers where age is in 30 and 35.

Query 4: retrieve min house allowance from teacher where qualification is


MS

Query 5: retrieve min salary where age is greater than 25 and less than 30.

3:“Count”
Scenario: select + count () +from

Query 1: retrieve total number of distinct yearsofexp from teacher.

Query 2: retrieve total number of salaries whose qualification is MS.

Query 3: retrieve total number of distinct t_name from teacher.

Query 4: retrieve total number of salaries from sales where age is greater
than 28.

Query 5: retrieve total number of distinct qualifications from teacher

4: “Sum”
Scenario: select + sum () + from

Query 1: show total salary from teachers.

Query 2: retrieve total years of experience from teachers.

Query 3: retrieve total Bonus from Teacher where tid is 5001 and 5007.

DBS LAB MANUALS 76


Query 4: retrieve total House Allowance where age is greater than 30.

Query 5: retrieve sum of all bonus where t_lname is Ahmad.

5:“Avg”
Scenario: select +avg () + from

Query 1: show Average salary from teachers.

Query 2: retrieve Average years of experience from teachers.

Query 3: retrieve Average Bonus from Teacher where tid is 5001 and 5007.

Query 4: retrieve Average House Allowance where age is greater than 30.

Query 5: retrieve Average of all bonus where t_lname is Ahmad.

Exercise 9
Student

1 Write a
query to display Maximum cgpa of Students.

DBS LAB MANUALS 77


2 Write a query to display the highest First_Name alphabetically from student
table.

3 Write a query to display Minimum cgpa of Students.

4 Write a query to Display the lowest Last_Name alphabetically from student


table.

5 Write a query to display “average Age” of all students.

6 Write a query to display ‘total cgpa” of all Students.

7 Write a query to display the highest, lowest and average age from student
table.

8 Write a query to display total Number of students

9 Write a query to display total number of students whose city is distinct.

10 Write a query to display total number of Students whose Last_Name is


different.

Lab # 10
Aggregate Functions (GROUP Clause and HAVING Clause)

The SQL GROUP BY Statement

• The GROUP BY statement is used in conjunction with the aggregate


functions to group the result-set by one or more columns.
• The GROUP BY statement is often used with aggregate functions
(COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more
columns.

GROUP BY Syntax

DBS LAB MANUALS 78


SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value GROUP BY column_name

OR
SELECT column_name(s) FROM table_name WHERE condition GROUP BY
column_name(s) ORDER BY column_name(s)

SQL GROUP BY Example

We have the following "Course" table:

Now we want to find the total Categories of each Course.


We will have to use the GROUP BY statement to group the customers. We
use the following SQL statement:

Select category, count(category) as [total] from course group


by category

The Result will be like this:

Explanation of why the above SELECT statement cannot be used:


The SELECT statement above has two columns specified (Category and
Count (category). The "count(category)" returns a single value (that is
the total number of the "category" column), while "category" returns 6
values (one value for each row in the "Orders" table). This will therefore
not give us the correct result. However, you have seen that the GROUP
BY statement solves this problem.

DBS LAB MANUALS 79


GROUP BY More Than One Column
We can also use the GROUP BY statement on more than one column, like this:

select category, count(cr_hours)as[Credit Hours] from course


group by category,cr_hours

The Result will be like this:

SQL HAVING Clause


The HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not
be used with aggregate functions.

SQL HAVING Syntax

SELECT column_name, aggregate_function(column_name) FROM


table_name

WHERE column_name operator value

GROUP BY column_name

HAVING aggregate_function(column_name) operator value


SQL HAVING Example
We have the following "Course" table:

Now we want to find if any of the category have a total credit of less than 11.

DBS LAB MANUALS 80


We use the following SQL statement:
Select category,sum(cr_hours) as[total Credit Hours] from course
group by Category having sum(cr_hours)<11

Example 2

Now we want to find if the Category “CS" or "Math" have a total Cr_hours of
more than 10.
We add an ordinary WHERE clause to the SQL statement:
Select category,sum(cr_hours) as [total Hours] from Course where
category in(‘cs’,’math’) group by category having
sum(cr_hours)>10
The Result will be like this:

Task 10

Student

Query 1: Write a Sql Statement to retrieve no of Students

Query 2: Write a Sql Statement to retrieve fname, minimum age from student
group by section.

Query 3: Write a Sql Statement to retrieve lname, maximum cgpa from


student group by city.

DBS LAB MANUALS 81


Query 4: Write a Sql Statement to retrieve sid, total age from student group
by degree having total age less than 50

Query 5: Write a Sql Statement to retrieve Name, average age from student
group by section having average age greater than 50

Exercise 10
Teacher

“Group By”
Scenario: select + from +where +group by

Query 1: retrieve no. of Teachers in each City

Query 2: retrieve Qualification, minimum salary from teacher in each city

Query 3: retrieve city, maximum bonus from teacher in each qualification

Query 4: retrieve City, total salary from teacher in each city

Query 5: retrieve qualification, average house allowance from teacher group


by qualification

”Having”
Scenario: Select + from + group by + having

Query 1: retrieve no. of teacher in each city where city is Rawalpindi

DBS LAB MANUALS 82


Query 2: retrieve qualification, minimum salary from teacher in from distinct
qualification where minimum salary greater than 120500

Query 3: retrieve city maximum salary from teacher in each city where
maximum salary less than 120000

Query 4: retrieve city, total salary from teacher in each city where total salary
is less than 1900000

Query 5: retrieve city, number of teachers from teacher in each city where
number of teacher is greater than 4

Lab # 11
Create Database, Create Table, Alter Table, Adding
Constraints

Create Database
The CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a database.
SQL CREATE DATABASE Syntax
CREATE DATABASE database_name

CREATE DATABASE Example


Now we want to create a database called “testDB".
We use the following CREATE DATABASE statement:
CREATE DATABASE myDBS

To use your database. Write a simple query that given


below.
Use myDBS

DBS LAB MANUALS 83


SQL CREATE TABLE Statement
The CREATE TABLE Statement
The CREATE TABLE statement is used to create a table in a database.
SQL CREATE TABLE Syntax
CREATE TABLE table_name
(
column_name1 data_type, column_name2 data_type, column_name3
data_type,
)
CREATE TABLE Example

Now we want to create a table called "Persons" that contains five columns:
C_Id, L_Name, F_Name, Age, M_Income and City.
We use the following CREATE TABLE statement:
CREATE TABLE student
(
Sid int, fname varchar(50), lname varchar(50),
City varchar(100), age int, degree(50), semesterno int,
Section varchar(50),primary key(sid) )
The sid and age column is of type int and will hold a number. The LName,
FName and City columns are of type varchar with a maximum length of 50
characters. The empty "student" table will now look like this:

SQL ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.
The ALTER TABLE statement is also used to add and drop various constraints
on an existing table.

ALTER TABLE - ADD Column

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

Example:-
Alter table student add DateOfBirth int

The Result will be like this:

DBS LAB MANUALS 84


Change Data Type Example

Now we want to change the data type of the column named "DateOfBirth" in
the "Student" table.
We use the following SQL statement:
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;

Notice that the "DateOfBirth" column is now of type year and is going to hold
a year in a two- or four-digit format.

ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;

DROP COLUMN Example


Next, we want to delete the column named "DateOfBirth" in the "Student"
table.
We use the following SQL statement:
ALTER TABLE student
DROP COLUMN DateOfBirth;

The Result will be like this:

ALTER TABLE - ALTER/MODIFY COLUMN


To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;

Change Data Type Example


Now we want to change the data type of the column named "cgpa" in the
"student" table.

DBS LAB MANUALS 85


We use the following SQL statement:
ALTER TABLE Student
ALTER COLUMN semesterno varchar(2);

Rename column in table


You cannot use the ALTER TABLE statement in SQL Server to rename a
column in a table. However, you can use sp_rename, though Microsoft
recommends that you drop and recreate the table so that scripts and
stored procedures are not broken.

Syntax
The syntax to rename a column in an existing table in SQL Server is:
sp_rename 'table_name.old_column_name', 'new_column_name', 'COLUMN';

Example:
Sp_rename‘student.fname’,’first name’

Rename table
You cannot use the ALTER TABLE statement in SQL Server to rename a table.
However, you can use sp_rename, though Microsoft recommends that you
drop and recreate the table so that scripts and stored procedures are not
broken.
Syntax
The syntax to rename a table in SQL Server is: sp_rename
'old_table_name', 'new_table_name';
Example:-
This SQL Server example will use sp_rename to rename the Students table
to Student 1

Sp_rename ‘student’,’student 1’

Check Constraint
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in
a column.
If you define a CHECK constraint on a single column it allows only certain
values for this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.

The following constraints are commonly used in SQL:

DBS LAB MANUALS 86


• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
• FOREIGN KEY - Uniquely identifies a row/record in another table
• CHECK - Ensures that all values in a column satisfies a specific
condition

SQL NOT NULL Constraint


By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot
insert a new record, or update a record without adding a value to this field.
The following SQL ensures that the "ID", "Last_Name", and "First_Name"
columns will NOT accept NULL values:
Example
CREATE TABLE Student (
ID int NOT NULL,
Last_Name varchar (255) NOT NULL,
First_Name varchar (255) NOT NULL,
Age int
);

SQL UNIQUE Constraint


The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint per table.

SQL UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "ID" column when the
"student" table is created:
Example
CREATE TABLE Student (
ID int NOT NULL UNIQUE,
Last_Name varchar (255) NOT NULL,
First_Name varchar (255),
Age int
);
OR

DBS LAB MANUALS 87


CREATE TABLE student (
ID int NOT NULL,
Last_Name varchar (255) NOT NULL,
First_Name varchar (255),
Age int,
UNIQUE (ID)
);

UNIQUE constraint on multiple columns


To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
CREATE TABLE Student (
ID int NOT NULL,
Last_Name varchar(255) NOT NULL,
First_Name varchar(255),
Age int,
CONSTRAINT Uc_PersonID UNIQUE (ID, Last_Name) );
SQL CHECK Constraint on CREATE TABLE
To create a UNIQUE constraint on the "ID" column when the table is already
created, use the following SQL:

ALTER TABLE Student ADD UNIQUE (ID);

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a


database table.
Primary keys must contain UNIQUE values, and cannot contain NULL
values.
A table can have only one primary key, which may consist of single or
multiple fields.

SQL PRIMARY KEY on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "ID" column when the
"Student" table is created:
CREATE TABLE student (
ID int NOT NULL PRIMARY KEY,
Last_Name varchar (255) NOT NULL,
First_Name varchar (255),
Age int
);

DBS LAB MANUALS 88


To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY
KEY constraint on multiple columns, use the given below Syntax.
SQL syntax:
CREATE TABLE Student (
ID int NOT NULL,
Last_Name varchar (255) NOT NULL,
First_Name varchar (255),
Age int,
PRIMARY KEY (ID, Last_Name) );

SQL PRIMARY KEY on ALTER TABLE


To create a PRIMARY KEY constraint on the "ID" column when the table is
already created, use the following SQL:

Syntax
ALTER TABLE Student ADD PRIMARY KEY (ID);

PRIMARY KEY constraint on multiple columns on Alter Table


To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY
KEY constraint on multiple columns, use the following SQL syntax
Syntax:

ALTER TABLE Student


ADD CONSTRAINT Pk PRIMARY KEY (ID, Last_Name);

Note: If you use the ALTER TABLE statement to add a primary key, the
primary key column(s) must already have been declared to not contain NULL
values (when the table was first created).

DROP a PRIMARY KEY Constraint


To drop a PRIMARY KEY constraint, use the following SQL:
ALTER TABLE Student DROP PRIMARY KEY;

OR

ALTER TABLE Persons DROP CONSTRAINT PK_Person;

SQL FOREIGN KEY Constraint

A FOREIGN KEY is a key used to link two tables together.

A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.

DBS LAB MANUALS 89


The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table. Look
at the following two tables:

"Student" table:

The enrollment Table

Notice that the "sid" column in the "student" table points to the "sid" column
in the "enrollment" table.

The "sid" column in the "student" table is the PRIMARY KEY in the

The "sid" column in the "enrollment" table is a FOREIGN KEY

The FOREIGN KEY constraint is used to prevent actions that would destroy
links between tables.

The FOREIGN KEY constraint also prevents invalid data from being inserted
into the foreign key column, because it has to be one of the values
contained in the table it points to.

DBS LAB MANUALS 90


SQL FOREIGN KEY on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "sid" column when the
"enrollment" table is created: Example:-

CREATE TABLE enrollment (

Sid int foreign key references student(sid),

cid int foreign key references course (cid)

);

FOREIGN KEY constraint on multiple columns

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN


KEY constraint on multiple columns, use the following SQL syntax:

Example:-

CREATE TABLE enrollment (

Sid int foreign key references student(sid),

cid int foreign key references course (cid)

);

SQL FOREIGN KEY on ALTER TABLE


To create a FOREIGN KEY constraint on the "sid" column when the
"enrollment" table is already created, use the following SQL:
Example:

ALTER TABLE enrollment


ADD FOREIGN KEY (sid) REFERENCES student(sid);
-

FOREIGN KEY constraint on multiple columns


To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN
KEY constraint on multiple columns, use the following SQL syntax:

Example:-
ALTER TABLE enrollment
ADD CONSTRAINT FK FOREIGN KEY (sid) REFERENCES student(sid);

DBS LAB MANUALS 91


DROP a FOREIGN KEY Constraint
To drop a FOREIGN KEY constraint, use the following SQL:
Example Drop FOREIGN KEY

ALTER TABLE Orders


DROP FOREIGN KEY FK_PersonOrder;
Example Drop FOREIGN KEY constraint

ALTER TABLE Orders


DROP CONSTRAINT FK_PersonOrder;

SQL CHECK Constraint

The CHECK constraint is used to limit the value range that can be placed in a
column.

If you define a CHECK constraint on a single column it allows only certain


values for this column.

If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.

SQL CHECK on CREATE TABLE


The following SQL creates a CHECK constraint on the "Age" column when the
"student" table is created. The CHECK constraint ensures that you can not
have any person below 18 years:
Sql Check Example
CREATE TABLE student (
ID int NOT NULL,
Last_Name varchar(255) NOT NULL,
First_Name varchar(255),
Age int,
CHECK (Age>=18)
);
OR
CREATE TABLE Student (
ID int NOT NULL,
Last_Name varchar(255) NOT NULL,
First_Name varchar(255),
Age int CHECK (Age>=18) );

CHECK constraint on multiple columns


To allow naming of a CHECK constraint, and for defining a CHECK
constraint on multiple columns, use the following SQL syntax: SQL syntax:

DBS LAB MANUALS 92


CREATE TABLE Student (
ID int NOT NULL,
Last_Name varchar(255) NOT NULL,
First_Name varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK CHECK (Age>=18 AND City='rwp') );

SQL CHECK on ALTER TABLE


To create a CHECK constraint on the "Age" column when the table is already
created, use the following SQL:
Example:-
ALTER TABLE Student
ADD CHECK (Age>=18);

Alter CHECK constraint on multiple columns


To allow naming of a CHECK constraint, and for defining a CHECK constraint
on multiple columns, use the following SQL syntax:
SQL syntax:
ALTER TABLE Student
ADD CONSTRAINT CHK_Age CHECK (Age>=18 AND City='Rwp');

DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:
Example DROP a CHECK Constraint

ALTER TABLE Student


DROP CONSTRAINT CHK_Age;

OR

ALTER TABLE Student


DROP CHECK CHK_Age;

Task 11
1: Write a Sql Statement to create new database and write Sql statement to
use new database.

DBS LAB MANUALS 93


2: Write a Sql Statement to create table Student

3 Write a Sql Statement to Add column in Student table.

4 Write a Sql Statement to add constraint primary key in Student table.

5 Write a Sql Statement to Drop a check Constraint.

Exercise 11
1 Write a SQL statement to create a simple table teacher including
columns tid, name and city.

2 Write a Sql Statement to add column in Teacher table and also write
statement to drop column from Teacher table.

3 Write a Sql Statement to add constraint in Teacher table and also


write statement to drop constraint from Teacher table.

4 Write a Sql Statement to rename any column in Teacher table and


write a Sql statement to rename Teacher table to Professor.

DBS LAB MANUALS 94


5 Write a Sql Statement for you forget to create primary key in Teacher
table. Now you have to create composite key (tid,name). tid and name
both are null.

6 Write a SQL statement to create a table named course including


columns cid, crs_name and cr_hrs and make sure that the cid column will
be a key field which will not contain any duplicate data at the time of
insertion.

7 Write a SQL statement to create a table named course including


columns cid, crs_name and cr_hrs and make sure that no names except
DBS, OOP, MVC, WDD will be entered in the table.

8 Write a SQL statement to create a table named student including


columns sid, Name, Age, Cgpa and check whether the cgpa exceeding the
upper limit 4.

9 Write a SQL statement to create a table named Student including


columns sid, name, age, CGPA, and make sure that, the default value for
name is blank and age is 18 and cgpa is NULL will be entered automatically
at the time of insertion if no value assigned for the specified columns.

10 Write a SQL statement to create a table Student including columns


sid, name, age and make sure that the column Sid will be unique and store
an auto incremented value.

Lab #12
Insert, Update, Delete, Drop

DBS LAB MANUALS 95


SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a
table.

The INSERT INTO Statement


The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be
inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be
inserted:
INSERT INTO table_name (column1, column2, column3,...) VALUES
(value1, value2, value3,...)
SQL INSERT INTO Example
We have the following "Student" table:

Now we want to insert a new row in the "Student" table.

We use the following SQL statement:

INSERT INTO Student


VALUES (11,'Muhammad', 'Abbas', 'ISB', '19',3.4,’MCS’,5,’B’)
The "Student" table will now look like this:

DBS LAB MANUALS 96


Insert Data Only in Specified Columns
It is also possible to only add data in specific columns.
The following SQL statement will add a new row, but only add data in the
"sid", "fname" and the "city" columns:
Example
INSERT INTO student (sid, fname, city) VALUES
(12, 'Ajmal', 'ISB')

The "Student" table will now look like this:

SQL UPDATE Statement


The UPDATE statement is used to update records in a table.

The UPDATE Statement


The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE table_name

DBS LAB MANUALS 97


SET column1=value, column2=value2,... WHERE
some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause
specifies which record or records that should be updated. If you omit the
WHERE clause, all records will be updated!
SQL UPDATE Example

The "student" table:

Now we want to update the person "ali" in the "student" table.

We use the following SQL statement:

UPDATE student
SET City='Islamabad' WHERE FName='Ali'

The "Student" table will now look like this:

SQL DELETE Statement


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

The DELETE Statement

DBS LAB MANUALS 98


The DELETE statement is used to delete rows in a table.
SQL DELETE Syntax
DELETE FROM table_name
WHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause
specifies which record or records that should be deleted. If you omit the
WHERE clause, all records will be deleted!
SQL DELETE Example
The "Student" table:

Now we want to delete the person "Ajmal, Nazir" in the "Persons" table.

We use the following SQL statement:

DELETE FROM Student


WHERE LName='ahmad'

The "Student" table will now look like this:

Delete All Rows


It is possible to delete all rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact:
Syntax
DELETE FROM table_name or

DBS LAB MANUALS 99


DELETE * FROM table_name

Note: Be very careful when deleting records. You cannot undo this
statement!

The DROP DATABASE Statement


The DROP DATABASE statement is used to drop an existing SQL database.

Syntax

DROP DATABASE databasename;

Note: Be careful before dropping a database. Deleting a database will result


in loss of complete information stored in the database!
Example
The following SQL statement drops the existing database "myDBS":
DROP DATABASE myDBS;

Tip: Make sure you have admin privilege before dropping any database. Once
a database is dropped, you can check it in the list of databases with the
following SQL command: SHOW DATABASES;

The SQL DROP TABLE Statement


The DROP TABLE statement is used to drop an existing table in a database.

Syntax

DROP TABLE table_name;

Note: Be careful before dropping a table. Deleting a table will result in loss of
complete information stored in the table!
SQL DROP TABLE Example
The following SQL statement drops the existing table "Students":
DROP TABLE Students;
SQL TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data inside a table, but
not the table itself.

Syntax

DBS LAB MANUALS 100


TRUNCATE TABLE table_name;

Example
TRUNCATE TABLE Student;

Task 12
1 Write a Sql statement to insert data in Student table.

2 Write a Sql Statement to insert data in Course table.

4 Write a Sql Statement to update data from Student table where


lname is equal to ‘Ahmad’.

5 Write a Sql statement to delete a record from Student where cgpa is


equal to 3.7.

Exercise 12

1 Write a Sql statement to insert data in Student objects.

2 Write a Sql statement to insert data in Teacher objects.

3 Write a Sql statement to update data from Student where cgpa>3.5

4 Write a Sql statement to delete data from Customer Where name equal to
“Ali”.

5 Write a Sql statement to delete all those students who are living in Rwp.

DBS LAB MANUALS 101


6 Write a Sql statement to update lname of Student whose fname start with
‘a’.

7 Write a Sql statement to update Student Age to 21 whose degree is MCS.

8 Write a Sql statement to delete Student whose age is greater than 21.

9 Write a Sql Statement to delete only data from Student not the Student
table.

10 Write a Sql Statement to delete all those Students whose age not in
range of 20 and 22.

Lab #13
Sql Views and Sql Subqueries
SQL Views
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view
are fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from one single table.

CREATE VIEW Syntax

CREATE VIEW view_name AS SELECT


column1, column2, ...
FROM table_name

DBS LAB MANUALS 102


WHERE condition;
Note: A view always shows up-to-date data! The database engine recreates
the data, using the view's SQL statement, every time a user queries a view.

SQL CREATE VIEW Examples


If you have the Northwind database you can see that it has several views
installed by default.
The view "Salesmans_View" lists all active products (Salesman’s that have
commission 0.12) from the "Salesman’s" table. The view is created with the following
SQL:
CREATE VIEW [Salesmans_View] AS
SELECT salesman_id, Name FROM
Salesman’s
WHERE commission = 0.12;
Then, we can query the view as follows:
SELECT * FROM [Salesmans_View];
Another view in the Northwind sample database selects every product in the
"Products" table with a unit price higher than the average unit price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, UnitPrice
FROM Products
WHERE UnitPrice > (SELECT AVG (UnitPrice) FROM Products);
We can query the view above as follows:
SELECT * FROM [Products Above Average Price];
Another view in the Northwind database calculates the total sale for each
category in 1997. Note that this view selects its data from another view
called "Product Sales for 1997":
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName, Sum (ProductSales) AS CategorySales
FROM [Product Sales for 1997] GROUP
BY CategoryName;
We can query the view above as follows:
SELECT * FROM [Category Sales For 1997];
We can also add a condition to the query. Let's see the total sale only for the
category "Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName = 'Beverages';

SQL Updating a View


You can update a view by using the following syntax:

DBS LAB MANUALS 103


SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS


SELECT column1, column2,…
FROM table_name
WHERE condition;

Example
Now we want to add the "Category" column to the "Current Product List"
view. We will update the view with the following SQL:
CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID, ProductName, Category
FROM Products
WHERE Discontinued = No;

SQL Dropping a View


You can delete a view with the DROP VIEW command.
SQL DROP VIEW Syntax
DROP VIEW view_name;

SQL Subqueries
 A subquery is a SQL statement that has another SQL query
embedded in the Where or the having clause  A subquery is
a SQL query within a query.
 Subqueries are nested queries that provide data to the
enclosing query.
 Subqueries can return individual values or a list of
records
 Subqueries must be enclosed with parenthesis

Syntax
The syntax for a subquery when the embedded SQL statement is part of
the WHERE condition is as follows:

SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"
FROM "table_name2"
WHERE "condition");

DBS LAB MANUALS 104


[Comparison Operator] could be equality operators such as =, >, <, >=, <=.
It can also be a text operator such as "LIKE". The portion in red is
considered as the "inner query," while the portion in Green is considered as
the "outer query."
Examples
We use the following tables for our examples.
Student

Example 1: Simple subquery


To use a subquery to find the data of youngest student

Select * from student where age in(select min(age) from student)

Result:

This type of subquery is called a simple subquery.


Example 2:
Consider 2 tables with student table

Course Enrollment

DBS LAB MANUALS 105


Now we want to show those students who have enrolled course with 3 credit
hours

Select * from student where sid in(select sid from enrollment


where cid in(select cid from course where cr_hours=3))

The Result will be like this:

Task 13
Student

Course Enrollment

DBS LAB MANUALS 106


1. Write a Sql Statement to retrieve youngest student.

2. Write a Sql Statement to retrieve name of student who registered CS

3. Write a Sql Statement to Display student who registered courses of


category MATH.

4. Write a Sql Statement to Display Name of Student who live in Rawalpindi


and studying Management.

5. Write a Sql Statement to display title of all courses registered by ALI.

6. Write a Sql Statement to Display title of courses which are registered by


either Ali or Basit

7. Write a query to create a view for those salesmen belongs to the city New
York.

8. Write a query to create a view for all salesmen with columns salesman_id,
name, and city.

DBS LAB MANUALS 107


9. Write a query to find the salesmen of the city New York who achieved the
commission more than 13%.

DBS LAB MANUALS 108


Lab # 14

SQL Joins
SQL joins are used to query data from two or more tables, based on a
relationship between certain columns in these tables.

The JOIN keyword is used in an SQL statement to query data from two or more
tables, based on a relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
A primary key is a column (or a combination of columns) with a unique value for
each row. Each primary key value must be unique within the table. The purpose is
to bind data together, across tables, without repeating all of the data in every
table.

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:

• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Return all records from the left table, and the
matched records from the right table
• RIGHT (OUTER) JOIN: Return all records from the right table, and the
matched records from the left table
• FULL (OUTER) JOIN: Return all records when there is a match in either
left or right table

DBS LAB MANUALS 109


SQL INNER JOIN Keyword
The INNER JOIN keyword return rows when there is at least one match in both
tables.
SQL INNER JOIN Syntax
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name

PS: INNER JOIN is the same as JOIN.


SQL INNER JOIN Example The
"Person" table:

The "Orders" table:

Example

DBS LAB MANUALS 110


Now we want to list all the persons with any orders.

We use the following SELECT statement:

SELECT Person.F_Name, Person.L_Name, Orders.OrderNo


FROM Person
INNER JOIN Orders
ON Person.p_id=Orders.p_id ORDER BY Person.F_Name

The result-set will look like this:

The INNER JOIN keyword return rows when there is at least one match in both
tables. If there are rows in "Persons" that do not have matches in "Orders",
those rows will NOT be listed.

SQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all rows from the left table (table_name1), even if
there are no matches in the right table (table_name2).
SQL LEFT JOIN Syntax
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.


SQL LEFT JOIN Example The
"Person" table:

The "Orders" table:

DBS LAB MANUALS 111


Now we want to list all the persons and their orders - if any, from the tables
above.

We use the following SELECT statement:

SELECT Person.F_Name, Person.L_Name, Orders.OrderNo


FROM Person
LEFT JOIN Orders
ON Person.p_id=Orders.p_id ORDER BY Person.F_Name

The result-set will look like this:

The LEFT JOIN keyword returns all the rows from the left table (Persons), even if
there are no matches in the right table (Orders).

SQL RIGHT JOIN Keyword


The RIGHT JOIN keyword Return all rows from the right table (table_name2),
even if there are no matches in the left table (table_name1).
SQL RIGHT JOIN Syntax
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2

ON table_name1.column_name=table_name2.column_name
PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

DBS LAB MANUALS 112


SQL RIGHT JOIN Example The
"Persons" table:

The "Orders" table:

Now we want to list all the orders with containing persons - if any, from the
tables above.

We use the following SELECT statement:

SELECT Person.F_Name, Person.L_Name, Orders.OrderNo


FROM Person
RIGHT JOIN Orders
ON Person.p_id=Orders.p_id ORDER BY Person.F_Name

The result-set will look like this:

The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if
there are no matches in the left table (Persons).

SQL FULL JOIN Keyword


The FULL JOIN keyword return rows when there is a match in one of the tables.
SQL FULL JOIN Syntax

DBS LAB MANUALS 113


SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name

SQL FULL JOIN Example


The "Person" table:

The "Orders" table:

Now we want to list all the persons and their orders, and all the orders with their
persons.

We use the following SELECT statement:

SELECT Person.F_Name, Person.L_Name, Orders.OrderNo


FROM Person
FULL JOIN Orders
ON Person.p_id=Orders.p_id ORDER BY Person.F_Name

The result-set will look like this:

DBS LAB MANUALS 114


The FULL JOIN keyword returns all the rows from the left table (Persons), and all
the rows from the right table (Orders). If there are rows in "Persons" that do not
have matches in "Orders", or if there are rows in "Orders" that do not have
matches in "Persons", those rows will be listed as well.

Task 14

1 Write a query that will display all those students who have registered a
course which is taught by a teacher having name Aslam.

2 write a query that will display tname and course title where category is CS.

3 write a query that will display name of teacher who are teaching a course
which is registered by a student having Cgpa greater than 3.0.

DBS LAB MANUALS 115


4 Write a query that will display all those Courses which is assign to Students
having name Adnan.

5 Write a query that will display all those course which are registered by
student having name Ali.

Exercise 14

We have data of Doctor and patients stored in the following tables.


Doctor Table:

Patient Table:

Ward Table:

Nurse Table:

DBS LAB MANUALS 116


1 Write a query to show records of those patients who are being treated
by Female Doctors.

2 Write a query to show City and ages of those patients who are treated
by doctors who age is between 30 to 40 years old.

3 Write a query to show nurse ID and address of those nurses whose are
managing ward where ward type is adult.

4 Write a query to all records of wards which are managed by nurses


whose salary is between 600 to 800.

5 Write a query to show name, age, gender of those doctors who are
assigned to projects whose duration of project is maximum.

6 Write a query to show patient ID, name of the patient(s) who is being
treated by the doctor whose salary is the lowest.

7 Write a query to show name, duration of those projects who are


assigned to doctors whose age lies between 35 to 45.

8 Write a query to show name of those doctors who are treating patients
who reside in Islamabad.

DBS LAB MANUALS 117


9 Write a query to show name and salary of those nurses whose nurse
are managing ward with 4 beds.

10 Write a query to show name of those projects who are assigned to


doctors whose gender is female.

LAB #15
Relational Algebraic Operators
SQL UNION Operator
The SQL UNION operator combines two or more SELECT statements.

The UNION operator is used to combine the result-set of two or more SELECT
statements.
Notice that each SELECT statement within the UNION must have the same
number of columns. The columns must also have similar data types. Also,
the columns in each SELECT statement must be in the same order.
SQL UNION Syntax
SELECT column_name(s) FROM table_name1 UNION
SELECT column_name(s) FROM table_name2

Note: The UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL.
SQL UNION ALL Syntax
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2

PS: The column names in the result-set of a UNION are always equal to the
column names in the first SELECT statement in the UNION.
SQL UNION Example
Look at the following tables:
"Employees_Rwp":
E_ID E_Name
01 Ashiq Hussain
02 Ahmed Raza
03 Akhter Rehmani
04 Muhammad Arshad

DBS LAB MANUALS 118


"Employees_Isb":
E_ID E_Name
01 Tanveer Abbas
02 Awais Qadir
03 Akhter Rehmani
04 Azeem Javed
Now we want to list all the different employees in Rwp and Isb.
We use the following SELECT statement:
SELECT E_Name FROM Employees_Rwp
UNION
SELECT E_Name FROM Employees_Isb
The result-set will look like this:
E_Name
Ashiq Hussain
Ahmed Raza
Akhter Rehmani
Muhammad Arshad
Tanveer Abbas
Awais Qadir
Azeem Javed
Note: This command cannot be used to list all employees in Rwp and Isb. In the
example above we have two employees with equal names, and only one of them
will be listed. The UNION command selects only distinct values.

SQL UNION ALL Example


Now we want to list all employees in Rwp and Isb:
SELECT E_Name FROM Employees_Rwp
UNION ALL
SELECT E_Name FROM Employees_Isb
Result
E_Name
Ashiq Hussain
Ahmed Raza
Akhter Rehmani
Muhammad Arshad
Tanveer Abbas
Awais Qadir
Akhter Rehmani
Azeem Javed

DBS LAB MANUALS 119


Exercise 15

Salesman Table

salesman_id name city commission


5001 James Hoog New York 0.15
5002 Nail Knite Paris 0.13
5005 Pit Alex London 0.11
5006 Mc Lyon Paris 0.14
5003 Lauson Hen 0.12
5007 Paul Adam Rome 0.13

Customer Table

customer_id cust_name city grade salesman_id


3002 Nick Rimando New York 100 5001
3005 Graham Zusi California 200 5002
3001 Brad Guzan London 5005
3004 Fabian Johns Paris 300 5006
3007 Brad Davis New York 200 5001
3009 Geoff Camero Berlin 100 5003
3008 Julian Green London 300 5002
3003 Jozy Altidor Moscow 200 5007
Order Table
ord_no purch_amt ord_date customer_id salesman_id
---------- ---------- ---------- ----------- -----------
70001 150.5 2012-10-05 3005 5002
70009 270.65 2012-09-10 3001 5005
70002 65.26 2012-10-05 3002 5001
70004 110.5 2012-08-17 3009 5003
70007 948.5 2012-09-10 3005 5002
70005 2400.6 2012-07-27 3007 5001
70008 5760 2012-09-10 3002 5001
70010 1983.43 2012-10-10 3004 5006
70003 2480.4 2012-10-10 3009 5003
70012 250.45 2012-06-27 3008 5002
70011 75.29 2012-08-17 3003 5007
70013 3045.6 2012-04-25 3002 5001

DBS LAB MANUALS 120


1: Write a query to display all salesmen and customer located in London.

2: Write a query to display distinct salesman and their cities.

3: Write a query to display all the salesmen and customer involved in this
inventory management system.

4: Write a query to make a report of which salesman produce the largest


and smallest orders on each date.

5: Write a query to make a report of which salesman produce the largest and
smallest orders on each date and arranged the orders number in smallest to the
largest number.

6: Write a query to list all the salesmen, and indicate those who do not have
customers in their cities.

7: Write a query to that appends strings to the selected fields, indicating whether
or not a specified salesman was matched to a customer in his city.

8: Create a union of two queries that shows the names, cities, and ratings of all
customers. Those with a rating of 200 or greater will also have the words "High
Rating", while the others will have the words "Low Rating".

DBS LAB MANUALS 121


9: Write a command that produces the name and number of each salesman and
each customer with more than one current order. Put the results in alphabetical
order.

Lab # 16
SQL Cross Join
What is Cross Join in SQL?
The SQL CROSS JOIN produces a result set which is the number of rows in the first
table multiplied by the number of rows in the second table if no WHERE clause is
used along with CROSS JOIN. This kind of result is called as Cartesian Product.

If WHERE clause is used with CROSS JOIN, it functions like an INNER JOIN.

An alternative way of achieving the same result is to use column names separated by
commas after SELECT and mentioning the table names involved, after a FROM
clause.

Syntax:
SELECT *
FROM table1
CROSS JOIN table2;
Pictorial Presentation of Cross Join syn
Example:
Here is an example of cross join in SQL between two tables.
Sample table: foods

+---------+--------------+-----------+------------+
| ITEM_ID | ITEM_NAME | ITEM_UNIT | COMPANY_ID |
+---------+--------------+-----------+------------+
| 1 | Chex Mix | Pcs | 16 |

DBS LAB MANUALS 122


| 6 | Cheez-It | Pcs | 15 |
| 2 | BN Biscuit | Pcs | 15 |
| 3 | Mighty Munch | Pcs | 17 |
| 4 | Pot Rice | Pcs | 15 |
| 5 | Jaffa Cakes | Pcs | 18 |
| 7 | Salt n Shake | Pcs | |
+---------+--------------+-----------+------------+

Sample table: company


+------------+---------------+--------------+
| COMPANY_ID | COMPANY_NAME | COMPANY_CITY |
+------------+---------------+--------------+
| 18 | Order All | Boston |
| 15 | Jack Hill Ltd | London |
| 16 | Akas Foods | Delhi |
| 17 | Foodies. | London |
| 19 | sip-n-Bite. | New York |
+------------+---------------+--------------+

To get item name and item unit columns from foods table and company name,
company city columns from company table, after a CROSS JOINING with these
mentioned tables, the following SQL statement can be used:

SQL Code:
SELECT foods.item_name, foods.item_unit, company.company_name,

company.company_city

FROM foods CROSS

JOIN Company; or

SQL Code:
SELECT foods.item_name,foods.item_unit,
company.company_name,company.company_city
FROM foods,company;
How cross joining happend into two tables

DBS LAB MANUALS 123


Output:
ITEM_NAME ITEM_UNIT COMPANY_NAME COMPANY_CITY
--------------- ---------- --------------- ---------------
Chex Mix Pcs Order All Boston
Cheez-It Pcs Order All Boston
BN Biscuit Pcs Order All Boston
Mighty Munch Pcs Order All Boston
Pot Rice Pcs Order All Boston
Jaffa Cakes Pcs Order All Boston
Salt n Shake Pcs Order All Boston
Chex Mix Pcs Jack Hill Ltd London
Cheez-It Pcs Jack Hill Ltd London
BN Biscuit Pcs Jack Hill Ltd London
Mighty Munch Pcs Jack Hill Ltd London
Pot Rice Pcs Jack Hill Ltd London
Jaffa Cakes Pcs Jack Hill Ltd London
Salt n Shake Pcs Jack Hill Ltd London
Chex Mix Pcs Akas Foods Delhi
Cheez-It Pcs Akas Foods Delhi
BN Biscuit Pcs Akas Foods Delhi
Mighty Munch Pcs Akas Foods Delhi
Pot Rice Pcs Akas Foods Delhi
Jaffa Cakes Pcs Akas Foods Delhi
Salt n Shake Pcs Akas Foods Delhi Chex
Mix Pcs Foodies. London
.........
.........
More presentaion of the said output:

DBS LAB MANUALS 124


Exercise 16

Salesman Table

salesman_id name city commission


5001 James Hoog New York 0.15
5002 Nail Knite Paris 0.13
5005 Pit Alex London 0.11
5006 Mc Lyon Paris 0.14
5003 Lauson Hen 0.12
5007 Paul Adam Rome 0.13

Customer Table

customer_id cust_name city grade salesman_id


3002 Nick Rimando New York 100 5001
3005 Graham Zusi California 200 5002

DBS LAB MANUALS 125


3001 Brad Guzan London 5005
3004 Fabian Johns Paris 300 5006
3007 Brad Davis New York 200 5001
3009 Geoff Camero Berlin 100 5003
3008 Julian Green London 300 5002
3003 Jozy Altidor Moscow 200 5007
Order Table
ord_no purch_amt ord_date customer_id salesman_id
---------- ---------- ---------- ----------- -----------
70001 150.5 2012-10-05 3005 5002
70009 270.65 2012-09-10 3001 5005
70002 65.26 2012-10-05 3002 5001
70004 110.5 2012-08-17 3009 5003
70007 948.5 2012-09-10 3005 5002
70005 2400.6 2012-07-27 3007 5001
70008 5760 2012-09-10 3002 5001
70010 1983.43 2012-10-10 3004 5006
70003 2480.4 2012-10-10 3009 5003
70012 250.45 2012-06-27 3008 5002
70011 75.29 2012-08-17 3003 5007
70013 3045.6 2012-04-25 3002 5001

1: Write a SQL statement to prepare a list with salesman name, customer name and
their cities for the salesmen and customer who belongs to the same city.

2: Write a SQL statement to make a list with order no, purchase amount, customer
name and their cities for those orders which order amount between 500 and 2000.

3: Write a SQL statement to know which salesman are working for which customer.

4: Write a SQL statement to find the list of customers who appointed a salesman for
their jobs who gets a commission from the company is more than 12%.

DBS LAB MANUALS 126


5: Write a SQL statement to find the list of customers who appointed a salesman for
their jobs who does not live in the same city where their customer lives, and gets a
commission is above 12%.

6: Write a SQL statement to find the details of a order i.e. order number, order date,
amount of order, which customer gives the order and which salesman works for that
customer and how much commission he gets for an order.

7: Write a SQL statement to make a join on the tables salesman, customer and orders
in such a form that the same column of each table will appear once and only the
relational rows will come.

8: Write a SQL statement to make a list in ascending order for the customer who
works either through a salesman or by own.

9: Write a SQL statement to make a list in ascending order for the customer who holds
a grade less than 300 and works either through a salesman or by own.

10: Write a SQL statement to make a report with customer name, city, order number,
order date, and order amount in ascending order according to the order date to find
that either any of the existing customers have placed no order or placed one or more
orders.

DBS LAB MANUALS 127


DBS LAB MANUALS 126

You might also like