Lab Mannual DBMS
Lab Mannual DBMS
(Publisher:???)
Author(s): Prof. Dr. Munir Ahmed ISBN: B IIT
???? Serie
Learning Objectives: By the end of the lab work, students should have
following skills; Lab Manual
Databas
Sr. Learning Objective
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
What is SQL?
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.
Now click on New Query Button its open new Screen like this to write
queries.
Schema/ Meta-data
For Teacher
For Allocation
For Enrollment
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
Example:
Selecting Student sid, city, age
Exercise 1
Student table stores the following data of student object;
5) Write a query that will retrieve city, age and Name of a students.
10) Write a Sql Statement that will retrieve all record of sales.
Example
Task 2
b. Write a Sql Statement to retrieve any two column 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.
Lab # 03
Concatenation Operator, Distinct & Duplicate Record
Retrieval
Example
The query for concatenation of First Name with Last Name of student is as
follows:
RESULT
Example
The query for concatenation of Degree with section of student is as
follows:
RESULT
Figure 1
Now we want to select only the distinct values from the column named
"City" from the table above.
Task 3
1 Write a Sql Statement to merged fname and lname as Full Name from
Student table.
3 Write a Sql Statement to retrieve all those student whose age is not
duplicate/repeated.
Exercise 3
Teacher table stores the following data of teacher object;
Teacher
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.
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
Example 2
Now we want to select all the students from the table above, however, we
want to sort the students by their Age
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 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.
Example: 2
Now we want to select only those students who have age equal to 18 in
student table.
Example: 3
Now we want to select only those students who have M_Income cgpa =
3.4 from the student table.
SQL uses single quotes around text values (most database systems will
also accept double quotes).
Task 4
Teacher table stores the following data of teacher object;
Teacher
2 Write a query that will retrieve data of teachers whose bonus is 11000.
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’.
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.
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":
Example: 2
Now we want to select only those students with the first name equal to
"Saad" AND the last name equal to "Amir":
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":
Example: 2
Now we want to select only those persons with the last name equal to
‘ahmad’ or cgpa=3.4
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’;
Example: 2
Now we want to select all those students where cgpa not equal to 3.4
from the student table.
Task 5
The tables and the data in the tables from which the queries are written are
given below:
Course
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 4: write a query that will retrieve all the data from coursewhere cid
is equal to 1010 and category is not cs.
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”.
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”.
7: write a query that will retrieve the cgpa from students where age is
either 18 or 20.
9: Write a Sql Statement to retrieve all students where cgpa not equal to
2.4 and 3.4
Lab # 06
Comparison Operators
Comparison Operators
A comparison (or relational) operator is a mathematical symbol which is
used to compare two values.
Operator Description
Now we want to select all those Students whose age is greater than 20.
Now we want to select all those Students whose cgpa is less than or equal
to 3.4.
Example: 2(<>)
Now we want to select all those Students whose city is not equal to rwp.
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.
4 Write a query that will retrieve all the data from course where category
is CS and cr_hours is not 3.
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”.
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
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.
Now we want to select the Student with a sid between 3 and 6 from the
table above.
Now we want to select the Student with Age between 20 and 21 from the
table above.
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
IN Operator Example
The student table
Now we want to select the student fName equal to "Ali" or "Nabeel" from
the table above.
Now we want to select the student with city equal to "Rwp" or "isb" from
the table above.
Now we want to select the students with city is equal to NOT NULL from
the table student.
Now we want to select the students whose age is not between 19 and 22.
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
Not In Example
Now we want to select the students with sid not in 3,6,8 from student
table
BETWEEN with IN
Example
Select * from student where (age between 19 and 20) and city
not in(‘karachi’,’multan’)
Now we want to select only 50% of the records from teacher table.
Now we want to select only top 3 of the records from teacher table.
Task 7
Teacher
Use of In
Scenario: select + from + where + in ()
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.
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.
Exercise 7
Employee table stores the following data of student object
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'
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.
The "%" sign can be used to define wildcards (missing letters in the
pattern) both before and after the pattern.
Now we want to select the student living in a city that End with "b" from
the above table.
Now we want to select the students having fname containing "s" at any
position the above table.
SQL statement selects all students with lname that have "a" in the second
position:
The following SQL statement selects all students with city that does NOT
start with "r":
The following SQL statement selects all student with fname that start with
"r",”m”,”a” from the persons table.
The following SQL statement selects all student with city that Not start
with "r",”i”,”a” from the persons table.
OR
Task 8
Teacher
Use of Like
Scenario: select+from+where+like
Query 3: retrieve full name from teacher whose last letter of t_lname is q.
Exercise 8
1 Write a query to display the First Name of all teacher who have both
"b" and "c" in their first name
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”.
Example 2
Example 1
The MAX () function returns the largest value of the selected column.
Task 9
Teacher Table
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 5: retrieve max salary where age is greater than 25 and less than 30.
2:“MIN”
Scenario: select + min ()+from
Query 2: retrieve min Bonus from teacher where t_fname starts with S.
Query 5: retrieve min salary where age is greater than 25 and less than 30.
3:“Count”
Scenario: select + count () +from
Query 4: retrieve total number of salaries from sales where age is greater
than 28.
4: “Sum”
Scenario: select + sum () + from
Query 3: retrieve total Bonus from Teacher where tid is 5001 and 5007.
5:“Avg”
Scenario: select +avg () + from
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.
Exercise 9
Student
1 Write a
query to display Maximum cgpa of Students.
7 Write a query to display the highest, lowest and average age from student
table.
Lab # 10
Aggregate Functions (GROUP Clause and HAVING Clause)
GROUP BY Syntax
OR
SELECT column_name(s) FROM table_name WHERE condition GROUP BY
column_name(s) ORDER BY column_name(s)
GROUP BY column_name
Now we want to find if any of the category have a total credit of less than 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 2: Write a Sql Statement to retrieve fname, minimum age from student
group by section.
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
”Having”
Scenario: Select + from + group by + having
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
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:
Example:-
Alter table student add DateOfBirth int
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.
To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):
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.
Syntax
ALTER TABLE Student ADD PRIMARY KEY (ID);
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).
OR
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
"Student" 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 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.
);
Example:-
);
Example:-
ALTER TABLE enrollment
ADD CONSTRAINT FK FOREIGN KEY (sid) REFERENCES student(sid);
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 table it can limit the values in certain
columns based on values in other columns in the row.
OR
Task 11
1: Write a Sql Statement to create new database and write Sql statement to
use new database.
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.
Lab #12
Insert, Update, Delete, Drop
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:
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
UPDATE student
SET City='Islamabad' WHERE FName='Ali'
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.
Note: Be very careful when deleting records. You cannot undo this
statement!
Syntax
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;
Syntax
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
Example
TRUNCATE TABLE Student;
Task 12
1 Write a Sql statement to insert data in Student table.
Exercise 12
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.
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.
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 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");
Result:
Course Enrollment
Task 13
Student
Course Enrollment
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.
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.
• (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
Example
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.
The LEFT JOIN keyword returns all the rows from the left table (Persons), even if
there are no matches in the right table (Orders).
ON table_name1.column_name=table_name2.column_name
PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
Now we want to list all the orders with containing persons - if any, from the
tables above.
The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if
there are no matches in the left table (Persons).
Now we want to list all the persons and their orders, and all the orders with their
persons.
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.
5 Write a query that will display all those course which are registered by
student having name Ali.
Exercise 14
Patient Table:
Ward Table:
Nurse Table:
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.
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.
8 Write a query to show name of those doctors who are treating patients
who reside in Islamabad.
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
Salesman Table
Customer Table
3: Write a query to display all the salesmen and customer involved in this
inventory management system.
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".
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 |
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
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
Salesman Table
Customer Table
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%.
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.