0% found this document useful (0 votes)
127 views13 pages

DBS LAB Manual Updated

The document is a lab manual for a database systems course that provides examples and exercises for using SQL statements like SELECT, WHERE, ORDER BY, GROUP BY, and HAVING to query database tables. It also covers data definition statements like CREATE TABLE and data manipulation statements like INSERT. The exercises ask students to write SQL statements to retrieve, aggregate, and filter data from sample database tables and to create tables and insert data.

Uploaded by

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

DBS LAB Manual Updated

The document is a lab manual for a database systems course that provides examples and exercises for using SQL statements like SELECT, WHERE, ORDER BY, GROUP BY, and HAVING to query database tables. It also covers data definition statements like CREATE TABLE and data manipulation statements like INSERT. The exercises ask students to write SQL statements to retrieve, aggregate, and filter data from sample database tables and to create tables and insert data.

Uploaded by

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

Lab Manual Database Systems

LAB Manual

Database Systems

CS-2014-P

Course Coordinator Nadeem Zafar


(Assistant Professor)

Department of Computer Science


G.C. University Lahore

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

THE SAMPLE ERD


This schema can be found in Oracle as HR schema or it can be developed in any DBMS by the
instructor

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

SELECT statement

SELECT statement retrieves data from a database. The data is returned in a table-like structure called a
result-set. It is the most frequently used statement on a database.
Following is the description and syntax of this statement.

SELECT Specification of desired columns


DISTINCT Omits duplicate record
TOP(n) Displays top n number of rows
FROM Specification of table or tables
WHERE Selection criteria for rows
GROUP BY Formation of groups with identical values
in specified column
HAVING Selection of specific groups
ORDER BY Sorting sequence of rows of result table

EXERCISES

A1 Display all the contents of the departments, employees and jobs


tables.

Syntax:

Select * from Employees


To produce an answer to the request "Give a list of all employees showing their employee
number, name & department number." We will require the following SQL statement,

Select employee_id, first_name, department_id from


Employees

A2 Display the name and commission of all the employees.

A3 Display the name and commission of all the employees together with another column that shows
their commission increased by 10%.

A4 Display the job id of all the employees.

To remove duplicates within the result table, use:

SELECT DISTINCT column 1, column2, etc FROM table-name;

A5 Display all the different job titles which currently exist in the company.

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

SELECT using WHERE condition

WHERE =, <>, >, >=, <, <=, (!= means not equal) comparison operators
WHERE NOT, AND, ORlogical operators
WHERE column BETWEEN field value AND field value
WHERE column IN (field value, field value, )
WHERE column LIKE '%charstring%'
(% means skip 0 or any no of characters; use _ for exactly one
character)
WHERE column IS NULL

(All these operators can be negated by using NOT)

A6 Display the employee number, name and current job of all those who work in Department 30.

A7 Display the names of all the IT Programmer, showing their employee number and that of their
manager id.

A8 Display details of all st_clerks, ad_vp and salesmen (sa_man).

A9 Display details of employees who are not st_clerks, ad_vp or salesmen.

A10 Display details of all employees whose commission is greater than salary.

A11 Display employee name, job and department number for employees whose names begin with ‘N’.

A12 Display details of employees whose salaries are not between 12,000 and 14,000.

A13 Display details of sales representative (sa_rep) and managers in department 80, whose salary is
greater than or equal to 7,000.
(Note: with logical operators - AND precedes OR)

Using the ORDER BY statement to control the display order of selected records

ORDER BY column1, column2, etc ASC/DESC; or


ORDER BY n; (being the nth column)

Note: The default ordering is ascending.


Null values are always displayed first regardless of sort sequence.

A14 Display the employee number, current job and salary of all those who work in Department 50, with
the output in ascending salary order.

A15 Display the employee name and current job of all those who work in Department 50, with the
output in descending salary order.

A16 Display the employee name and current job of all those who work in Department 50, with the
output in descending salary order within each job.

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

A17 Display employee details for departments 90 and 30, in name order, within each department

SIMPLE FUNCTIONS
SQL provides some simple aggregating functions that enable us to derive information about the rows in a
table.

COUNT(*) returns a single value, the number of rows in the table

MAX(Attribute) returns the largest value for the attribute

MIN(Attribute) returns the smallest value for the attribute

AVG(Attribute) works out the average value for this attribute

SUM(Attribute) works out the total/sum value for this attribute

A18 What are the lowest and highest basic salaries within the company?

A19 How many people have a salary greater than 20,000?

NULL Values
Null, in a database context, is the total absence of a value in a certain field and means that the field value
is unknown. Null is not the same as a zero value for a numerical field, text field or space value. Null
implies that a database field value has not been stored.

Converting NULL into a value

In MS-SQL Server, the IsNull function can be used to convert a null into a specified value e.g.

IsNull(Attribute, replacement value)

IsNull(commission_pct, 0) will return the actual value of commission_pct if it has a value, or a zero if
commission_pct is null. This is often necessary when performing calculations, or formatting for output
since null values will be totally ignored by many functions and operations.

Oracle has a function called NVL which allows you do a similar thing. It actually returns the first non-null
value in a list, but used as below enables a null to be treated as a specific number:

Select ename NVL(commission_pct,0) from employees;

A column can be tested using IS NULL or IS NOT NULL e.g.

SELECT ...FROM... WHERE column_name IS NOT NULL;

A20 What are the highest and lowest incomes (i.e. to include commission) in the Department 80?

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

GROUPING DATA

The GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data
into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes
the ORDER BY clause . GROUP BY can group with respect to one or more columns. GROUP BY
typically also involves aggregates: COUNT, MAX, SUM, AVG, etc.

A21 How many employees are there in each department?

A22 How many employees are there in each type of job in each department?

A23 For each department, find the average salary and the total salary bill excluding commission.

A24 Find the maximum commission earned, and the number of people in each department.

THE HAVING CLAUSE.


The HAVING clause is used to specify which GROUPS are to be displayed. It filters records that work
on summarized GROUP BY results. It applies to summarized group records, whereas WHERE applies
to individual records. Only the groups that meet the HAVING criteria will be returned.

Note:
WHERE restricts which rows a SELECT works on and HAVING restricts which groups.

A25 Display the department number and number of employees in departments with fewer than 6
employees.

CREATE TABLE
Creating a basic table involves naming the table and defining its columns and each column's data
type.The SQL CREATE TABLE statement is used to create a new table.

Syntax:

CREATE TABLE table name(


Column1 datatype,
Column2 datatype,
.
.
Column n datatype,
CONSTRAINT any name [PRIMARY KEY/FOREIGN KEY/UNIQUE] (one or more columns)
*REFERENCES table name(primary key column)
)

*used in case of implementing foreign key

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

INSERT INTO
INSERT INTO statement is used to add new tuple to the table

Syntax:

INSERT INTO Table name (column1,column2, column3,column4,.…..)


VALUES(value1,value2,value3,value4,……)

A26

a) Write statement to create table EMPLOYEE_TEST with these fields.


b) write statements to insert the following data into the table just created

EMPLOYEE_TEST

EMPID EMPNAME JOB HIREDATE SAL COMM DEPTNO

7369 Abid CLERK 17-DEC-2000 16000 20


7499 Hafeez SALESPERSON 20-FEB-2001 38000 2000 30
7521 namrah SALESPERSON 22-FEB-2001 38000 3500 30
7566 nadeem MANAGER 02-APR-2001 75000 20
7654 Fatima SALESPERSON 28-SEP-2001 18700 2500 30

Write the SQL statements by considering EMPLOYEE_TEST table.


A27 Write statements to
a) Show all the records from table EMPLOYEE_TEST
b) Show all the employees who’s job is ‘CLERK’
c) Display the no of employees who are earning commission more then 1000.
d) Display name and HIREDATE of the employees who’s name starts with ‘n’ and has ‘e’ as
second last character.
e) Display Gross Salary of each employee along with employee’s name (hint: gross salary = sal
+ comm).
f) Display all the different job titles, which currently exist in the company.
g) Display the department and number of employees in departments with fewer than 6 employees.
h) How many people are there in each type of job in each department?
i) Find the employee name and its salary who is earning maximum salary in department 20
j) Display the no of employees in each department

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

DELETE
The DELETE Query is used to delete the existing records from a table. WHERE clause can be used with
a DELETE query to delete the selected rows, otherwise all the records would be deleted.

Syntax:

DELETE FORM table name


WHERE condition

A28 Write statements to

a) Delete all employees having NULL commission.


b) Delete all employees whose salary is not between 9000 and 20000
c) Delete the employees those were employed before 01-jan-2001
d) Delete employees working in department 20.

UPDATE
UPDATE statement is used to modify existing records. We can update single column as well as multiple
column records as per our requirement.

Syntax:

UPDATE table name


SET column1=value, column2=value, …..
WHERE condition

A29 Write statements to


a) Change the department no. to 30 where job is not ‘CLERK’ or ‘SALESMAN’.
b) Add 1000 to the salary of those employees earning commission greater than 2500.
c) Change all salesmen to Manager, those getting commission greater than salary.

DROP TABLE
Drop table command is used to destroy the whole table even if it is populated or not.

A30
a) Delete all records of Employee
b) Destroy table EMPLOYEE

JOINS
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a
means for combining fields from two tables by using values common to each .

There are different types of joins available in SQL −


INNER JOIN returns rows when there is a match in both tables.
Syntax:
SELECT table1.column1,….,table2.column2,….
FROM table1 INNER JOIN table 2
ON table1.common domain field=table2.common domain field

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

LEFT OUTER JOIN Returns all rows from the left table, even if there are no matches in the right
table.

Syntax:

SELECT table1.column1,….,table2.column2,….
FROM table1 LEFT OUTER JOIN table 2
ON table1.common domain field=table2.common domain field

RIGHT OUTER JOIN returns all rows from the right table, even if there are no matches in the left
table.

Syntax:

SELECT table1.column1,….,table2.column2,….
FROM table1 RIGHT OUTER JOIN table 2
ON table1.common domain field=table2.common domain field

FULL JOIN returns rows when there is a match in one of the tables.

Syntax:

SELECT table1.column1,….,table2.column2,….
FROM table1 FULL JOIN table 2
ON table1.common domain field=table2.common domain field

CROSS JOIN also known as Cartesian join. This join returns the Cartesian product of the sets
of records from the two or more joined tables. This join does not need common domain
columns as it returns all possible combinations of rows from both tables.

Syntax:

SELECT table1.column1,….,table2.column2,….
FROM table1 CROSS JOIN table 2

SELF JOIN is used to join a table to itself as if the table were two tables, temporarily renaming
at least one table in the SQL statement. You must use TABLE ALIAS to implement self join.

Syntax:

SELECT T1.column1,….,T2.column2,….
FROM table1 AS T1 INNER JOIN table 1 AS T2
ON T1.common domain field=T2.common domain field

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

A31 Display the names, designations and department names of all the employees.
A32 Display all the employees along-with department names in which employees work.
A33 Display All the departments and only those employees who work in any department.
A34 Display all the employees and departments along-with those employees who work in any
department.
A35 Display the names of employees and their managers.

VIEWS
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real table in
the database. We can create a view by selecting fields from one or more tables present in the database.
A View can either have all the rows of a table or specific rows based on certain condition. A view can be
created on any SQL Select statement.

A view can be updated under certain conditions which are given below −
 The SELECT clause may not contain the keyword DISTINCT.
 The SELECT clause may not contain summary functions.
 The SELECT clause may not contain set functions.
 The SELECT clause may not contain set operators.
 The SELECT clause may not contain an ORDER BY clause.
 The FROM clause may not contain multiple tables.
 The WHERE clause may not contain subqueries.
 The query may not contain GROUP BY or HAVING.
 Calculated columns may not be updated.
 All NOT NULL columns from the base table must be included in the view in order for the INSERT
query to function.

Syntax:

CREATE VIEW View_Name


AS
[Any select statement]

A36 Display the names, designations and department names of all the employees.
A37 Display all the employees along-with department names in which employees work.
A38 Display All the departments and only those employees who work in any department.

STORED PROCEDURE
STORED PROCEDURE is a pre compiled query. It is a set of Structured Query Language
(SQL) statements with an assigned name, which are stored in a relational database management
system as a group, so it can be reused and shared by multiple programs. Stored procedures can access

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

or modify data in a database. There are two types of procedures

1. Non parameterized stored procedure


2. Parameterized stored procedure

Syntax:
Non Parameterized Stored Procedure

CREATE PROCEDURE Procedure_name


AS
Sql_statement

A39 Create a procedure that displays the names, designations and department names of all
the employees.
A40 Create a procedure that displays all the employees along-with department names in
which employees work.
A41 Create a procedure that displays All the departments and only those employees who
work in any department.

Parameterized Stored Procedure

CREATE PROCEDURE Procedure_name


(Variable1 datatype,
Variable2 datatype,……)
AS
Sql_statement with variable utilization

A42 Create a procedure that deletes a record of employees on the basis of his Id.
A43 Create a procedure that updates the salary (salary+a) of employee on the basis of Id.
A44 Create a procedure that inserts a record in the employees table

SUB QUERY

A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the
WHERE clause. it is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.

Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.

There are a few rules that subqueries must follow −

 Subqueries must be enclosed within parentheses.


 A subquery can have only one column in the SELECT clause, unless multiple columns are in the
main query for the subquery to compare its selected columns.

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

 An ORDER BY command cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER
BY in a subquery.
 Subqueries that return more than one row can only be used with multiple value operators such as the
IN operator.
 The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB,
or NCLOB.
 A subquery cannot be immediately enclosed in a set function.
 The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be
used within the subquery.

Syntax:
SELECT Column name1, Column name2,……
FROM table1, table2
WHERE column name OPERATOR (SELECT column name FROM table2 WHERE condition)

A45. Display the names and designations of those employees whose salary is equal to salary of
AD_VP.
A46 display names and salaries of those employees who are getting commission more than smith.

Miscellaneous Questions
1. Write a query to retrieve top 5 records from employees table.

2. Write a query to count the number of employees, and salary they are getting according to their job
titles and departments and filter out those groups only who are getting above 10,000 salary  AND Select
employees who got more than 01 (one) promotions.

3. Write a query to separate phone number into three parts before each full stop (.) and display all three
parts in different columns with names ‘First Part’, ‘Second Part’ and ‘Third Part’ also in a single column but this
time separated not by (.) but by /. AND Write a query to separate job_id into two different parts given (_) as a
separator and display it in two columns.

4. Write a query to find out how many years/ months any employee work on a particular post, If he/she
has changed his job then tell the duration on each job.

5. Suppose a scenario where there is no primary key intact in a table and there may exist duplicate record, with
same id and related information, your task is to delete these duplicate records by meticulously observing the
working of query, you also have to find at least TWO different methods to perform this task, one of them may
be less efficient than other .

6. Write a query to create a join on nested level, You have to tell the region detail, country detail, location detail
and employee detail. You have to write 1) matching records 2) suppose some regions do not contain any
country records 3) all records from each side of table either they match or not.

7. Display department name and total number of employees in that department.

8. You already know how to create a table, find at least another method to create a table

9. List those employees who were hired before their managers.

10. The organization want the list of senior-most employees in each departments, list those employees.

Department of Computer Science G.C.University Lahore


Lab Manual Database Systems

11. List the employees who are getting top 3 salaries (Note: Its not department-wise top 3 but over all top 3
salaried employees and if more than one employee stands on first, second or third position, include
that employee as well).

12. Display the list of employees hired between year 1995 and 2000.

13. Using subquery list the department names who do not hired any employee so far. (Note: if the result will
show no department, find the reason as there are departments who do not have any employee).
Resolve it anyway.

14. Select department names who are located in either US or Canada.

15. Use Update Statement to raise the salary of all employees to 10% of their existing salary.

16. Use update statement to raise the salary upto 20%  of only those employees who are managing a
department (use sub query in update statement)

17. Suppose there is a table table1(id number(10), name varchar2(100)), fill in some example data in this table
with insert statement. Now, create a copy of this table using CREATE statement and make some
changes in the copy (insert, update, delete few records). Your task is to write a query that will reflect
the changes made in this copy table in the original table i.e. after this query both tables will have same
data.

Department of Computer Science G.C.University Lahore

You might also like