0% found this document useful (0 votes)
28 views59 pages

Lab Sheets Manual (Complete)

Lab sheet

Uploaded by

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

Lab Sheets Manual (Complete)

Lab sheet

Uploaded by

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

Table of Contents

Lab Sheet 1 ............................................................................................................................................................... 2


a) Creating User .................................................................................................................................................... 2
b) Assigning user rights to create database and perform DB operations using data sublanguages ..................... 2
c) Building sample database ................................................................................................................................. 2
Lab Sheet 2............................................................................................................................................................... 6
Introduction to SQL .............................................................................................................................................. 6
Lab Sheet 3 ............................................................................................................................................................. 13
Creating Table Using DDL Commands................................................................................................................ 13
Lab Sheet 4 ............................................................................................................................................................. 18
Working with SQL Basic operations ................................................................................................................... 18
Lab Sheet 5 ............................................................................................................................................................. 21
Working with Comparison and Condition operators ......................................................................................... 21
Lab Sheet 6 ............................................................................................................................................................. 24
Working with Cartesian product with 2 relations and more than 2 relations .................................................... 24
Lab Sheet 7 ............................................................................................................................................................. 30
Working with INSERT, DELETE, and UPDATE Statements in SQL ....................................................................... 30
Lab Sheet 8 ............................................................................................................................................................. 34
Working with Update Operations, Transactions, and Dealing with Constraint Violations................................ 34
Lab Sheet 9 ............................................................................................................................................................. 38
Single-row and multiple-row functions in SQL .................................................................................................. 38
Lab Sheet 10 ........................................................................................................................................................... 48
Introduction to Subqueries in SQL ..................................................................................................................... 48
Lab Sheet 11 ........................................................................................................................................................... 52
Working with Compound Queries ..................................................................................................................... 52
Lab Sheet 12 ........................................................................................................................................................... 56
Data retrieval operations in SQL using join operations .................................................................................... 56

Page | 1
Lab Sheet 1
(Activity 0)

Object:
a) Creating User
b) Assigning user rights to create database and perform DB operations using data sublanguages
c) Building sample database

a) Creating user

CONNECT / AS SYSDBA OR sqlplus "/as sysdba"

CREATE USER NewDBA


IDENTIFIED BY passwd;

b) Assigning user rights (to create database and perform DB operations using data sublanguages )

GRANT DBA TO NewDBA WITH ADMIN OPTION;

c) Building sample database (oracle employee datable)

// dbscript.txt file has been shared. Place this file in D: drive and use following command on SQL command line
interface:

SQL> @ ‘ d:\dbscript.txt’;

The dbscript.txt file contains following instructions: (For your reference only)

-- Setting terminal output ON/OFF

SET TERMOUT ON

PROMPT Building demonstration tables. Please wait.

SET TERMOUT OFF

DROP TABLE EMP;

DROP TABLE DEPT;

DROP TABLE BONUS;

DROP TABLE SALGRADE;

DROP TABLE DUMMY;

Page | 2
CREATE TABLE EMP

(EMPNO NUMBER(4) NOT NULL,

ENAME VARCHAR2(10),

JOB VARCHAR2(9),

MGR NUMBER(4),

HIREDATE DATE,

SAL NUMBER(7, 2),

COMM NUMBER(7, 2),

DEPTNO NUMBER(2));

INSERT INTO EMP VALUES

(7369, 'SMITH', 'CLERK', 7902,

TO_DATE('17-DEC-1980', 'DD-MON-YYYY'), 800, NULL, 20);

INSERT INTO EMP VALUES

(7499, 'ALLEN', 'SALESMAN', 7698,

TO_DATE('20-FEB-1981', 'DD-MON-YYYY'), 1600, 300, 30);

INSERT INTO EMP VALUES

(7521, 'WARD', 'SALESMAN', 7698,

TO_DATE('22-FEB-1981', 'DD-MON-YYYY'), 1250, 500, 30);

INSERT INTO EMP VALUES

(7566, 'JONES', 'MANAGER', 7839,

TO_DATE('2-APR-1981', 'DD-MON-YYYY'), 2975, NULL, 20);

INSERT INTO EMP VALUES

(7654, 'MARTIN', 'SALESMAN', 7698,

TO_DATE('28-SEP-1981', 'DD-MON-YYYY'), 1250, 1400, 30);

INSERT INTO EMP VALUES

(7698, 'BLAKE', 'MANAGER', 7839,

TO_DATE('1-MAY-1981', 'DD-MON-YYYY'), 2850, NULL, 30);

INSERT INTO EMP VALUES

(7782, 'CLARK', 'MANAGER', 7839,

TO_DATE('9-JUN-1981', 'DD-MON-YYYY'), 2450, NULL, 10);

INSERT INTO EMP VALUES

(7788, 'SCOTT', 'ANALYST', 7566,

TO_DATE('09-DEC-1982', 'DD-MON-YYYY'), 3000, NULL, 20);

INSERT INTO EMP VALUES

(7839, 'KING', 'PRESIDENT', NULL,

Page | 3
TO_DATE('17-NOV-1981', 'DD-MON-YYYY'), 5000, NULL, 10);

INSERT INTO EMP VALUES

(7844, 'TURNER', 'SALESMAN', 7698,

TO_DATE('8-SEP-1981', 'DD-MON-YYYY'), 1500, 0, 30);

INSERT INTO EMP VALUES

(7876, 'ADAMS', 'CLERK', 7788,

TO_DATE('12-JAN-1983', 'DD-MON-YYYY'), 1100, NULL, 20);

INSERT INTO EMP VALUES

(7900, 'JAMES', 'CLERK', 7698,

TO_DATE('3-DEC-1981', 'DD-MON-YYYY'), 950, NULL, 30);

INSERT INTO EMP VALUES

(7902, 'FORD', 'ANALYST', 7566,

TO_DATE('3-DEC-1981', 'DD-MON-YYYY'), 3000, NULL, 20);

INSERT INTO EMP VALUES

(7934, 'MILLER', 'CLERK', 7782,

TO_DATE('23-JAN-1982', 'DD-MON-YYYY'), 1300, NULL, 10);

CREATE TABLE DEPT

(DEPTNO NUMBER(2),

DNAME VARCHAR2(14),

LOC VARCHAR2(13) );

INSERT INTO DEPT VALUES (10, 'ACCOUNTING', 'NEW YORK');

INSERT INTO DEPT VALUES (20, 'RESEARCH', 'DALLAS');

INSERT INTO DEPT VALUES (30, 'SALES', 'CHICAGO');

INSERT INTO DEPT VALUES (40, 'OPERATIONS', 'BOSTON');

CREATE TABLE BONUS

(ENAME VARCHAR2(10),

JOB VARCHAR2(9),

SAL NUMBER,

COMM NUMBER);

CREATE TABLE SALGRADE

(GRADE NUMBER,

LOSAL NUMBER,

Page | 4
HISAL NUMBER);

INSERT INTO SALGRADE VALUES (1, 700, 1200);

INSERT INTO SALGRADE VALUES (2, 1201, 1400);

INSERT INTO SALGRADE VALUES (3, 1401, 2000);

INSERT INTO SALGRADE VALUES (4, 2001, 3000);

INSERT INTO SALGRADE VALUES (5, 3001, 9999);

CREATE TABLE DUMMY

(DUMMY NUMBER);

INSERT INTO DUMMY VALUES (0);

COMMIT;

SET TERMOUT ON

PROMPT Demonstration table build is complete.

Reference: Oracle Corporation

Page | 5
Lab Sheet 2
Object:
Introduction to SQL

THEORY

What is a database?
Every organization needs information for making effective decisions. A library keeps a list of books,
members, due dates and fines. A company needs to save information about employees, departments and
salaries. The collection of facts about different entities in an organization is called data.
A database is an organized collection of interrelated data. In order to manage databases, we need Database
Management Systems (DBMS). A DBMS is a program that stores, retrieves and modifies data in the database
on user’s request as illustrated in figure 2.1 below.

Database Users

Database Management
System

Database

Figure 2.1: Users access data in a database through DBMS

Relational Database Concept


A relational database uses relations or two-dimensional tables to store data. Such a database can be accessed
and modified by executing Structured Query Language (SQL) statements. Dr. E. F. Codd proposed the
relational model for database systems in 1970. Relational Database Management Systems (RDBMS)
soon became very popular, especially for their ease of use and flexibility in structure. In addition, a number
of innovative vendors such as Oracle, supplemented the RDBMS with a suite of powerful application
development and user products, providing a total solution.
A table is the basic storage structure of an RDBMS. A table holds all the data necessary about
something in the real world – for example, employees, invoices, or customers.

Page | 6
For instance, the Oracle 11g database we are referring to store all your data.

The table 2.1 below shows the contents of the EMP table or relation that stores data about employees
presently working in an organization.
▪ The table has eight columns namely EMPNO, ENAME. JOB, MGR, HIREDATE, SAL, COMM,
DEPTNO storing the different attributes of an employee.
▪ The table has fourteen rows each representing all data that is required for a particular employee.
Each row in a table should be identified by a primary key, which allows no duplicate rows. In
table 2.1, EMPNO is the primary key where as in table 2.2, DEPTNO is the primary key.
▪ A foreign key is a column or a set of columns that refers to a primary key or a unique key in the
same table or another table. In EMP table, DEPTNO is the foreign key.
▪ A field can be found at the intersection of a row and a column. There can be only one
value in it.
▪ A field may have no value in it. This is called null value. In the EMP table, only employees
who have a role of salesman have a value in the COMM (Commission) field.
Moreover, table 2.3 and 2.4 will be discussed in lab.
EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7839 KING PRESIDENT 17-NOV-81 5000 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
Table 2.1
The table DEPT below contains data about different departments in an organization and SALGRADE
gives details of salaries for various grades. The table JOB_HISTORY stores data about the job history
of employees.

DEPT
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Table 2.2
SALGRADE
GRADE LOSAL HISAL
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999
Table 2.3

Page | 7
JOB_HISTORY
EMPNO JOB START_DATE END_DATE
7698 ASSISTANT 04-MAR-80 30-APR-81
7654 RECEPTIONIST 13-JAN-80 09-SEP-80
7654 SALESMAN 10-SEP-80 20-SEP-81
7788 PROGRAMMER 13-FEB-80 03-DEC-82
7876 TYPIST 12-APR-80 13-NOV-81
7876 OPERATOR 15-NOV-81 11-JAN-83
7839 ANALYST 13-JUN-78 10-OCT-81

Table 2.4

Relating Multiple Tables


Each table contains data that describes exactly one entity. For example, the EMP table contains
information about employees. Since data about different entities is stored in different tables, it may be
needed to combine two or more tables to answer a particular question. For example, someone may want
to know the location of the department where an employee works. In this scenario, information is
needed from both the EMP and DEPT table. An RDBMS enables to relate the data in one table to the
data in another table by using the foreign keys.

Guidelines for Primary and Foreign Keys


▪ No duplicate values are allowed in a primary key.
▪ Primary keys generally cannot be changed.
▪ Foreign keys are based on data values and are purely logical, not physical pointers.
▪ A foreign key value must match an existing primary key value or unique key value, or else be null.

SQL (Structured Query Language)


Most commercial database management systems support a query language, SQL, which is the most
influential commercially marketed product. SQL is a nonprocedural language: you

Page | 8
specify what information you require, rather than how to get it. In other words, SQL does not require you
to specify the access methods to the data. As a result, it doesn’t provide traditional programming structures.
Instead, it is a language for specifying the operations at an unusually high level. The details of the
implementation are left to the DBMS.
In Oracle, SQL is a language for communication with the Oracle Server from any tool or application.
Oracle SQL has many extensions. Although we refer to the SQL language as a query language, it
contains many other capabilities besides querying a database. It includes features for defining the structure
of the data, for inserting and modifying data in the database, and for specifying security constraints.
It has following advantages:-
▪ Efficient
▪ Easy to learn and use
▪ Functionally complete (SQL allows to define, retrieve, and manipulate data in the tables.)
Background of SQL
The SQL language, originally called SEQUEL, was developed by IBM as part of the extensive
work on the relational model in 1970s at their San Jose Research Laboratory, California. In order to
test the viability of implementing the relational model in a DBMS, workers at the San Jose Research
Laboratory undertook the project of the development of a prototype RDBMS named System R. This
project took place from 1974 to 1979. The System R project led to the development of SEQUEL
(Structured English Query Language) which was later renamed as SQL. Because System R was well
received at the user sites where it was installed, other vendors began developing relational products that
used SQL. In the late 1970s, the database management system Oracle was produced by what is now
called the Oracle Corporation and was probably the first commercial implementation of a relational
DBMS based on SQL. ORACLE is now available in mainframe, client-server and PC-based
platforms for many operating systems including DOS, OS/2, various UNIX operating systems,
Windows, VAX/VMS and MVS. Numerous RDBMS products now support the SQL language.
In 1986, the American National Standards Institute (ANSI) and the International Standards Organization
(ISO) published an SQL standard, called SQL-86. IBM published its own corporate SQL standard,
the Systems Application Architecture Database Interface (SAA- SQL) in 1987. An extended standard
for SQL, SQL-89, was published in 1989. The ISO and ANSI committees created SQL-92 which was a
more extensive expansion of SQL-86. SQL-
92 which was in fact a first major revision of the SQL standard is sometimes referred to as SQL2. It
was not until 1999 that the next release of the standard was formalized, commonly referred to as SQL3.
This release contains additional features that support object-oriented data management.
Scope
SQL is used for all types of database activities by all types of users including:
▪ System administrators
▪ Database administrators
▪ Security administrators
▪ Application programmers
▪ Decision support system personnel
▪ Many other types of end users

Page | 9
Language Components
The SQL language has several parts:-
Data Retrieval: The SQL includes a query language based on both the relational algebra and the tuple relational
calculus.
Data-definition language (DDL): The SQL DDL provides commands for defining relation schemas, deleting
relations, creating indices, and modifying relation schemas.
Interactive data-manipulation language (DML): It includes commands to insert tuples into, delete tuples from,
and to modify tuples in the database.
Embedded DML: The embedded form of SQL is designed for use within general purpose programming
languages, such as Cobol, Pascal and C.
View definition: The SQL DDL includes commands for defining views.
Authorization: The SQL DDL includes commands for specifying access rights for relations and views.
Integrity: The SQL DDL includes commands for specifying integrity constraints that the data stored in the
database must satisfy. Updates that violate integrity constraints are disallowed. Transaction control: SQL
includes commands for specifying the beginning and ending of transaction. Several implementations also
allow explicit locking of data for concurrency
control.

Basic Data Retrieval


The basic structure of an SQL query consists of three clauses: SELECT, FROM and WHERE.

SELECT * | {[DISTINCT] column | expression [alias], …}


FROM table
[WHERE condition];

Note: The keywords and clauses enclosed in square brackets are optional.

Examples
i. Selecting all columns from a table
SELECT * FROM DEPT;

ii. To select names of all jobs in a department, use


SELECT DISTINCT JOB FROM EMP;

Note: The DISTINCT clause before a column name suppresses duplicate values

iii. To select all employees whose salary is greater than 2200.


SELECT * FROM EMP WHERE SAL > 2200;

iv. To display the name and department number of employees who were hired before 12th
May, 1981.

SELECT ENAME, DEPTNO FROM EMP WHERE HIREDATE < ’12-MAY-1981’;

v. To display the name and job of employees using literal character strings and concatenation
operators.
SELECT ENAME || ‘ is a ‘ || JOB AS “Employee Details” FROM EMP;

vi. Retrieving data from multiple tables: To select employee name, job and department name,

Page | 10
SELECT E.ENAME, E.JOB, D.DNAME FROM EMP E, DEPT D WHERE E.DEPTNO = D.DEPTNO;

DESC[RIBE]: To display the structure of a table


e.g., SQL> DESC EMP

SAV[E] filename[.ext]: Saves current contents of SQL buffer to a file


e.g., SQL>SAVE D:\DATA\FINDSAL

GET filename[.ext]: Writes the contents of a previously saved file to the SQL buffer. The
default extension for the file is sql.
e.g., SQL> GET D:\DATA\FINDSAL

@: Runs a previously saved command file


e.g., SQL>@ filename SPO[OL]: Stores query results in a file
e.g., SQL>SPOOL filename.ext SPOOL OFF: Closes the spool file

SPOOL OUT: Closes the spool file and sends the file results to the system printer
ED[IT]: Invokes the editor and saves the buffer contents to a file named afiedt.buf
ED[IT] [filename[.ext]]: Invokes editor to edit contents of a saved file
EXIT: Leaves SQL*Plus
Figure 1.4
EXERCISES

1. What are relational databases? Describe, with the help of an example, how an RDBMS
enables to relate data in one table to the data in another table.

2. Why SQL is called a nonprocedural language?

3. Write down a brief history of SQL and explain why its standardization was necessary.

Page | 11
4. Write a query to display the employee number, name and salary of all managers.

5. Write a query to display the name and department number of all employees who were hired after
1982.

6. Write a query to display the name of all managers in department 20.

7. Display the one-month salary of employee ten as:

KING: 1 Month salary = 5000

Hint: use literal character strings

Reference:
Practical Workbook, Database Management Systems, Second Edition, Reviewed in 2011, Department of Computer & Information Systems Engineering,
NED University of Engineering & Technology, Karachi – 75270, Pakistan

Page | 12
Lab Sheet 3
Object:

Creating Table Using DDL Commands

SQL> CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,


2 ENAME VARCHAR2(10),
3 JOB VARCHAR2(9),
4 MGR NUMBER(4),
5 HIREDATE DATE,
6 SAL NUMBER(7, 2),
7 COMM NUMBER(7, 2),
8 DEPTNO NUMBER(2));

Table created.

SQL>
SQL> INSERT INTO EMP VALUES (7369, 'SMITH', 'CLERK', 7902, TO_DATE('17-DEC-1980', 'DD-
MON-YYYY'), 800, NULL, 20);

1 row created.

SQL> INSERT INTO EMP VALUES (7499, 'ALLEN', 'SALESMAN', 7698, TO_DATE('20-FEB-1981', 'DD-
MON-YYYY'), 1600, 300, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7521, 'WARD', 'SALESMAN', 7698, TO_DATE('22-FEB-1981', 'DD-
MON-YYYY'), 1250, 500, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7566, 'JONES', 'MANAGER', 7839, TO_DATE('2-APR-1981', 'DD-
MON-YYYY'), 2975, NULL, 20);

1 row created.

SQL> INSERT INTO EMP VALUES (7654, 'MARTIN', 'SALESMAN', 7698,TO_DATE('28-SEP-1981', 'DD-
MON-YYYY'), 1250, 1400, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7698, 'BLAKE', 'MANAGER', 7839,TO_DATE('1-MAY-1981', 'DD-MON-
YYYY'), 2850, NULL, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7782, 'CLARK', 'MANAGER', 7839,TO_DATE('9-JUN-1981', 'DD-MON-
YYYY'), 2450, NULL, 10);

1 row created.

SQL> INSERT INTO EMP VALUES (7788, 'SCOTT', 'ANALYST', 7566,TO_DATE('09-DEC-1982', 'DD-MON-
YYYY'), 3000, NULL, 20);

1 row created.

SQL> INSERT INTO EMP VALUES (7839, 'KING', 'PRESIDENT', NULL,TO_DATE('17-NOV-1981', 'DD-MON-

Page | 13
YYYY'), 5000, NULL, 10);

1 row created.

SQL> INSERT INTO EMP VALUES (7844, 'TURNER', 'SALESMAN', 7698,TO_DATE('8-SEP-1981', 'DD-MON-
YYYY'), 1500, 0, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7876, 'ADAMS', 'CLERK', 7788,TO_DATE('12-JAN-1983', 'DD-MON-
YYYY'), 1100, NULL, 20);

1 row created.

SQL> INSERT INTO EMP VALUES (7900, 'JAMES', 'CLERK', 7698,TO_DATE('3-DEC-1981', 'DD-MON-
YYYY'), 950, NULL, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7902, 'FORD', 'ANALYST', 7566,TO_DATE('3-DEC-1981', 'DD-MON-
YYYY'), 3000, NULL, 20);

1 row created.

SQL> INSERT INTO EMP VALUES (7934, 'MILLER', 'CLERK', 7782,TO_DATE('23-JAN-1982', 'DD-MON-
YYYY'), 1300, NULL, 10);

1 row created.

SQL>
SQL> select * from emp;

EMPNO Employee Name JOB MGR HIREDATE Salary COMM DEPTNO


---------- ------------- --------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 12-JAN-83 1100 20

EMPNO Employee Name JOB MGR HIREDATE Salary COMM DEPTNO


---------- ------------- --------- ---------- --------- ---------- ---------- ----------
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

14 rows selected.

SQL>
SQL>
SQL> create or replace procedure emp_lookup(
2 p_empno in number,
3 o_ename out emp.ename%type,
4 o_sal out emp.sal%type ) as
5 begin
6 select ename, sal
7 into o_ename, o_sal

Page | 14
8 from emp
9 where empno = p_empno;
10 exception
11 when NO_DATA_FOUND then
12 o_ename := 'NULL';
13 o_sal := -1;
14 end emp_lookup;
15 /

Procedure created.

SQL>
SQL> variable name varchar2(10);
SQL> variable sal number;
SQL>
SQL> exec emp_lookup( '7782', :name, :sal );

PL/SQL procedure successfully completed.

SQL>
SQL> print name

NAME
--------------------------------
CLARK

SQL>
SQL> print sal

Salary
----------
2450

SQL>
SQL> select :name, :sal from dual;

:NAME :SAL
-------------------------------- ----------
CLARK 2450

SQL>
SQL>
SQL> drop table emp;

Table dropped.

SQL>

SQL>
SQL> CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,
2 ENAME VARCHAR2(10),
3 JOB VARCHAR2(9),
4 MGR NUMBER(4),
5 HIREDATE DATE,
6 SAL NUMBER(7, 2),
7 COMM NUMBER(7, 2),
8 DEPTNO NUMBER(2));

Table created.

SQL>
SQL> INSERT INTO EMP VALUES (7369, 'SMITH', 'CLERK', 7902, TO_DATE('17-DEC-1980', 'DD-
MMM-YYYY'), 800, NULL, 20);

Page | 15
1 row created.

SQL> INSERT INTO EMP VALUES (7499, 'ALLEN', 'SALESMAN', 7698, TO_DATE('20-FEB-1981', 'DD-
MON-YYYY'), 1600, 300, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7521, 'WARD', 'SALESMAN', 7698, TO_DATE('22-FEB-1981', 'DD-
MON-YYYY'), 1250, 500, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7566, 'JONES', 'MANAGER', 7839, TO_DATE('2-APR-1981', 'DD-
MON-YYYY'), 2975, NULL, 20);

1 row created.

SQL> INSERT INTO EMP VALUES (7654, 'MARTIN', 'SALESMAN', 7698,TO_DATE('28-SEP-1981', 'DD-
MON-YYYY'), 1250, 1400, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7698, 'BLAKE', 'MANAGER', 7839,TO_DATE('1-MAY-1981', 'DD-MON-
YYYY'), 2850, NULL, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7782, 'CLARK', 'MANAGER', 7839,TO_DATE('9-JUN-1981', 'DD-MON-
YYYY'), 2450, NULL, 10);

1 row created.

SQL> INSERT INTO EMP VALUES (7788, 'SCOTT', 'ANALYST', 7566,TO_DATE('09-DEC-1982', 'DD-MON-
YYYY'), 3000, NULL, 20);

1 row created.

SQL> INSERT INTO EMP VALUES (7839, 'KING', 'PRESIDENT', NULL,TO_DATE('17-NOV-1981', 'DD-MON-
YYYY'), 5000, NULL, 10);

1 row created.

SQL> INSERT INTO EMP VALUES (7844, 'TURNER', 'SALESMAN', 7698,TO_DATE('8-SEP-1981', 'DD-MON-
YYYY'), 1500, 0, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7876, 'ADAMS', 'CLERK', 7788,TO_DATE('12-JAN-1983', 'DD-MON-
YYYY'), 1100, NULL, 20);

1 row created.

SQL> INSERT INTO EMP VALUES (7900, 'JAMES', 'CLERK', 7698,TO_DATE('3-DEC-1981', 'DD-MON-
YYYY'), 950, NULL, 30);

1 row created.

SQL> INSERT INTO EMP VALUES (7902, 'FORD', 'ANALYST', 7566,TO_DATE('3-DEC-1981', 'DD-MON-
YYYY'), 3000, NULL, 20);

1 row created.

Page | 16
SQL> INSERT INTO EMP VALUES (7934, 'MILLER', 'CLERK', 7782,TO_DATE('23-JAN-1982', 'DD-MON-
YYYY'), 1300, NULL, 10);

1 row created.

SQL>
SQL> select * from emp;

EMPNO Employee Name JOB MGR HIREDATE Salary COMM DEPTNO


---------- ------------- --------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 12-JAN-83 1100 20

EMPNO Employee Name JOB MGR HIREDATE Salary COMM DEPTNO


---------- ------------- --------- ---------- --------- ---------- ---------- ----------
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

14 rows selected.

SQL>
SQL> drop table emp;

Table dropped.

SQL>

Exercise

1. Write a query to display the employee number, name and salary of all managers.

2. Write a query to display the name and department number of all employees who were hired after
1982.

3. Write a query to display the name of all managers in department 20.

4. Display the one month salary of employee written as:

Page | 17
KING: 1 Month salary = 5000

Lab Sheet 4

Object

Working with SQL Basic operations

1. Change the heading of column by using column ALIAS:


SQL> SELECT ename, sal, sal+100 Total SQL> SELECT ename sal, sal+100 “total”
FROM emp; FROM emp;
OR
SQL>SELECT ename, sal, sal+100 AS Total SQL>SELECT ename, sal, sal+100 AS “total”
FROM emp; FROM emp;

Example OUTPUT:
TOTAL total
---------- _______
900 900
1700 1700
1350 1350

2. Literal Character Strings and Concatenation Operator( || ):


SQL> ename || ‘IS A’ || job AS “EMPLOYEE DETAILS” FROM emp;
SQL> ename || ‘: 1 Month salary= ‘ || sal Monthly FROM emp;

• Date and character literal values must be enclosed within single quotation marks.
• Character values are case sensitive and date values are format sensitive.

3. Eliminating DUPLICATE rows:


As default display of queries is al rows, to eliminate duplicate one use the
DISTINCT keyword in SELECT clause.
SQL>SELECT deptno FROM emp;
SQL>SELECT DISTINCT deptno FROM emp;

4. Conditional Retrieval: One can restrict the rows returned by using the WHERE clause, it directly
follow the FROM clause.

Employee belonging to department 20:

SQL> SELECT *
FROM emp
WHERE deptno=20;

Page | 18
BETWEEN-AND condition:
It is basically a range condition i.e. one can specify lower and upper limit.
Displays the Employee name and salary, such that employee salary is between 1000
and 3000.

SQL>SELECT ename, sal FROM emp WHERE sal BETWEEN 1000 AND 3000;

LIKE condition: used for performing wildcard search(pattern matching).


Employee name whose first name begins with S not with s.

SQL> SELECT * FROM emp WHERE ename LIKE ‘S%’;

Any sequence of zero or more characters represent any single character


Employee names whose name have a ‘L’ as the second character.

SQL> SELECT ename FROM emp WHERE ename LIKE ‘_L%’;

IN condition: Test values in a specified set of values also known as membership


condition.
All Employees no, name, salary whose job is ‘CLERK’, ‘MANAGER’, ‘PRESIDENT’.
SQL> SELECT empno, ename, sal, job
FROM emp
WHERE job IN( ‘CLERK’, ‘MANAGER’, ‘PRESIDENT’);

NULL condition: includes IS NULL(test for nulls) as null cannot be test with = and
IS NOT NULL conditions.
Employee names and their commission, who are not eligible for commission.

SQL> SELECT ename, comm


FROM emp
WHERE comm IS NULL;

5. Logical Conditions: all e.g. so far have specified only one condition in WHERE clause, however one
can use several conditions in WHERE clause using logical operators.
SQL>SELECT empno, ename, job, sal
FROM emp logical AND operator
WHERE sal>=10000 AND job LIKE ‘%MAN%’ ;

SQL> SELECT ename, job FROM emp


WHERE job NOT IN (‘IT_PROG’,’ST_CLERK’,’SA_REP’);

Page | 19
6. ORDER BY Clause: SQL uses ORDER BY clause to sort rows i.e. in ascending
(default order) and descending. The ORDER BY clause comes last in SELECT statement.
Displays the empno, ename hiredate and sal in ascending order of salary
SQL> SELECT empno, ename, hiredate, sal
FROM emp ORDER BY sal;
Sorting by Column ALIAS
SQL>SELECT ename, hiredate AS date_of_joining
FROM emp ORDER BY date_of_joining DESC;
Sorting by Multiple Columns
SQL> SELECT ename, deptno
FROM emp ORDER BY deptno, sal DESC ;
Can Sort by column not in SELECT list
SQL>SELECT empno, ename, job, hiredate, sal
FROM emp ORDER BY 5 ;
order OUTPUT by column NUMBER(must be the no of a SELECT-list expression)

Character Strings and Dates


Character strings and date values are enclosed by single quotation marks.
Character values are case-sensitive, and date values are format-sensitive.
The default date format is DD-MON-RR.

SELECT last_name, job_id, department_id


FROM employees
WHERE last_name = 'Whalen' ;

Page | 20
Lab Sheet 5

Object:

Working with Comparison and Condition operators

Using the IN Condition


Use the IN membership condition to test for values in a list:

SELECT employee_id, last_name, salary, manager_id


FROM employees
WHERE manager_id IN (100, 101, 201) ;

Using the LIKE Condition


You can combine pattern-matching characters:

SELECT last_name
FROM employees
WHERE last_name LIKE '_o%' ;

Page | 21
Using the NULL Conditions
Test for nulls with the IS NULL operator.

SELECT last_name, manager_id


FROM employees
WHERE manager_id IS NULL ;

Using the NOT Operator

SELECT last_name, job_id


FROM employees
WHERE job_id
NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;

Rules of Precedence

Rules of Precedence

SELECT last_name, job_id, salary


FROM employees
WHERE job_id = 'SA_REP'
OR job_id = 'AD_PRES'
AND salary > 15000;

Page | 22
SELECT last_name, job_id, salary
FROM employees
WHERE (job_id = 'SA_REP'
OR job_id = 'AD_PRES')
AND salary > 15000;

Page | 23
Lab Sheet 6
Object:

Working with Cartesian product with 2 relations and more than 2 relations

Task: Write query as relational algebraic notation and its equivalent SQL syntax to find pre-requisite course
name(s) of Database Course

Course_name Course_number Credit_hours Department

Intro to Computer CS1310 4 CS


Science

Data Structures CS3320 4 CS

Discrete MATH2410 3 MATH


Mathematics

Database CS3380 3 CS

Course_number Prerequisite_number

CS3380 CS1310

CS3380 MATH2410

CS3320 CS1310

Page | 24
Page | 25
Course X Prerequisite X Course

Course C1 X Prerequisite P X Course C2

Course X Prerequisite Course

Course Prerequisite

Course_na Course_nu Credit_ho Departm Course_nu Prerequisite_nu


me mber urs ent mber mber

Intro to CS1310 4 CS CS3380 CS1310 Intro to CS1310 4 CS


Computer Computer
Science Science

Intro to CS1310 4 CS CS3380 CS1310 Data CS3320 4 CS


Computer Structures
Science

Intro to CS1310 4 CS CS3380 CS1310 Discrete MATH24 3 MAT


Computer Mathema 10 H
Science tics

Intro to CS1310 4 CS CS3380 CS1310 Database CS3380 3 CS


Computer
Science

Intro to CS1310 4 CS CS3380 MATH2410 Intro to CS1310 4 CS


Computer Computer
Science Science

Intro to CS1310 4 CS CS3380 MATH2410 Data CS3320 4 CS


Computer Structures
Science

Intro to CS1310 4 CS CS3380 MATH2410 Discrete MATH24 3 MAT


Computer Mathema 10 H
Science tics

Intro to CS1310 4 CS CS3380 MATH2410 Database CS3380 3 CS


Computer
Science

Intro to CS1310 4 CS CS3320 CS1310 Intro to CS1310 4 CS


Computer Computer
Science Science

Intro to CS1310 4 CS CS3320 CS1310 Data CS3320 4 CS


Computer Structures
Science

Page | 26
Intro to CS1310 4 CS CS3320 CS1310 Discrete MATH24 3 MAT
Computer Mathema 10 H
Science tics

Intro to CS1310 4 CS CS3320 CS1310 Database CS3380 3 CS


Computer
Science

Data CS3320 4 CS CS3380 CS1310 Intro to CS1310 4 CS


Structures Computer
Science

Data CS3320 4 CS CS3380 CS1310 Data CS3320 4 CS


Structures Structures

Data CS3320 4 CS CS3380 CS1310 Discrete MATH24 3 MAT


Structures Mathema 10 H
tics

Data CS3320 4 CS CS3380 CS1310 Database CS3380 3 CS


Structures

Data CS3320 4 CS CS3380 MATH2410 Intro to CS1310 4 CS


Structures Computer
Science

Data CS3320 4 CS CS3380 MATH2410 Data CS3320 4 CS


Structures Structures

Data CS3320 4 CS CS3380 MATH2410 Discrete MATH24 3 MAT


Structures Mathema 10 H
tics

Data CS3320 4 CS CS3380 MATH2410 Database CS3380 3 CS


Structures

Data CS3320 4 CS CS3320 CS1310 Intro to CS1310 4 CS


Structures Computer
Science

Data CS3320 4 CS CS3320 CS1310 Data CS3320 4 CS


Structures Structures

Data CS3320 4 CS CS3320 CS1310 Discrete MATH24 3 MAT


Structures Mathema 10 H
tics

Data CS3320 4 CS CS3320 CS1310 Database CS3380 3 CS


Structures

Page | 27
Discrete MATH2410 3 MATH CS3380 CS1310 Intro to CS1310 4 CS
Mathemat Computer
ics Science

Discrete MATH2410 3 MATH CS3380 CS1310 Data CS3320 4 CS


Mathemat Structures
ics

Discrete MATH2410 3 MATH CS3380 CS1310 Discrete MATH24 3 MAT


Mathemat Mathema 10 H
ics tics

Discrete MATH2410 3 MATH CS3380 CS1310 Database CS3380 3 CS


Mathemat
ics

Discrete MATH2410 3 MATH CS3380 MATH2410 Intro to CS1310 4 CS


Mathemat Computer
ics Science

Discrete MATH2410 3 MATH CS3380 MATH2410 Data CS3320 4 CS


Mathemat Structures
ics

Discrete MATH2410 3 MATH CS3380 MATH2410 Discrete MATH24 3 MAT


Mathemat Mathema 10 H
ics tics

Discrete MATH2410 3 MATH CS3380 MATH2410 Database CS3380 3 CS


Mathemat
ics

Discrete MATH2410 3 MATH CS3320 CS1310 Intro to CS1310 4 CS


Mathemat Computer
ics Science

Discrete MATH2410 3 MATH CS3320 CS1310 Data CS3320 4 CS


Mathemat Structures
ics

Discrete MATH2410 3 MATH CS3320 CS1310 Discrete MATH24 3 MAT


Mathemat Mathema 10 H
ics tics

Discrete MATH2410 3 MATH CS3320 CS1310 Database CS3380 3 CS


Mathemat
ics

Database CS3380 3 CS CS3380 CS1310 Intro to CS1310 4 CS


Computer
Science

Page | 28
Database CS3380 3 CS CS3380 CS1310 Data CS3320 4 CS
Structures

Database CS3380 3 CS CS3380 CS1310 Discrete MATH24 3 MAT


Mathema 10 H
tics

Database CS3380 3 CS CS3380 CS1310 Database CS3380 3 CS

Database CS3380 3 CS CS3380 MATH2410 Intro to CS1310 4 CS


Computer
Science

Database CS3380 3 CS CS3380 MATH2410 Data CS3320 4 CS


Structures

Database CS3380 3 CS CS3380 MATH2410 Discrete MATH24 3 MAT


Mathema 10 H
tics

Database CS3380 3 CS CS3380 MATH2410 Database CS3380 3 CS

Database CS3380 3 CS CS3320 CS1310 Intro to CS1310 4 CS


Computer
Science

Database CS3380 3 CS CS3320 CS1310 Data CS3320 4 CS


Structures

Database CS3380 3 CS CS3320 CS1310 Discrete MATH24 3 MAT


Mathema 10 H
tics

Database CS3380 3 CS CS3320 CS1310 Database CS3380 3 CS

Select C2.course_name

From Course C1, Prerequisite P, Course C2

Where C1.course_name = ‘Database’

AND

C1.course_number = P.course_number

AND

P.prerequisite_number = C2.course_number;

Page | 29
Lab Sheet 7
Object:

Working with INSERT, DELETE, and UPDATE Statements in SQL

CREATE TABLE EMPLOYEE (


Fname VARCHAR(15) NOT NULL,
Minit CHAR,
Lname VARCHAR(15) NOT NULL,
Ssn CHAR(9) NOT NULL,
Bdate DATE,
Address VARCHAR(30),
Gender CHAR,
Salary DECIMAL(10,2),
Super_ssn CHAR(9),
Dno INT NOT NULL,
PRIMARY KEY (Ssn),
FOREIGN KEY (Super_ssn) REFERENCES EMPLOYEE(Ssn),
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber) );

CREATE TABLE DEPARTMENT (


Dname VARCHAR(15) NOT NULL,
Dnumber INT NOT NULL,
Mgr_ssn CHAR(9) NOT NULL,
Mgr_start_date DATE,
PRIMARY KEY (Dnumber),
UNIQUE (Dname),
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn) );

CREATE TABLE DEPT_LOCATIONS (


Dnumber INT NOT NULL,
Dlocation VARCHAR(15) NOT NULL,
PRIMARY KEY (Dnumber, Dlocation),
FOREIGN KEY (Dnumber) REFERENCES DEPARTMENT(Dnumber) );

CREATE TABLE PROJECT (


Pname VARCHAR(15) NOT NULL,
Pnumber INT NOT NULL,
Plocation VARCHAR(15),
Dnum INT NOT NULL,
PRIMARY KEY (Pnumber),
UNIQUE (Pname),
FOREIGN KEY (Dnum) REFERENCES DEPARTMENT(Dnumber) );

CREATE TABLE WORKS_ON (


Essn CHAR(9) NOT NULL,
Pno INT NOT NULL,
Hours DECIMAL(3,1) NOT NULL,
PRIMARY KEY (Essn, Pno),
FOREIGN KEY (Essn) REFERENCES EMPLOYEE(Ssn),
FOREIGN KEY (Pno) REFERENCES PROJECT(Pnumber) );

CREATE TABLE DEPENDENT (


Essn CHAR(9) NOT NULL,
Dependent_name VARCHAR(15) NOT NULL,
Gender CHAR,
Bdate DATE,
Relationship VARCHAR(8),
PRIMARY KEY (Essn, Dependent_name),
FOREIGN KEY (Essn) REFERENCES EMPLOYEE(Ssn) );

Fig. 6.1
Page | 30
THEORY
In SQL, three commands can be used to modify the database: INSERT, DELETE, and
UPDATE. We discuss each of these in turn.

Fig. 6.2

INSERT INTO EMPLOYEE


VALUES ( ‘Richard’, ‘K’, ‘Marini’, ‘653298653’, ‘1962-12-30’, ’98 Oak Forest, Katy, TX’, ‘M’, 37000, ‘653298653’, 4 );
OR
INSERT INTO EMPLOYEE (Fname, Lname, Dno, Ssn)
VALUES (‘Richard’, ‘Marini’, 4, ‘653298653’);

OR
INSERT INTO EMPLOYEE (Fname, Lname, Ssn, Dno)
VALUES (‘Robert’, ‘Hatcher’, ‘980760540’, 2);
(rejected if referential integrity checking is provided by DBMS.)
OR
INSERT INTO EMPLOYEE (Fname, Lname, Dno)
VALUES (‘Robert’, ‘Hatcher’, 5);
(rejected if NOT NULL checking is provided by DBMS.)

OR
CREATE TABLE WORKS_ON_INFO
( Emp_name VARCHAR(15),
Proj_name VARCHAR(15),
Hours_per_week DECIMAL(3,1) );

INSERT INTO WORKS_ON_INFO ( Emp_name, Proj_name, Hours_per_week )


SELECT E.Lname, P.Pname, W.Hours
FROM PROJECT P, WORKS_ON W, EMPLOYEE E
WHERE P.Pnumber=W.Pno AND W.Essn=E.Ssn;

Page | 31
The INSERT Command
In its simplest form, INSERT is used to add a single tuple to a relation. We must specify the
relation name and a list of values for the tuple. The values should be listed in the same order in
which the corresponding attributes were specified in the CREATE TABLE command. For
example, to add a new tuple to the EMPLOYEE relation shown in Fig. 6.2 and specified in the
CREATE TABLE EMPLOYEE command in Fig. 6.1 and Fig. 6.3, we can use:
CREATE TABLE EMPLOYEE
(...,
Fig. 6.3
Dno INT NOT NULL DEFAULT 1,
CONSTRAINT EMPPK
PRIMARY KEY (Ssn),
CONSTRAINT EMPSUPERFK
FOREIGN KEY (Super_ssn) REFERENCES EMPLOYEE(Ssn)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT EMPDEPTFK
FOREIGN KEY(Dno) REFERENCES DEPARTMENT(Dnumber)
ON DELETE SET DEFAULT ON UPDATE CASCADE);
CREATE TABLE DEPARTMENT
(...,
Mgr_ssn CHAR(9) NOT NULL DEFAULT ‘888665555’,
...,
CONSTRAINT DEPTPK
PRIMARY KEY(Dnumber),
CONSTRAINT DEPTSK
UNIQUE (Dname),
CONSTRAINT DEPTMGRFK
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn)
ON DELETE SET DEFAULT ON UPDATE CASCADE);
CREATE TABLE DEPT_LOCATIONS
(...,
PRIMARY KEY (Dnumber, Dlocation),
FOREIGN KEY (Dnumber) REFERENCES DEPARTMENT(Dnumber)
ON DELETE CASCADE ON UPDATE CASCADE);

We can create domain with The CHECK clause, that can also be used in conjunction with the
CREATE DOMAIN statement.

For example, we can write the following statement:


CREATE DOMAIN D_NUM AS INTEGER
CHECK (D_NUM > 0 AND D_NUM < 21);

We can then use the created domain D_NUM as the attribute type for all attributes that refer to
department numbers in Fig. 1, such as Dnumber of DEPARTMENT, Dnum of PROJECT, Dno of
EMPLOYEE, and so on.

Moreover, we can also use to define Primary Key as:

Dnumber INT PRIMARY KEY;


And check as:

CHECK (Dept_create_date <= Mgr_start_date);


In addition to key and referential integrity constraints, which are specified by special
keywords, other table constraints can be specified through additional CHECK clauses at the
end of a CREATE TABLE statement. These can be called tuple-based constraints because
they apply to each tuple individually and are checked whenever a tuple is inserted or modified.
For example, suppose that the DEPARTMENT table in Fig.6.1 had an additional attribute

Page | 32
Dept_create_date, which stores the date when the department was created. Then we could add
the following CHECK clause at the end of the CREATE TABLE statement for the
DEPARTMENT table to make sure that a
manager’s start date is later than the department creation date.

The DELETE Command

The DELETE command removes tuples from a relation. It includes a WHERE clause, similar
to that used in an SQL query, to select the tuples to be deleted. Tuples are explicitly deleted
from only one table at a time. However, the deletion may propagate to tuples in other relations
if referential triggered actions are specified in the referential integrity constraints of the DDL.

• DELETE FROM EMPLOYEE


WHERE Lname=‘Brown’;

• DELETE FROM EMPLOYEE


WHERE Ssn=‘123456789’;

• DELETE FROM EMPLOYEE


WHERE Dno=5;

• DELETE FROM EMPLOYEE;

The UPDATE Command

The UPDATE command is used to modify attribute values of one or more selected tuples. As
in the DELETE command, a WHERE clause in the UPDATE command selects the tuples to
be modified from a single relation. However, updating a primary key value may propagate to
the foreign key values of tuples in other relations if such a referential triggered action is
specified in the referential integrity constraints of the DDL.

• UPDATE PROJECT
SET Plocation = ‘Bellaire’, Dnum = 5
WHERE Pnumber=10;

• UPDATE EMPLOYEE
SET Salary = Salary * 1.1
WHERE Dno = 5;

Page | 33
Lab Sheet 8

Object:

Working with Update Operations, Transactions, and Dealing with Constraint Violations

Theory

The operations of the relational model can be categorized into retrievals and updates. The
relational algebra operations, which can be used to specify retrievals. A relational algebra
expression forms a new relation after applying a number of algebraic operators to an existing
set of relations; its main use is for querying a database to retrieve information. The user
formulates a query that specifies the data of interest, and a new relation is formed by applying
relational operators to retrieve this data. That result relation becomes the answer to (or result
of) the user’s query.

Now, we concentrate on the database modification or update operations. There are three
basic operations that can change the states of relations in the database: Insert, Delete, and
Update (or Modify). They insert new data, delete old data, or modify existing data records.
Insert is used to insert one or more new tuples in a relation, Delete is used to delete tuples,
and Update (or Modify) is used to change the values of some attributes in existing tuples.
Whenever these operations are applied, the integrity constraints specified on the relational
database schema should not be violated.
In this section we discuss the types of constraints that may be violated by each of these
operations and the types of actions that may be taken if an operation causes a violation. We
use the database shown in last activity for examples and discuss only key constraints, entity
integrity constraints, and the referential integrity constraints. For each type of operation, we give
some examples and discuss any constraints that each operation may violate.

The Insert Operation

The Insert operation provides a list of attribute values for a new tuple t that is to be inserted
into a relation R. Insert can violate any of the four types of constraints discussed in the previous
activity. Domain constraints can be violated if an attribute value is given that does not appear
in the corresponding domain or is not of the appropriate data type. Key constraints can be
violated if a key value in the new tuple t already exists in another tuple in the relation r(R). Entity
integrity can be violated if any part of the primary key of the new tuple t is NULL. Referential
integrity can be violated if the value of any foreign key in t refers to a tuple that does not exist
in the referenced relation. Here are some examples to illustrate this discussion.

■ Operation:

Insert <‘Cecilia’, ‘F’, ‘Kolonsky’, NULL, ‘1960-04-05’, ‘6357 Windy Lane, Katy, TX’, F, 28000,
NULL, 4> into EMPLOYEE.

Result: This insertion violates the entity integrity constraint (NULL for the primary key Ssn), so
it is rejected.

Page | 34
■ Operation:

Insert <‘Alicia’, ‘J’, ‘Zelaya’, ‘999887777’, ‘1960-04-05’, ‘6357 Windy Lane, Katy, TX’, F, 28000,
‘987654321’, 4> into EMPLOYEE.

Result: This insertion violates the key constraint because another tuple with the same Ssn value
already exists in the EMPLOYEE relation, and so it is rejected.

■ Operation:

Insert <‘Cecilia’, ‘F’, ‘Kolonsky’, ‘677678989’, ‘1960-04-05’, ‘6357 Windswept, Katy, TX’, F,
28000, ‘987654321’, 7> into EMPLOYEE.

Result: This insertion violates the referential integrity constraint specified on Dno in EMPLOYEE
because no corresponding referenced tuple exists in DEPARTMENT with Dnumber = 7.

■ Operation:

Insert <‘Cecilia’, ‘F’, ‘Kolonsky’, ‘677678989’, ‘1960-04-05’, ‘6357 Windy Lane, Katy, TX’, F,
28000, NULL, 4> into EMPLOYEE.

Result: This insertion satisfies all constraints, so it is acceptable.

If an insertion violates one or more constraints, the default option is to reject the insertion. In
this case, it would be useful if the DBMS could provide a reason to the user as to why the
insertion was rejected. Another option is to attempt to correct the reason for rejecting the
insertion, but this is typically not used for violations caused by Insert; rather, it is used more
often in correcting violations for Delete and Update. In the first operation, the DBMS could ask
the user to provide a value for Ssn, and could then accept the insertion if a valid Ssn value is
provided. In operation 3, the DBMS could either ask the user to change the value of Dno to
some valid value (or set it to NULL), or it could ask the user to insert a DEPARMENT tuple with
Dnumber = 7 and could accept the original insertion only after such an operation was accepted.
Notice that in the latter case the insertion violation can cascade back to the EMPLOYEE
relation if the user attempts to insert a tuple for department 7 with a value for Mgr_ssn that does
not exist in the EMPLOYEE relation.

Page | 35
The Delete Operation

The Delete operation can violate only referential integrity. This occurs if the tuple being deleted
is referenced by foreign keys from other tuples in the database. To specify deletion, a condition
on the attributes of the relation selects the tuple (or tuples) to be deleted. Here are some
examples.
■ Operation:

Delete the WORKS_ON tuple with Essn = ‘999887777’ and Pno = 10.

Result: This deletion is acceptable and deletes exactly one tuple.


■ Operation:

Delete the EMPLOYEE tuple with Ssn = ‘999887777’.

Result: This deletion is not acceptable, because there are tuples in WORKS_ON that refer to
this tuple. Hence, if the tuple in EMPLOYEE is deleted, referential integrity violations will result.
■ Operation:

Delete the EMPLOYEE tuple with Ssn = ‘333445555’.

Result: This deletion will result in even worse referential integrity violations, because the tuple
involved is referenced by tuples from the EMPLOYEE, DEPARTMENT,WORKS_ON, and
DEPENDENT relations. Several options are available if a deletion operation causes a violation.
The first option, called restrict, is to reject the deletion. The second option, called cascade, is
to attempt to cascade (or propagate) the deletion by deleting tuples that reference the tuple that
is being deleted. For example, in operation 2, the DBMS could automatically delete the
offending tuples from WORKS_ON with Essn = ‘999887777’. A third option, called set null or
set default, is to modify the referencing attribute values that cause the violation; each such
value is either set to NULL or changed to reference another default valid tuple.

Notice that if a referencing attribute that causes a violation is part of the primary key, it cannot
be set to NULL; otherwise, it would violate entity integrity.

Combinations of these three options are also possible. For example, to avoid having
operation 3 cause a violation, the DBMS may automatically delete all tuples from WORKS_ON
and DEPENDENT with Essn = ‘333445555’. Tuples in EMPLOYEE with
Super_ssn = ‘333445555’ and the tuple in DEPARTMENT with Mgr_ssn = ‘333445555’ can
have their Super_ssn and Mgr_ssn values changed to other valid values or to NULL. Although
it may make sense to delete automatically the WORKS_ON and DEPENDENT tuples that refer
to an EMPLOYEE tuple, it may not make sense to delete other EMPLOYEE tuples or a
DEPARTMENT tuple.

In general, when a referential integrity constraint is specified in the DDL, the DBMS will allow
the database designer to specify which of the options applies in case of a violation of the
constraint.

Page | 36
The Update Operation

The Update (or Modify) operation is used to change the values of one or more attributes in a
tuple (or tuples) of some relation R. It is necessary to specify a condition on the attributes of the
relation to select the tuple (or tuples) to be modified.

Here are some examples.

■ Operation:

Update the salary of the EMPLOYEE tuple with Ssn = ‘999887777’ to 28000.

Result: Acceptable.

■ Operation:

Update the Dno of the EMPLOYEE tuple with Ssn = ‘999887777’ to 1.

Result: Acceptable.

■ Operation:

Update the Dno of the EMPLOYEE tuple with Ssn = ‘999887777’ to 7.

Result: Unacceptable, because it violates referential integrity.

■ Operation:

Update the Ssn of the EMPLOYEE tuple with Ssn = ‘999887777’ to ‘987654321’.

Result: Unacceptable, because it violates primary key constraint by repeating a value that
already exists as a primary key in another tuple; it violates referential integrity constraints
because there are other relations that refer to the existing value of Ssn.

Updating an attribute that is neither part of a primary key nor of a foreign key usually causes no
problems; the DBMS need only check to confirm that the new value is of the correct data type
and domain. Modifying a primary key value is similar to deleting one tuple and inserting another
in its place because we use the primary key to identify tuples. If a foreign key attribute is
modified, the DBMS must make sure that the new value refers to an existing tuple in the
referenced relation (or is set to NULL). Similar options exist to deal with referential integrity
violations caused by Update as those options discussed for the Delete operation. In fact, when
a referential integrity constraint is specified in the DDL, the DBMS will allow the user to choose
separate options to deal with a violation caused by Delete and a violation caused by Update.

Page | 37
Lab Sheet 9
OBJECT
Single-row and multiple-row functions in SQL

THEORY

SQL functions
Functions are a very powerful feature of SQL and can be used to do the following tasks:
▪ Perform calculations on data
▪ Modify individual data items
▪ Manipulate output for groups of rows
▪ Format dates and numbers for display
▪ Convert column datatypes

SQL functions may accept arguments and always return a value as illustrated in figure 8.1.

Input Output
arg 1
Function
arg 2 Result Value

arg 3
Fig 8.1: Functions accept arguments and return a value

Types of SQL functions


There are two distinct types of functions:
▪ Single-row
▪ Multiple-row
Single-Row functions
These functions operate on single rows only and return one result per row. There are different
types of single-row functions. This session covers the following ones:
▪ Character
▪ Number
▪ Date
▪ Conversion
Multiple-Row functions
These functions manipulate groups of rows to give one result per group of rows.

Single-Row Functions
Character Functions
Single-row character functions accept character data as input and can return both character
and number values. Character functions can be divided into the following:-

▪ Case conversion functions


▪ Character manipulation functions

Page | 38
Case Conversion Functions
Convert case for character strings

Function Result
LOWER(‘SQL Course’) sql course
UPPER(‘SQL Course’) SQL COURSE
INITCAP(‘SQL Course’) Sql Course

Table 8.1
Examples

i. To print an employee name (first letter capital) and job title (lower case)
SELECT ‘The job title for ‘ || INITCAP(ename) || ‘ is ‘ || LOWER(job) AS “EMPLOYEE
DETAILS” FROM emp;
ii. To display the employee number, name (in upper case) and department number for
employee Blake.
SELECT empno, UPPER(ename), deptno
FROM emp
WHERE LOWER(ename) = ‘blake’;
Note: Since the actual case of the letters in the employee name column may not be
known, so it is necessary for comparison to convert the name to either uppercase or
lowercase.

Character manipulation functions


Manipulate character strings

Function Result
CONCAT(‘Good’, ‘String’) GoodString
SUBSTR(‘String’, 2, 4) trin
LENGTH(‘String’) 6
INSTR(‘String’, ‘r’) 3
LPAD(sal, 10, ‘*’) ******5000

Table 8.2
Example

To display employee name and job joined together, length of employee name, and the
numeric position of letter A in the employee name, for all employees who are in sales.
SELECT empno, CONCAT(ename, job), LENGTH(ename), INSTR(ename, ‘A’)
FROM emp
WHERE SUBSTR(job, 1, 5) = ‘SALES’;

Number Functions
Number functions accept numeric input and return numeric values.
ROUND(column|expression, n) Rounds the column, expression or value to n decimal
places or if n is omitted, no decimal places (If n is negative, numbers to left of decimal point
are rounded)

TRUNC(column|expression, n) Truncates the column, expression or value to n decimal


places or if n is omitted, no decimal places (If n is negative, numbers to left of decimal point
are truncated)

Page | 39
MOD(m, n) Returns the remainder of m divided by n

Function Result
ROUND(45.927, 2) 45.93
ROUND(45.927) 46
ROUND(45.927, -1) 50
TRUNC(45.927, 2) 45.92
TRUNC(45.927) 45
MOD(20, 3) 2

Table 8.3
Examples

i. SELECT ROUND(45.923, 2), ROUND(45.923, 0),


ROUND(45.923, -1) FROM DUAL;
The DUAL is a dummy table with one column and one row.
ii. SELECT TRUNC(45.923, 2), TRUNC(45.923),
TRUNC(45.923, -1) FROM DUAL;
iii. To calculate the remainder of the ratio of salary to commission for all employees
whose job title is salesman.
SELECT ename, sal, comm., MOD(sal, comm.)
FROM emp
WHERE UPPER(job) = ‘SALESMAN’;

Date Functions
SYSDATE is a date function that returns the current date and time. The current date can be
displayed by selecting SYSDATE from a table. It is customary to select SYSDATE from a
dummy table called DUAL.
The DUAL table is owned by the user SYS and can be accessed by all users. It contains one
column, DUMMY, and one row with the value X. It is useful for returning a value once only
– for instance, the value of a constant, pseudocolumn, or expression that is not derived from a
table with user data.
For example, to display the current date using the DUAL table as
SELECT SYSDATE
FROM DUAL;

Arithmetic with Dates


We can add or subtract a number to or from a date for a resultant date value. For example, to
display the name and the number of weeks employed for all employees in department 10.
SELECT ename, (SYSDATE – HIREDATE) / 7 “Number of Weeks”
FROM emp
WHERE deptno = 10;

Date functions operate on Oracle dates. All date functions return a value of DATE datatype
except MONTHS_BETWEEN, which returns a numeric value.

Page | 40
Function Result Description
MONTHS_BETWEEN(’01-SEP-95’, ’11-JAN-94’) 19.6774194 Number of months
between two dates
ADD_MONTHS(’11-JAN-94’, 6) ’11-JUL-94’ Add calendar
months to dates
NEXT_DAY(’01-SEP-95’, ‘FRIDAY’) ’08-SEP-95’ Next day of the date
specified
LAST_DAY(’01-SEP-95’) ’30-SEP-95’ Last day of the
month
ROUND(TO_DATE(’25-JUL-95’, ‘DD-MON-YY’), 01-AUG-95 Round date
‘MONTH’)
ROUND(TO_DATE(’25-JUL-95’, ‘DD-MON-YY’), 01-JAN-96 Round date
‘YEAR’)
TRUNC(TO_DATE(’25-JUL-95’, ‘DD-MON-YY’), 01-JUL-95 Truncate date
‘MONTH’)
TRUNC(TO_DATE(’25-JUL-95’, ‘DD-MON-YY’), 01-JAN-95 Truncate date
‘YEAR’)

Table 8.4
Examples

i. For all employees employed for fewer than 200 months, display the employee number,
hiredate, number of months employed, six-month review date, first Friday after
hiredate and last day of the month hired.
SELECT empno, hiredate, MONTHS_BETWEEN(SYSDATE, hiredate) TENURE,
ADD_MONTHS(hiredate, 6) REVIEW, NEXT_DAY(hiredate, ‘FRIDAY’),
LAST_DAY(hiredate) FROM emp
WHERE MONTHS_BETWEEN(SYSDATE, hiredate) < 200;
ii. Comparing the hire dates for all employees who started in 1982, display the employee
number, hiredate, and month started using the ROUND and TRUNC functions. SELECT
empno, hiredate, ROUND(hiredate, ‘MONTH’),TRUNC(hiredate,
‘MONTH’) FROM emp
WHERE hiredate like ‘%82’;

Conversion Functions

Figure 8.2

SQL provides three functions to convert a value from one data type to another.
TO_CHAR
TO_NUMBER
TO_DATE

Page | 41
TO_CHAR function with Dates
i. To display the employee number, the month number and year of hiring
SELECT empno, TO_CHAR(hiredate, ‘MM/YY’) Month_Hired FROM
emp
WHERE ename = ‘BLAKE’;
The second argument of TO_CHAR is called format model, is in single quotation
marks and is case sensitive.
ii. To display the employee name and hiredate for all employees. The hiredate appears as
17 November, 1981.
SELECT ename, TO_CHAR(hiredate, 'fmDD Month, YYYY') HIREDATE
FROM emp;
The fm element is used to remove padded blanks or suppress leading zeros.
iii. To print the employee name and time of joining in format HH:MI:SS (Assuming that
hiredate column were used for storing joining time)
SELECT ename, TO_CHAR(hiredate, ‘HH:MI:SS’) HIREDATE
FROM emp;

TO_CHAR function with Numbers


It is used to display a number value as a character string. This technique is especially useful
for concatenating a numeric value to a character string.
i. To display the salary of employee SCOTT with $ sign preceded
SELECT TO_CHAR(sal, ‘$99,999’) SALARY
FROM emp
WHERE ename = ‘SCOTT’;
The oracle server displays a string of pound signs (#) in place of a whole number whose
digits exceed the number of digits provided in the format model. The oracle server
rounds the stored decimal value to the number of decimal places provided in the format
model.

TO_NUMBER function
Convert a character string to a number format using the TO_NUMBER function.
TO_DATE function
Converts a character string to a date format using the TO_DATE function.
i. To display the names and hire dates of all the employees who joined on February 22,
1981
SELECT ename, hiredate
FROM emp
WHERE hiredate = TO_DATE(‘February 22, 1981’, ‘Month dd, YYYY’);

DECODE Function
Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement. It
decodes an expression in a way similar to the IF-THEN-ELSE logic used in various
languages. The DECODE function decodes expression after comparing it to each search
value. If the expression is the same as search, result is returned.
If the default value is omitted, a null value is returned where a search value does not match
any of the result values.
DECODE (col/expression, search1, result1 [,search2, result2, ….,] [, default]);
Examples
i. To print job, salary and revised salary depending on the job.

Page | 42
SELECT job, sal, DECODE (job, ‘ANALYST’, SAL*1.1, ‘CLERK’, SAL*1.15,
‘MANAGER’, SAL*1.20, SAL) REVISED_SALARY
FROM emp;
The same statement can be written as an IF-THEN-ELSE statement:
IF job = ‘ANALYST’ THEN sal = sal * 1.1
IF job = ‘CLERK’ THEN sal = sal * 1.15
IF job = ‘MANAGER’ THEN sal = sal * 1.20
ELSE sal = sal
ii. To display the applicable tax rate for each employee in department 30
SELECT ename, sal, DECODE(TRUNC(sal/1000, 0),
0, 0.00,
1, 0.09,
2, 0.20,
3, 0.30,
4, 0.40,
5, 0.42,
6, 0.44,
0.45) TAX_RATE
FROM emp
WHERE deptno = 30;

Nesting Functions
Single-row functions can be nested to any level. For example, the following query displays
the head of a company who has no manager.
SELECT ENAME, NVL(TO_CHAR(MGR), ‘No Manager’)
FROM EMP
WHERE MGR IS NULL;

Multiple_Row Functions
Group functions operate on sets of rows to give one result per group. The following table
identifies the options that can be used in the syntax:-

Following is the syntax of using group functions:-


SELECT [column, ] group_function(column)
FROM table
[WHERE condition]
[GROUP BY column]
[ORDER BY column];

Applying multiple-row functions to all rows in a table


Examples
i. To show the average salary, minimum salary, maximum salary and count of
employees in the organization
SELECT AVG (SAL), MIN(SAL), MAX(SAL), COUNT(*)
FROM EMP;
ii. To show the minimum and maximum hiredate for employees
SELECT MIN (hiredate), MAX(hiredate)
FROM emp;
iii. To return the number of rows in a table

Page | 43
SELECT COUNT(*)
FROM emp
WHERE deptno = 30;
iv. To return the number of nonnull rows in a table
SELECT COUNT(comm)
FROM emp
WHERE deptno = 30;
v. The group function like AVG do not include null rows. The NVL function forces
group functions to include null values.
SELECT AVG(NVL(comm, 0))
FROM emp;
Display employees who not receive commission;
vi. SELECT ename, 'not receive commission' as comm from emp where NVL(comm,
NULL) is NULL;
Applying Multiple-row functions to groups of rows in a table
Examples
i. To show the department-wise average salary,
SELECT deptno, AVG(sal) AVERAGE_SALARY
FROM emp
GROUP BY deptno;
Note that all columns in the SELECT list that are not in group functions must be in the
GROUP BY clause.
ii. To show the job-wise total salary for each department
SELECT deptno, job, sum(sal)
FROM emp
GROUP BY deptno, job;

Excluding groups result


In the same way that we use the WHERE clause to restrict the rows that we select, the
HAVING clause is used to restrict groups. First the group function is applied and the groups
matching the HAVING clause are displayed.
The syntax of the SELECT statement showing the HAVING clause along with the GROUP
BY clause is shown below:-

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

The HAVING clause can precede the GROUP BY clause but it is recommended that the
GROUP BY clause come first because it is more logical.
Examples
i. To show the department-wise average and maximum salary, in the descending order of
average salary, for all departments having average salary higher than 4500.
SELECT DEPTNO, AVG(SAL), MAX(SAL)
FROM EMP
GROUP BY DEPTNO
HAVING AVG(SAL) > 2000
ORDER BY AVG(SAL)

Page | 44
ii. To display the job title and total monthly salary for each job title with a total payroll
exceeding 5000.
SELECT JOB, SUM(SAL) PAYROLL
FROM EMP
WHERE JOB NOT LIKE 'SALES%'
GROUP BY JOB
HAVING SUM(SAL) > 5000
ORDER BY SUM(SAL);

Nesting Group Functions


i. To display the maximum average salary by nesting group functions
SELECT max(avg(sal))
FROM emp
GROUP BY deptno;

EXERCISES
1. Write down the result of the function calls in the first column to the second column.

Function Call Result


SUBSTR(CONCAT(‘HIGH’, ‘SALARY’), 4, 6) HSALAR
CONCAT(SUBSTR(‘INFORMATION’, 3, 4), ‘TECH’) FORMTECH
INSTR(CONCAT(‘GET’, ‘ING’), ‘TIN’) 3
ROUND(69.476, 1) 69.5
TRUNC(’13-MAR-90’, ‘MONTH’) 1-MAR-90
TRUNC(’13-MAR-90’, ‘YEAR’) 1-JAN-90
MOD(90, LENGTH(‘SEVENTY’)) 6
MONTHS_BETWEEN(’14-AUG-96’, ’23-MAR-95’) 16.71

2. Write down SQL queries to perform following functions:-


i. To show the current date. Label the column Current Date.

ii. To display the employee number, name, salary, salary increase by 15% expressed as a
whole number (labeled as New Salary), the difference between old salary and new
salary (labeled as Increment).

Page | 45
iii. To display the employee name and calculate the number of months between today and
the date the employee was hired (Labeled as Months_Worked). Order the results by
the number of months employed and round the number of months up to the closest
whole number.

iv. Write a query that produces the following for each employee:
<employee name> earns <salary> monthly

v. To display the employee’s name (labeled name) with the first letter capitalized and all
other letters lowercase and the length of their name (labeled length), for all employees
whose name starts with J, A or M.

vi. To list the name, hiredate, and day of the week (labeled DAY) on which job was
started. Order the result by day of week starting with Monday.

vii. To display the job-wise count of employees in each department as follows:-


DEPTNO JOB NUM_EMP

Page | 46
viii. To display the department name, location name, number of employees and the average salary for all
employees in that department. Label the columns DNAME, LOC, NUMBER OF PEOPLE and
SALARY, respectively. Round the average salary to two decimal places.

ix. To display the employee name, department number and job title for all employees whose
department location is Dallas.

x. To display the difference between the highest and lowest salaries (Labeled as DIFFERENCE)

xi. To show the manager name, MANAGER, and the number of employees, NUM, working under
him.

Reference:
Practical Workbook, Database Management Systems, Second Edition, Reviewed in 2011, Department of Computer & Information Systems Engineering,
NED University of Engineering & Technology, Karachi – 75270, Pakistan

Page | 47
Lab Sheet 10
Object:
Introduction to Subqueries in SQL

THEORY

SUBQUERIES
Why use subqueries?
uppose we want to write a query to find out who earns a salary greater than Jones’ salary. To solve this
Sproblem, we need two queries: one query to find what Jones earns and a
second query to find who earns more than that amount.
The above problem can be solved by combining the two queries, placing one query inside the other query.
The inner query or the subquery returns a value that is used by the outer query or the main query. Using
a subquery is equivalent to performing two sequential queries and using the result of the first query as the
search value in the second query.

Main Query “Which employees have a salary greater than


Jones’ Salary?”

Subquery

“What is Jones’ salary?”


Figure 9.1 Subquery
A subquery is a SELECT statement that is embedded in a clause of another SELECT
statement. They can be very useful when we need to select rows from a table with a condition
that depends on the data in the table itself. The subquery generally executes first and its output is
used to complete the query condition for the main or outer query.
The subquery can be placed in a number of SQL clauses:
▪ WHERE clause
▪ HAVING clause
▪ FROM clause
The syntax of SELECT statement using subqueries is

SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Note: In the syntax, operator means comparison operator. Comparison operators fall into two
clauses: single-row operators (>, =, >=, <, <>, <=) and multiple-row operators (IN, ANY,
ALL).
For example, to display the names of all employees who earn more than employee with
number 7566.

Page | 48
SELECT ename
FROM emp
WHERE sal >
(SELECT sal
FROM emp
WHERE empno = 7566);

Types of Subqueries
Single-row subquery: Query that returns only one row from the inner SELECT statement.
Multiple-row subquery: Query that returns more than one row form the inner SELECT
statement.
Multiple-column subquery: Query that returns more than one column from the inner
SELECT statement.

Single-Row Subqueries
Examples
i. To display the employees whose job title is the same as that of employee 7369.
SELECT ename, job
FROM emp
WHERE job =
(SELECT job
FROM emp
WHERE empno = 7369);
ii. To display employees whose job title is the same as that of employee 7369 and whose
salary is greater than that of employee 7876.
SELECT ename, job
FROM emp
WHERE job =
(SELECT job
FROM emp
WHERE empno = 7369)
AND sal >
(SELECT sal
FROM emp
WHERE empno = 7876);

iii. We can display data from a main query by using a group function in a subquery to return
a single row. e.g. to display the employee name, job title and salary of all employees
whose salary is equal to the minimum salary.

SELECT ename, job, sal


FROM emp
WHERE sal =
(SELECT MIN(sal) FROM emp);

Page | 49
iv. We can use subqueries not only in the WHERE clause, but also in the HAVING
clause. The Oracle server executes the subquery and the results are returned into the
HAVING clause of the main query. E.g. to display all departments that have a
minimum salary greater than that of department 20.
SELECT deptno, MIN(sal)
FROM emp
GROUP BY deptno
HAVING MIN(sal) >
(SELECT MIN(sal)
FROM emp
WHERE deptno = 20);

Multiple-Row Subqueries
Multiple-row subqueries return more than one row. We use multiple-row operator, instead of a
single-row operator, with a multiple-row subquery. The multiple-row operator expects one or
more values. Following table illustrates multiple row operators.

Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by the subquery
ALL Compare value to every value returned by the subquery
Table 5.1
Note: The NOT operator can be used with IN, ANY, and ALL operators.
Examples
i. Find the employees who earn the same salary as the minimum salary for
departments. SELECT ename, sal, deptno
FROM emp
WHERE sal IN (SELECT MIN(sal)
FROM emp
GROUP BY deptno);
ii. To display employees whose salary is less than any clerk and who are not
clerks. SELECT empno, ename, job
FROM emp
WHERE sal < ANY
(SELECT sal
FROM emp
WHERE job = ‘CLERK’)
AND JOB <> ‘CLERK’;
iii. To display employees whose salary is greater than the average salary of all the
departments.
SELECT empno, ename, job
FROM emp
WHERE sal > ALL
(SELECT avg(sal)
FROM emp
GROUP BY deptno);
Multiple-Column Subqueries
If we want to compare two or more columns, we must write a compound WHERE clause
using logical operators. Multiple column subqueries enable us to combine duplicate WHERE

Page | 50
conditions into a single WHERE clause.
For example, to display the name of all employees who have done their present job
somewhere before in their career.

SELECT ENAME
FROM EMP
WHERE (EMPNO, JOB)
IN
(SELECT EMPNO, JOB
FROM JOB_HISTORY)

Page | 51
Lab Sheet 11

Object:

Working with Compound Queries

In SQL, we can use the normal set operators of Union, Intersection and Set Difference to
combine the results of two or more component queries into a single result table. Queries
containing SET operators are called compound queries. The following table shows the
different set operators provided in Oracle SQL.

Operator Returns
UNION All distinct rows selected by either query
UNION ALL All rows selected by either query including all duplicates
INTERSECT All distinct rows selected by both queries
MINUS All distinct rows that are selected by the first SELECT statement and
that are not selected in the second SELECT statement

Table 5.2
Restrictions on using set Operators

There are restrictions on the tables that can be combined using the set operations, the most
important one being that the two tables have to be union-compatible; that is, they have the
same structure. This implies that the two tables must contain the same number of columns,
and that their corresponding columns contain the same data types and lengths. It is the user’s
responsibility to ensure that values in corresponding columns come from the same domain.
For example, it would not be sensible to combine a column containing the age of staff with
the number of rooms in a property, even though both columns may have the same data type
i.e. NUMBER.

The UNION Operator


The UNION operator returns rows from both queries after eliminating duplicates. By default,
the output is sorted in ascending order of the first column of the SELECT clause.
For example to display all the jobs that each employee has performed, the following query
will be given. (NOTE: If an employee has performed a job multiple times, it will be shown
only once)
SELECT EMPNO, JOB
FROM JOB_HISTORY
UNION
SELECT EMPNO, JOB
FROM EMP;

The UNION ALL Operator


The UNION ALL operator returns rows from both queries including all duplicates. For
example to display the current and previous jobs of all employees, the following query will be
given. (NOTE: If an employee has performed a job multiple times, it will be shown
separately)

Page | 52
SELECT EMPNO, JOB
FROM JOB_HISTORY
UNION ALL
SELECT EMPNO, JOB
FROM EMP;

The INTERSECT Operator


The INTERSECT operator returns all rows that are common to both queries. For example, to
display all employees and their jobs those have already performed their present job
somewhere else in the past.

SELECT EMPNO, JOB


FROM JOB_HISTORY
INTERSECT
SELECT EMPNO, JOB
FROM EMP;

The MINUS Operator


The MINUS operator returns rows from the first query that is not present in the second query.
For example to display the ID of those employees whose present job is the first one in their
career.

SELECT EMPNO, JOB


FROM EMP
MINUS
SELECT EMPNO, JOB
FROM JOB_HISTORY;

EXERCISE
1. Why are subqueries needed in accessing data from the database?

Page | 53
2. Write down the restrictions on using set operators in SQL.

3. Write down SQL queries to perform following functions:-

i. To display the employee number and name for all employees who earn more than the
average salary. Sort the results in descending order of salary.

ii. To display the employee name and salary of all employees who report to king.

iii. To display the department number, name and job for all employees in the Sales
department.

iv. To display the name, hiredate and salary for all employees who have both the same
salary and commission as scott.

Page | 54
v. To display the employee name, department number and job title for all employees whose location
is Dallas.

vi. List the id of all employees who have not performed the job of analyst anywhere in their career.
(Note: Use set operators)

vii. Write a query to display the employee name and hiredate for all employees in the same
department as Blake. Exclude Blake.

viii. Display the employee number, name and salary for all employees who earn more than the average
salary and who work in department with any employee with a T in their name.

Page | 55
Lab Sheet 12
Object:

Data retrieval operations in SQL using join operations

THEORY
We frequently need data from more than one table. For example, suppose we need a report that displays
employee id, name, job and department name. The first three attributes are present in EMP table where as the
last one is in DEPT table (see lab session 1). To produce the report, we need to link the EMP and DEPT
tables and access data from both of them. This is called join operation. To gain better understanding of join,
it would be helpful to first clarify the concept of Cartesian Product.

Figure 9.1: The join operation collects data from multiple sources

Cartesian Product
A Cartesian Product results when all rows in the first table are joined to all rows in the second table. A
Cartesian product is formed under following conditions:-
i. When a join condition is omitted ii. When
a join condition is invalid
Consider the following example:-
SELECT *
FROM EMP, DEPT;
In the above example, if EMP table has 14 rows and DEPT table has 4 rows, then their
Cartesian product would generate 14 x 4 = 56 rows.
In fact, the ISO standard provides a special format of the SELECT statement for the Cartesian product:-
SELECT *
FROM EMP CROSS JOIN DEPT;

A Cartesian product tends to generate a large number of rows and its result is rarely useful. It is always
necessary to include a valid join condition in a WHERE clause. Hence a join is always a subset of a
Cartesian product.
Types of Joins
There are various forms of join operation, each with subtle differences, some more useful than others. The
Oracle 9i database offers join syntax that is SQL 1999 compliant. Prior to release
9i, the join syntax was different from the ANSI standard. However, the new syntax does not
offer any performance benefits over the Oracle proprietary join syntax that existed in prior releases.

Page | 56
i. Inner-Join/Equi-Join
If the join contains an equality condition, it is called equi-join.
Examples
i. To retrieve the employee name, their job and department name, we need to extract
data from two tables, EMP and DEPT. This type of join is called equijoin-that is,
values in the DEPTNO column on both tables must be equal. Equijoin is also called
simple join or inner join.
SELECT E.ENAME, E.JOB, D.DNAME
FROM EMP E, DEPT D
WHERE E.DEPTNO = D.DEPTNO;
The SQL-1999 standard provides the following alternative ways to specify this join:-
SELECT ENAME, JOB, DNAME
FROM EMP NATURAL JOIN DEPT;

ii. Outer-Join
A join between two tables that returns the results of the inner join as well as unmatched rows
in the left or right tables is a left or right outer join respectively. A full outer join is a join
between two tables that returns the results of a left and right join.
Left Outer Join
SELECT E.ENAME, D.DEPTNO, D.DNAME
FROM EMP E, DEPT D
WHERE E.DEPTNO = D.DEPTNO(+);
NOTE: The outer join operator appears on only that side that has information missing.

The SQL-1999 standard provides the following alternative way to specify this join:-
SELECT E.ENAME, D.DEPTNO, D.DNAME
FROM EMP E LEFT OUTER JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO);
Right Outer Join
SELECT E.ENAME, D.DEPTNO, D.DNAME
FROM EMP E, DEPT D
WHERE E.DEPTNO(+) = D.DEPTNO;
The SQL-1999 standard provides the following alternative way to specify this join:-
SELECT E.ENAME, D.DEPTNO, D.DNAME
FROM EMP E RIGHT OUTER JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO);
NOTE: In the equi-join condition of EMP and DEPT tables, department OPERATIONS does
not appear because no one works in that department. In the outer join condition, the
OPERATIONS department also appears.

The output is shown in figure 9.2.

Page | 57
Figure 9.2: Joining tables using right outer-join

Full Outer Join


The SQL-1999 standard provides the following way to specify this join:- SELECT
E.ENAME, D.DEPTNO, D.DNAME
FROM EMP E FULL OUTER JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO);

iii. Non-Equijoin
If the join contains inequality condition, it is called non-equijoin. E.g. to retrieve employee name, salary
and their grades using non-equijoins, we need to extract data from two tables, EMP and SALGRADE.
SELECT E.ENAME, E.SAL, S.GRADE FROM
EMP E, SALGRADE S
WHERE E.SAL
BETWEEN S.LOSAL AND S.HISAL;

iv. Self Join


To find the name of each employee’s manager, we need to join the EMP table to itself, or perform a
self join.
SELECT WORKER.ENAME || ‘ works for ‘ || MANAGER.ENAME FROM
EMP WORKER, EMP MANAGER
WHERE WORKER.MGR = MANAGER.EMPNO;

Page | 58
EXERCISES
i. To display the employee name, department name, and location of all employees who earn a commission.

ii. To display all the employee’s name (including KING who has no manager) and their manager name.

iii. To display the name of all employees whose manager is KING.

iv. Create a unique listing of all jobs that in department 30. Include the location of department 30 in the
Output.

v. Write a query to display the name, job, department number and department name for all employees who
work in DALLAS.

vi. Display the employee name and employee number along with their manager’s name Manager Number.
Label the columns Employee, Emp#, Manager, and Manager#, respectively.

Reference:
Practical Workbook, Database Management Systems, Second Edition, Reviewed in 2011, Department of Computer &
Information Systems Engineering, NED University of Engineering & Technology, Karachi – 75270, Pakistan.

Page | 59

You might also like