Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DBMS Query

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

DATABASE MANAGEMENT SYSTEMS LABORATORY LTPC

0 0
42
AIM:

The aim of this laboratory is to inculcate the abilities of applying the principles of the
database management systems. This course aims to prepare the students for projects where a proper
implementation of databases will be required.

OBJECTIVES:
 To understand data definitions and data manipulation commands
 To learn the use of nested and join queries
 To understand functions, procedures and procedural extensions of data bases
 To be familiar with the use of a front end tool
 To understand design and implementation of typical database applications

LIST OF EXPERIEMENTS
1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating and
retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications
TOTAL: 60 PERIODS

OUTCOMES:

Upon completion of the course, the students will be able to:

 Use typical data definitions and manipulation commands.


 Design applications to test Nested and Join Queries
 Implement simple applications that use Views
 Implement applications that require a Front-end Tool
 Critically analyze the use of Tables, Views, Functions and Procedures

LIST OF EXPERIMENTS:

1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating and
retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications

BEYOND SYLLABUS

1. Embedded SQL programs.


2. Packages

MINI PROJECT

1. Time Table Management System


Ex. 1. Data Definition Commands, Data Manipulation Commands for
inserting, deleting, updating and retrieving Tables and Transaction Control
statements

Aim : To create database and perform DML and TCL queries to retrieve information from
the database.

BACKGROUND THEORY:

Different types of commands in SQL:

 DDL commands: - To create a database objects.


 DML commands: - To manipulate data of a database objects.
 TCL Commands – To manage changes and save a database

Data Definition Language (DDL): To specify the database schema.


DDL Commands:
 Create
 Alter
 Rename
 Drop

1. Creation of Table: Creates a table with specified attributes and its data type along with
constraints.
Syntax:
Create table r (A1 D1 , A2 D2,………An Dn,
(integrity-constraint1),
….,
(integrity-constraintk));
where r – relation name(Table name),
Ai – Attribute name,
Di – Data type.
Data Types in SQL:

1. char(n) : Fixed-length character string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255 characters
2. varchar(n) : Variable-length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note:
If you put a greater value than 255 it will be converted to a TEXT type
3. int : Integer -2147483648 to 2147483647 normal. 0 to 4294967295. The maximum
number of digits may be specified in parenthesis
4. smallint : Small Integer -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
5. numeric(p,d) : The number consists of p digits(plus a sign), d of the p digits are to
the right of the decimal point.
6. float(n,d) : Floating-point number. The maximum number of digits may be
specified in the size parameter. The maximum number of digits to the right of the decimal point
is specified in the d parameter
7. double (size,d): A large number with a floating decimal point. The maximum
number of digits may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter.
8. date : The date containing a date, month and year. Used to store date value as
DD-MON-YY, data size is 9 byte
Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
9. time : The time in hours, minutes and seconds.
Format: HH:MM:SS
10. timestamp : The combination of date and time.
Format: YYYY-MM-DD HH:MM:SS

Eg: Create a customer table which consists of 4 columns:


i) custID - Customer ID – Integer – Primary Key
ii) custname – Customer Name – varchar2 (15)
iii) custstreet – Customer Street – varchar2 (20)
iv) custcity – Customer City – varchar2 (10)
create table customer (
custID int,
custname varchar2(15),
custstreet varchar2(20),
custcity varchar2(10),Primary key (CustID));

2. To view the table structure:


Syntax:
desc r;
Ex:
Desc customer;

3. Retrieval of Information by Select Command

Syntax-
(i) Select A1,A2.. ,An from r1
(ii) Select * from r1;
(iii) Select A1,A2.. ,An from r1,r2,..,rn;
(iv) Select A1,A2.. ,An from r1,r2,..,rn where condition;

Example-
(i) Select CustID,Custname from customer ;
(ii) Select CustID,Custname from customer where Custname=’Arun’);

DDL Commands:

 Create
 Alter
 Rename
 Drop

Altering the Table Schema: Add or delete or change the attribute and data type.
It also can add or drop the integrity constraints.
Syntax:
1. Alter table r add (Ai Di);
2. Alter table r drop(Ai);
3. Alter table r modify(Ai Di);
4. Alter table r add primary key(Ai);
5. Alter table r enable primary key;
6. Alter table r disable primary key;
Eg:
Alter table customer add ( phoneno int(12));
Alter table customer drop( custcity);
Alter table customer modify( custname varchar2(20));
Alter table depositor add primary key(acctno);
Alter table depositor disable primary key;
Alter table depositor enable primary key;

Rename: Change the table name


Syntax:
Rename <tablename> to <newtablename>;
Eg:
Rename emp to employee;

Dropping the Table: Deletes all information and structure about that table(relation)
Syntax:
Drop table r;
Eg:
Drop table customer;
Data Manipulation Language (DML) – to express database queries and updates.

List of DML Commands:


1. Insertion of information
2. Retrieval of information
3. Deleting information
4. Modifying information

Two types of DML –

1. Procedural DMLs – requires a user to specify what data are needed and how to get
those data.
2. Declarative DMLs ( nonprocedural language) - requires a user to specify what data are
needed without specifying how to get those data.
DML Component of SQL language is nonprocedural language.

Query is a statement requesting the retrieval of information.

1. Insertion of information can be done in two ways -


(i) Syntax-
Insert into r values(V1, V2,…,Vn); // where Vi – Attribute Values
r - relation name (Table name)
Example-
Insert into customer values(101,’Arun’, ‘Bharathi Street’,’Chennai’);

(ii) Syntax-
Insert into r values(‘&A1’,’&A2’,….,’&An’); // where Ai – Attribute
Example-
Insert into customer values (‘&CustID’, ’&Custname’, ’&Custstreet’,
’&Custcity’);
2. Retrieval of Information by Select Command
(i) Syntax-
Select A1,A2.. ,An from r1,r2,..,rn where condition;
Example-
Select CustID,Custname from customer where Custname=’Arun’);

3. Modifying information by Update


Syntax-
Update r set A1=values;
Example-
Update customer set Custname=’babu’ where CustID=101;
4. Deletion of information-
Syntax-
Delete from r where condition;
Example-
Delete from customer where Custname=’Arun’;
5. Truncating a Table: Deletes the records and not the structure of a table.
Syntax:
Truncate table r;
Ex:
Truncate table customer;

Adding Constraints to the table


Constraints in SQL:
 NOT NULL
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
 CHECK
 DEFAULT

NOT NULL Constraints

 The NOT NULL constraint enforces a column to NOT accept NULL values.
 The NOT NULL constraint enforces a field to always contain a value. The following SQL
enforces the "P_Id" column and the "LastName" column to not accept NULL values:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(25)
)

UNIQUE Constraints

 The UNIQUE constraint uniquely identifies each record in a database table.


 The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness
for a column or set of columns.
 Note that you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.

Eg
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:

ALTER TABLE Persons


ADD UNIQUE (P_Id)

CHECK Constraints

 The CHECK constraint is used to limit the value range that can be placed in a column.
 If you define a CHECK constraint on a single column it allows only certain values for this
column.
 The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons"
table is created. The CHECK constraint specifies that the column "P_Id" must only include integers
greater than 0.

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)

To add a CHECK constraint, use the following SQL:

ALTER TABLE Persons


ADD CHECK (P_Id>0)

DEFAULT Constraints

 The DEFAULT constraint is used to insert a default value into a column.


 The following SQL creates a DEFAULT constraint on the "City" column when the
"Persons" table is created:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'chennai'
)

To create a DEFAULT constraint on the "City" column when the table is already created
without city column, use the following SQL:

ALTER TABLE Persons


add (City varchar(25) DEFAULT 'Chennai')

To drop a DEFAULT constraint, use the following SQL:

ALTER TABLE Persons


ALTER City DROP DEFAULT

PRIMARY KEY Constraints

 The PRIMARY KEY constraint uniquely identifies each record in a database table.
 Each table should have a primary key, and each table can have only one primary key.
 The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is
created:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
);

To add a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons


ADD PRIMARY KEY (P_Id)

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

To drop a PRIMARY KEY constraint, use the following SQL:


ALTER TABLE Persons
DROP PRIMARY KEY

FOREIGN KEY Constraints

 The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
 The FOREIGN KEY constraint is used to prevent actions that would destroy link
between tables.
 The FOREIGN KEY constraint also prevents that invalid data is inserted into the foreign
key column, because it has to be one of the values contained in the table it points to
 A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
 Let's illustrate the foreign key with an example. Look at the following two tables:

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 2
4 24562 1

Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons"
table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

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

ALTER TABLE Orders


ADD FOREIGN KEY
REFERENCES Persons(P_Id)

Adding & Deleting the Constraints to the Table using constraint Names:

This example demonstrates how to specify constraints with constraint name during table
creation
create table salary_table (
fiscal_year varchar2(4) constraint nn_sal_year not null,
salary number constraint chk_sal_sal check (salary > 0 ),
fullname varchar2(64) constraint unq_sal_fullname unique,
emp_id varchar2(12) constraint fk_sal_emp_id references emp1(eno));

To disable a constraint, use the alter table command. To enable a disabled constraint, again
use the alter table command. The following examples disables and then re-enables the salary
check condition

alter table salary_table disable constraint chk_salary_salary;


alter table salary_table enable constraint chk_salary_salary;

The following example demonstrates how to drop the constraints using constraint name,
alter table salary_table drop constraint unq_sal_fullname;
alter table salary_table drop constraint chk_sal_sal;
alter table salary_table drop constraint nn_sal_year;
alter table salary_table drop constraint fk_sal_emp_id;

Transaction Control Language(TCL) commands


Transaction Control Language(TCL) commands are used to manage transactions in the database.
These are used to manage the changes made to the data in a table by DML statements. It also allows
statements to be grouped together into logical transactions.
COMMIT command
COMMIT command is used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by these
commands are not permanent, until the current session is closed, the changes made by these
commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax,
COMMIT;
ROLLBACK command
This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and realise that
those changes were not required, then we can use the ROLLBACK command to rollback those
changes, if they were not commited using the COMMIT command.
Following is rollback command's syntax,
ROLLBACK TO savepoint_name;
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that
point whenever required.
Following is savepoint command's syntax,
SAVEPOINT savepoint_name;

In short, using this command we can name the different states of our data in any table and then
rollback to that state using the ROLLBACK command whenever required.
EXAMPLE :

SQL> select * from person;


PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ --------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.
SQL> commit;
Commit complete.

DELETE COMMAND
SQL> delete from person where lastname='Kumar';
2 rows deleted.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------ --------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Hinn Benny Britain 55
5 Prakash Bhaskar Assam 40

SQL> rollback;
Rollback complete.

SQL> select * from person;


PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ -------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.
SQL> savepoint s1;
Savepoint created.
SQL> delete from person;
7 rows deleted.
SQL> select * from person;
no rows selected
SQL> rollback to savepoint s1;
Rollback complete.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------- -------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.

Lab Exercise

1. Create and describe the following tables:

A) NAME: branch
FIELDS DATATYPE
branch_name varchar2(30)
branch_city varchar2(30)
assets number(8,2)

B) NAME: account
FIELDS DATATYPE
account_no varchar2(11)
branch_name varchar2(30)
balance number(8)

C) NAME: customer
FIELD DATATYPE
customer_id varchar2(11)
customer_name varchar2(20)
customer_street varchar2(15)
customer_city varchar2(15)

D) NAME: depositor
FIELD DATATYPE
customer_id varchar2(11)
account_no varchar2(11)

E) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4)
branch_name varchar2(30)
amount number(8,2)

F) NAME: borrower
FIELDS DATATYPE
customer_id varchar2(11)
loan_no varcahr2(4)

2. Describe the structure of all database schemas.

3. Alter the structure of the Database

a. Add a new column ‘account opening date’ in the account table, which is of type Date.
b. Increase the width of the column customer_street in table customer to 20.

4. Add primary keys to all the tables for the specified attributes
A) NAME: branch
FIELDS DATATYPE
branch_name varchar2(30) primary key
branch_city varchar2(30)
assets number(8,2)

B) NAME: account
FIELDS DATATYPE
account_no varchar2(11) primary key
branch_name varchar2(30)
balance number(8)

C) NAME: customer
FIELD DATATYPE
customer_id varchar2(11) primary key
customer_name varchar2(20)
customer_street varchar2(15)
customer_city varchar2(15)
D) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4) primary key
branch_name varchar2(30)
amount number(8,2)

5. Add foreign keys to the following tables for the specified attributes with mentioned
reference table

B) NAME: account
FIELDS DATATYPE
account_no varchar2(11) primary key
branch_name varchar2(30) references branch(branch_name)
balance number(8)

C) NAME: depositor
FIELD DATATYPE
customer_id varchar2(11)references customer (customer_id)
account_no varchar2(11)references account (account_no)

D) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4) primary key
branch_name varchar2(30) references branch(branch_name) (Create constraint
with constraint name)
amount number(8,2)

6. Drop foreign key constraint from loan table


7. Set loan_no attribute of borrower table as foreign key with cascade deletion,
which refers to loan table loan_no column.
8. Add foreign key for the customer_id of borrower table which refers to customer table with
constraint name.

9. Insert the following values into the tables

1. branch :

BRANCH_NAME BRANCH_CITY ASSETS


Perryridge Rye 5000000
Downtown Stamford 1000000
Brighton Paloalto 2500000
Redwood Harrison 1500000
Mianus Pitsfield 4500000
Roundhill Princeton 1500000

2. account :

ACCOUNT_NO BRANCH_NAME BALANCE


019_28_3746 Perryridge 15000
182_73_6091 Downtown 23000
192_83_7465 Brighton 18000
321_12_3123 Redwood 5000
336_66_9999 Mianus 5000
963_96_3963 Roundhill 5000
376_66_9999 Mianus 9000
963_96_3964 Mianus 13000

3. loan :

LOAN BRANCH_NAME AMOUNT


1_11 Roundhill 9000
1_14 Downtown 15000
1_15 Perryridge 15000
1_16 Perryridge 13000
1_17 Downtown 10000
1_23 Redwood 20000
1_93 Mianus 500
4. depositor
CUSTOMER_ID ACCOUNT_NO
c_08 182_73_6091
c_03 192_83_7465
c_05 321_12_3123
c_07 336_66_9999
c_08 963_96_3963
c_02 376_66_9999

5. customer
CUSTOMER_ID CUSTOMER_NAME CUSTOMER_STREET CUSTOMER_CITY
c_01 smith north rye
c_02 turner putnam stamford
c_03 johnson alma palo alto
c_04 curry north rye
c_05 jones main harrisdon
c_06 adoms spring pittsfield
c_07 lindsay park pittsfield
c_08 hayes main harrison
c_09 williams nassau Princeton

6. borrower
CUSTOMER_ID LOAN_NO
c_01 1_11
c_01 1_23
c_03 1_93
c_05 1_17
c_03 1_16
c_05 1_14

10. Create the Database Schema for a Employee-pay scenario

a) employee(emp_id : integer, emp_name: string, address: string, city: string)


b) department(dept_id: integer, dept_name:string)
c) paydetails(emp_id : integer, dept_id: integer, basic: integer, deductions: integer,
additions: integer, DOJ: date)
d) payroll(emp_id : integer, pay_date: date)

For the above schema, perform the following:

11. Create PRIMARY KEY for employee(emp_id) and department(dept_id).


12. Enforce NOT NULL constraint for emp_name.
13. Creates a DEFAULT constraint on the "City" column of employee table.
14. Create NOT NULL for dept_id on department table.
15. Create NOT NULL for basic in pay details.
16. Enforce CHECK constraints for (deductions > 780) on pay details.
EX. 2. Database Querying – Simple queries, Nested queries, Sub queries and
Joins

Aim : To perform data manipulation operations such as Insertion, Deletion, Updating,


Viewing records based on conditions and data definition operation for Altering the structure of
the database.

Simple Queries
1. Create Employee table and insert the values like given below
Emplo First_ Last_ Email Phone_Nu Hire_d Salar Comm Man Depar
yee_id Name Name mber ate y ission_ ager_ tment
pct id _id
101 selva kumar selva@xyz. 9350454613 05- 20000 .20 104 201
com JAN-
1990
102 muthu Kumar muthu@xyz 7250548158 08- 30000 .10 104 201
.com FEB-
1991
103 selva laksh Selva1@xyz 8795458162 40000 104 201
mi .com
104 anu Sree anu@xyz.co 8495188645 22- 60000 .10 104 202
m MAR-
1989
105 bharath Rajan bharathi@x 6548521486 25- 20000 105 202
i yz.com MAR-
1989
106 muthu Selvi 9874525842 26- 80000 .10 105 202
APR-
1994
107 devi Priya devi@xyz.c 8547962140 70000 .20 105 203
om
108 selva Kumar 7589632410 31- 30000 .10 108 203
i SEP-
1990
109 Tamil Arasi tamil@xyz. 8546231189 29- 50000 .50 108 204
com OCT-
1997
110 maha laxmi maha@xyz. 8745962311 70000 .10 108 204
com

2. Create a query to display the last name, hire date, and employee number for each
employee, with employee number appearing first.

SOLUTION:

SQL> select Employee_id,Last_Name,Hire_date from EMPLOYEES_TABLE;

EMPLOYEE_ID LAST_NAME HIRE_DATE


----------- ------------------------- ---------------------
104 Sree 22-MAR-89
105 Rajan 25-MAR-89
108 Kumari 30-SEP-90
101 Kumar 05-JAN-90
102 Kumar 08-FEB-91
103 lakshmi
106 Selvi 26-APR-94
107 Priya
109 Arasi 29-OCT-97
110 laxmi

10 rows selected.

3. Display employees records whose salary is greater than 20000.

SOLUTION:
SQL> select * from EMPLOYEES_TABLE where Salary>20000;

EMPLO FIRS LAST EMAI PHONE_ HIR SALA COMMI MAN DEPA
YEE_ID T_NA _NA L NUMBE E_D RY SSION_ AGE RTM
ME ME R ATE PCT R_ID ENT_
ID
---------------------------------------------------------------------------------------------------------------------
---------------------
104 anu Sree anu@ 8495188 22- 60000 .1 104 202
xyz.co 645 MAR
m -89
108 selva Kuma NULL 7589632 30- 30000 .1 108 203
ri 410 SEP-
90
102 muthu Kuma muthu 7250548 08- 30000 .1 104 201
r @xyz. 158 FEB-
com 91
103 selva laksh Selva1 8795458 40000 104 201
mi @xyz. 162
com
106 muthu Selvi NULL 9874525 26- 80000 .1 105 202
842 APR-
94
107 devi Priya devi@ 8547962 70000 .2 105 203
xyz.co 140
m
109 Tamil Arasi tamil 8542631 29- 50000 .5 108 204
@xyz. 189 OCT-
com 97
110 maha laxmi maha 8754962 70000 .1 108 204
@xyz. 311
com
8 rows selected.
4. Create a query to display the last name and salary of employees whose salary is not in
the range of 2000 and 80000. (hints: not between )

SOLUTION:
SQL> select Last_Name,Salary from EMPLOYEES_TABLE where Salary not between 20000
and 60000;

LAST_NAME SALARY
------------------------- ----------
Selvi 80000
Priya 70000
laxmi 70000

5. Display the employee last name, job ID, and start date of employees hired between 01-
MAR-1989 and May 1,1995. (hints: between)

SOLUTION:
SQL> select Last_Name,Employee_id,Hire_date from EMPLOYEES_TABLE where Hire_date
between '01-MAR-1989' and '01-MAY-1995';
LAST_NAME EMPLOYEE_ID HIRE_DATE
------------------------- ----------- -----------------
Sree 104 22-MAR-89
Rajan 105 25-MAR-89
Kumari 108 30-SEP-90
Kumar 101 05-JAN-90
Kumar 102 08-FEB-91
Selvi 106 26-APR-94
6 rows selected.
8. Display the last name and salary of all employees who earn between 60000 and 80000
and are in departments 201 and 204 .

(hints: between, in)

SOLUTION:
SQL> select Last_Name,Salary from EMPLOYEES_TABLE where Salary between 60000 and
80000 and Department_id in (201,204);

LAST_NAME SALARY
------------------------- ----------
laxmi 70000

9. Display the last name and hire date of every employee who was hired in 1994.
(hints: like)
SOLUTION:
SQL> select Last_Name,Hire_date from EMPLOYEES_TABLE where Hire_date like '%94';
LAST_NAME HIRE_DATE
------------------------- ---------
Selvi 26-APR-94
10. Display employee details who does not have mail-id.
SOLUTION:
SQL> select * from EMPLOYEES_TABLE where email=’NULL’;
No rows selected

SubQueries
A subquery is a SQL query nested inside a larger query.

 A subquery may occur in :


 - A SELECT clause
 - A FROM clause
 - A WHERE clause
 The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside
another subquery.
 A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
 You can use the comparison operators, such as >, <, or =. The comparison operator can also be a
multiple-row operator, such as IN, ANY, or ALL.
 A subquery is also called an inner query or inner select, while the statement containing a subquery is
also called an outer query or outer select.
 The inner query executes first before its parent query so that the results of an inner query can be
passed to the outer query.
You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to
perform the following tasks:

 Compare an expression to the result of the query.


 Determine if an expression is included in the results of the query.
 Check whether the query selects any rows.

Syntax :

 The subquery (inner query) executes once before the main query (outer query) executes.
 The main query (outer query) use the subquery result.

SQL Subqueries Example :


In this section, you will learn the requirements of using subqueries. We have the
following two tables 'student' and 'marks' with common field 'StudentID'.

student marks
Now we want to write a query to identify all students who get better marks than that of
the student who's StudentID is 'V002', but we do not know the marks of 'V002'.
- To solve the problem, we require two queries. One query returns the marks (stored in
Total_marks field) of 'V002' and a second query identifies the students who get better
marks than the result of the first query.
First query:
SELECT *
FROM `marks`
WHERE studentid = 'V002';
Copy
Query result:

The result of the query is 80.


- Using the result of this query, here we have written another query to identify the
students who get better marks than 80. Here is the query :
Second query:
SELECT a.studentid, a.name, b.total_marks
FROM student a, marks b
WHERE a.studentid = b.studentid
AND b.total_marks >80;
Copy
Query result:

Above two queries identified students who get the better number than the student who's
StudentID is 'V002' (Abhay).
You can combine the above two queries by placing one query inside the other. The
subquery (also called the 'inner query') is the query inside the parentheses. See the
following code and query result :
SQL Code:
SELECT a.studentid, a.name, b.total_marks
FROM student a, marks b
WHERE a.studentid = b.studentid AND b.total_marks >
(SELECT total_marks
FROM marks
WHERE studentid = 'V002');
Copy
Query result:

Pictorial Presentation of SQL Subquery:


Subqueries: General Rules
A subquery SELECT statement is almost similar to the SELECT statement and it is used
to begin a regular or outer query. Here is the syntax of a subquery:
Syntax:
(SELECT [DISTINCT] subquery_select_argument
FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY aggregate_expression [, aggregate_expression] ...]
[HAVING search_conditions])

Subqueries: Guidelines
There are some guidelines to consider when using subqueries :

 A subquery must be enclosed in parentheses.


 A subquery must be placed on the right side of the comparison operator.
 Subqueries cannot manipulate their results internally, therefore ORDER BY clause cannot be added
into a subquery. You can use an ORDER BY clause in the main SELECT statement (outer query) which will
be the last clause.
 Use single-row operators with single-row subqueries.
 If a subquery (inner query) returns a null value to the outer query, the outer query will not return any
rows when using certain comparison operators in a WHERE clause.

Type of Subqueries

 Single row subquery : Returns zero or one row.


 Multiple row subquery : Returns one or more rows.
 Multiple column subqueries : Returns one or more columns.
 Correlated subqueries : Reference one or more columns in the outer SQL statement. The subquery is
known as a correlated subquery because the subquery is related to the outer SQL statement.
 Nested subqueries : Subqueries are placed within another subquery.
In the next session, we have thoroughly discussed the above topics. Apart from the above
type of subqueries, you can use a subquery inside INSERT, UPDATE and DELETE
statement. Here is a brief discussion :

Subqueries with INSERT statement


INSERT statement can be used with subqueries. Here are the syntax and an example of
subqueries using INSERT statement.
Syntax:
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ];
If we want to insert those orders from 'orders' table which have the advance_amount 2000
or 5000 into 'neworder' table the following SQL can be used:

SQL Code:
INSERT INTO neworder
SELECT * FROM orders
WHERE advance_amount in(2000,5000);
Output:
2 rows inserted

Subqueries with UPDATE statement


In a UPDATE statement, you can set new column value equal to the result returned by a
single row subquery. Here are the syntax and an example of subqueries using UPDATE
statement.
Syntax:
UPDATE table SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
If we want to update that ord_date in 'neworder' table with '15-JAN-10' which have the
difference of ord_amount and advance_amount is less than the minimum ord_amount of
'orders' table the following SQL can be used:

SQL Code:
UPDATE neworder
SET ord_date='15-JAN-10'
WHERE ord_amount-advance_amount<
(SELECT MIN(ord_amount) FROM orders);
Output:
7 rows updated

Subqueries with DELETE statement


DELETE statement can be used with subqueries. Here are the syntax and an example of
subqueries using DELETE statement.
Syntax:
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
If we want to delete those orders from 'neworder' table which advance_amount are less
than the maximum advance_amount of 'orders' table, the following SQL can be used:

SQL Code:
DELETE FROM neworder
WHERE advance_amount<
(SELECT MAX(advance_amount) FROM orders);
Output:
34 rows deleted.
Correlated Subqueries

SQL Correlated Subqueries are used to select data from a table referenced in the outer
query. The subquery is known as a correlated because the subquery is related to the outer
query. In this type of queries, a table alias (also called a correlation name) must be used
to specify which table reference is to be used.
The alias is the pet name of a table which is brought about by putting directly after the
table name in the FROM clause. This is suitable when anybody wants to obtain
information from two separate tables.

Example: SQL Correlated Subqueries

The following correlated subqueries retrive ord_num, ord_amount, cust_code and


agent_code from the table orders ( 'a' and 'b' are the aliases of orders and agents table)
with following conditions -

the agent_code of orders table must be the same agent_code of agents table and
agent_name of agents table must be Alex,the following SQL statement can be used:

SQL Code:
SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code
FROM orders a
WHERE a.agent_code=(
SELECT b.agent_code
FROM agents b WHERE b.agent_name='Alex');
Output:

ORD_NUM ORD_AMOUNT CUST_CODE AGENT_CODE


---------- ---------- ---------- ----------
200127 2500 C00015 A003
200100 1000 C00015 A003
The inner of the above query returns the 'agent_code' A003.
The simplified form of above code is:
SQL Code:
SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code
FROM orders a
WHERE a.agent_code='A003';
Using EXISTS with a Correlated Subquery

We have already used the EXISTS operator to check the existence of a result of a
subquery. EXISTS operator can be used in correlated subqueries also. Using EXISTS the
following query display the employee_id, manager_id, first_name and last_name of those
employees who manage other employees.
SQL Code:
SELECT employee_id, manager_id, first_name, last_name

FROM employees a

WHERE EXISTS

(SELECT employee_id

FROM employees b

WHERE b.manager_id = a.employee_id)

Output:

EMPLOYEE_ID MANAGER_ID FIRST_NAME LAST_NAME


----------- ---------- -------------------- ---------------
100 Steven King
101 100 Neena Kochhar
102 100 Lex De Haan
103 102 Alexander Hunold
108 101 Nancy Greenberg
114 100 Den Raphaely
120 100 Matthew Weiss
121 100 Adam Fripp
122 100 Payam Kaufling
123 100 Shanta Vollman
124 100 Kevin Mourgos
145 100 John Russell
146 100 Karen Partners
147 100 Alberto Errazuriz
148 100 Gerald Cambrault
149 100 Eleni Zlotkey
201 100 Michael Hartstein
205 101 Shelley Higgins
Using NOT EXISTS with a Correlated Subquery
NOT EXISTS is logically opposite of EXISTS operator. NOT EXISTS is used when we
need to check if rows do not exist in the results returned by a subquery. Using NOT
EXISTS the following query display the employee_id, manager_id, first_name and
last_name of those employees who have no manager status. This query is opposite to the
previous one.
SQL Code:
SELECT employee_id, manager_id, first_name, last_name

FROM employees a

WHERE NOT EXISTS

(SELECT employee_id

FROM employees b

WHERE b.manager_id = a.employee_id);

Output:

EMPLOYEE_ID MANAGER_ID FIRST_NAME LAST_NAME


----------- ---------- -------------------- --------------
104 103 Bruce Ernst
105 103 David Austin
106 103 Valli Pataballa
107 103 Diana Lorentz
109 108 Daniel Faviet
110 108 John Chen
111 108 Ismael Sciarra
112 108 Jose Manuel Urman
113 108 Luis Popp
115 114 Alexander Khoo
116 114 Shelli Baida
117 114 Sigal Tobias
118 114 Guy Himuro
119 114 Karen Colmenares
125 120 Julia Nayer
126 120 Irene Mikkilineni
127 120 James Landry
128 120 Steven Markle
129 121 Laura Bissot
130 121 Mozhe Atkinson
131 121 James Marlow
........
.......
Create a table for the following schema using attributes from EMPLOYEES table

Emp_training (Employee_id,First_Name,email,Phone_number); and display its structure.


SOLUTION:
SQL> create table Emp_training as(select Employee_id,First_Name,Email,Phone_Number from
EMPLOYEES_TABLE);
Table created.
SQL> desc Emp_training;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPLOYEE_ID NUMBER(6)
FIRST_NAME NOT NULL VARCHAR2(20)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER NOT NULL VARCHAR2(10)
1. Display the content of emp_training table

SOLUTION:
SQL> select * from emp_training;

EMPLOYEE_ID FIRST_NAME EMAIL PHONE_NUMB


---------------------------------------------------------------------------------
104 anu anu@xyz.com 9876543212
105 bharathi bharathi@xyz.com 9087093245
108 selva NULL 9345678987
101 selva selva@xyz.com 9345986723
102 muthu muthu@xyz.com 9345091276
103 selva selval@xyz.com 9876543212
106 muthu NULL 8987654321
107 devi devi@xyz.com 9809876543
109 tamil tamil@xyz.com 7898098765
110 maha maha@xyz.com 9809231456

10 rows selected.

2. Copy records from the EMPLOYEES table whose salary is less than 60000 in to
Emp_training2 relation.
SOLUTION:
SQL> create table Emp_training2 as(select Employee_id,First_Name,Email,Phone_Number
from EMPLOYEES_TABLE where salary<60000);
Table created.
SQL> select * from emptraning2;
EMPID FNAME EMAILID PHNO
---------- -------------------- ---------------------------------------
105 bharathi bharathi@xyz.com 9442952654
108 selva NULL 9086543489
101 SELVA selva@xyz.com 9346790056
102 muthu muthu@xyz.com 9876545787
109 tamil tamil@xyz.com 9887654456

5 rows selected.

JOIN

SQL joins are used to fetch data from two or more tables, based on conditions between
tables.
There are various type of joins. Like
Equi-Joins
Self-Join
Outer-Join
Cross-Join
Exercise:
1. Fetch records from two tables emp, dept where deptno of employee is equal to dept
no of dept.
SELECT * FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO;
2. Suppose there are two tables category and product.Both table contains category_id.
We want to fetch the records where both tables contain same category_id .
SELECT * FROM CATEGORIES C ,PRODUCTS P where P.CATEGORYID = C.CATEGORYID;
Another way to write it,like
SELECT * FROM CATEGORIES C INNER JOIN PRODUCTS P ON P.CATEGORYID =
C.CATEGORYID;
3. There are two table emp and dept. We want to fetch records of emp where deptno
between 10 and 20.
SELECT * FROM EMP E, DEPT D WHERE D.DEPTNO BETWEEN 10 AND 20;
4. In Emp table there are two columns empno and mgr. Fetch the records where
empno and mgr are same.
SELECT * FROM EMP E1, EMP E2 WHERE E1.EMPNO=E2.MGR;
5. In Employee_details table retrieve the record whose city are same.
SELECT * FROM EMPLOYEE_DETAILS E1,EMPLOYEE_DETAILS E2 WHERE
E1.CITY=E2.CITY;
6. Select an employee's department where they have not been assigned to a
department.
SELECT * FROM EMP LEFT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;
(OR)
SELECT * FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO(+);
7. List dept no., Dept name for all the departments in which there are no employees in
the department.
SELECT * FROM EMP RIGHT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;
(OR)
SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO;
8. Retrieve each employee who is in a department and each department that has an
employee and also each employee who is not part of a department and each department
which doesn't have an employee.
SELECT * FROM EMP FULL OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;
(OR)
SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO(+);

Lab Exercise Questions

Update, Delete & Retrieval operation-

a. Modify the balance attribute alone such that it decreases the amount by 10% for the
account table
b. Delete all the account tuples in the ‘Redwood’ branch.
c. Delete all loans with loan amounts between 15000 to 20000.
d. Find the names of all branches in the loan relation.
e. Display all the Customer names whose come from either pittsfield or stamford.
f. Find all loan numbers for loans made at the ‘Perryridge’ branch with loan amount greater
than 1200.
g. Find loan numbers of those loans with loan amount between 10000 and 20000.
h. Display the customer name in alphabetical order
i. Display all the customer names ordered by customer city
j. Give a count of how many account holds are in each branch.

You might also like