Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

Government Engineering College, Patan

Computer Science and Engineering Department


Database Management System (3130703)

INDEX
SR. EXPT. PAGE NO. OF
TITLE
NO. NO. NO. PAGES
1 - Table of contents 01 01
1 - Revision Record Sheet 02 01
2 - Control copy holder 03 01
3 - General Instructions 04 01
4 - List of experiments - -
5 01 To study DDL-create and DML-insert commands. 05 07

6 02 To study various Data Constraints. 12 12


To study various data manipulation (delete,
update etc.) commands, sorting concepts, Range 24 08
7 03
searching and arithmetic, logical and relational
operators.
To study LIKE predicate, dual table concept and 31 09
8 04
various aggregation functions.
9 05 To study Single-row functions. 39 01

10 06 To Display data from Multiple Tables (join). 40 03


To apply the concept of Aggregating Data using 44 05
11 07
Group functions.
12 08 To solve queries using the concept of sub query. 49 08
13 09 To solve queries by manipulating Data. 57 01
14 10 To apply the concept of security and privileges. 58 04
15 11 To study Transaction control commands. 62 01

1
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

REVISION RECORD SHEET

SR.NO. EXPERIMENT NAME OF EXPERIMENT DATE OF NO.


NO. REVISION OF
PAGES
1 01 To study DDL-create and DML-insert
commands.
2 02 To study various Data Constraints.
3 03 To study various data manipulation
(delete, update etc.) commands,
sorting concepts, Range searching and
arithmetic, logical and relational
operators.
4 04 To study LIKE predicate, dual table
concept and various aggregation
functions.
5 05 To study Single-row functions.
6 06 To Display data from Multiple Tables
(join).
7 07 To apply the concept of Aggregating
Data using Group functions.
8 08 To solve queries using the concept of
sub query.
9 09 To solve queries by manipulating Data.
10 10 To apply the concept of security and
privileges.
11 11 To study Transaction control
commands.
12 12 Sample Program to learn PL/SQL

2
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

CONTROL COPY HOLDER

SR.NO EXPT. CONTROL COPY REVISION ISSUE


NO NO. DATE
1 Management representative
2 Head of the Department
3 Course Coordinator

3
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

GENERAL INSTRUCTIONS

1. Start computer only after obtaining permission of the concerned


instructor/teacher.
2. Do not bring the bags inside laboratory.
3. Observe safety precautions during the lab hours.
4. Obtain the required instruments/ manuals & other required material from the
lab teacher & return it at the end of the practical.
5. At the end of the lab, shut-down the computer, switch off power supply and
put chairs properly.

4
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 1

OBJECTIVE: To study various DDL commands and DML-insert command.

Theory:

 Structured Query Language (SQL) is a language that provides an interface to


relation database systems.

 Components of SQL:

(1) Data Definition Language (DDL): It is a set of SQL commands used to create,
modify and delete database structures and not the data. These commands are
auto commit. The examples are – CREATE, ALTER (modify), DROP (remove
table), TRUNCATE (remove all rows), COMMENT, RENAME.

(2) Data Manipulation Language (DML): It is a set of SQL commands that allows
changing data within database. These commands are not auto commit. The
examples are – INSERT, UPDATE, DELETE etc.

(3) Data Control Language (DCL): It is a set of SQL commands that control access
to data and to the database. The examples are –COMMIT, SAVEPOINT,
ROLLBACK, SET TRANSACTION, GRANT, REVOKE etc.

(4) Data Query Language (DQL): It is a component of SQL statement that allows
getting data from the database and imposing ordering upon it. The example is
SELECT.

 Basic SQL Data types:

(1) Char(size): Used to store character strings values of fixed length. The size in
determines the maximum number of characters that field can store. E.g. Name
char(20).

(2) Varchar2(size): Used to store variable length alphanumeric data.

(3) Number(P, S): Used to store integer or float numbers. P denotes precession & S
denotes scale. E.g Salary number(6,2) will allow 6 digit long salary with 2 digit
after decimal.

 Commands:

DDL commands:

5
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

1. Create Table Command: - it defines each column of the table uniquely. Each
column has minimum of three attributes, a name , data type and size.

Syntax:
CREATE TABLE <TABLE NAME> (<COL1> <DATATYPE>(<SIZE>),<COL2>
<DATATYPE><SIZE>));

Ex:
SQL> create table emp(empno number(4) , ename varchar2(10));
O/P: Table created.

Syntax for describing the table:

DESC <TABLE NAME>;

Ex:
SQL> desc emp;
O/P:
Name Null? Type
----------------------------------------------------- -------- ------------------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)

2. Modifying the structure of tables.

a) Add new columns

Syntax:
ALTER TABLE <TABLENAME> ADD(<NEW
COL><DATATYPE(SIZE),<NEW COL>DATATYPE(SIZE));

Ex:
SQL> alter table emp add(sal number(7,2));
O/P: Table altered.

SQL> desc emp;

O/P:
Name Null? Type
----------------------------------------------------- -------- ------------------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
SAL NUMBER(7,2)

6
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

b) Dropping a column from a table.

Syntax:
ALTER TABLE <TABLENAME> DROP COLUMN <COL>;

Ex:
SQL> alter table emp drop column sal;
O/P: Table altered.

SQL> desc emp;


O/P:
Name Null? Type
----------------------------------------------------- -------- ------------------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)

c) Modifying existing columns.

Syntax:
ALTER TABLE <TABLENAME> MODIFY (<COL>
<NEWDATATYPE>(<NEWSIZE>));

Ex:
SQL> alter table emp modify(ename varchar2(15));
O/P: Table altered.

SQL> desc emp;


O/P:
Name Null? Type
----------------------------------------------------- -------- ------------------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(15)

3. Renaming the tables

Syntax:
RENAME <OLDTABLE> TO <NEW TABLE>;

Ex:
SQL> rename emp to emp1;

SQL> desc emp1;


O/P:
Name Null? Type
----------------------------------------------------- -------- ------------------------------

7
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

EMPNO NUMBER(4)
ENAME VARCHAR2(15)

4. Truncating the tables.

Syntax:
TRUNCATE TABLE <TABLENAME>;

Ex:
SQL> truncate table emp1;

5. Destroying tables.

Syntax:
DROP TABLE <TABLENAME>;

Ex:
SQL> drop table emp;

DML-insert command:

6. Inserting Data into Tables: - once a table is created the most natural thing to do
is load this table with data to be manipulated later.

Syntax:
INSERT INTO <TABLENAME> (<COL1>,<COL2>) VALUES(<EXP>,<EXP>);

Ex:
SQL>insert into emp values(101, ‘Rakesh’);
O/P: 1 row created.

DQL Commands:

7. Viewing data in the tables: - Once data has been inserted into a table, the next
most logical operation would be to view what has been inserted.

a) All rows and all columns

Syntax:
SELECT * FROM TABLENAME;

8
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

8. Filtering table data: - While viewing data from a table, it is rare that all the data
from table will be required each time. Hence, SQL must give us a method of filtering
out data that is not required data.

a) Selected columns and all rows:

Syntax:
SELECT <COL1>,<COL2> FROM <TABLENAME>;

b) Selected rows and all columns:

Syntax:
SELECT * FROM <TABLENAME> WHERE <CONDITION>;

c) Selected columns and selected rows

Syntax:
SELECT <COL1>,<COL2> FROM <TABLENAME> WHERE<CONDITION>;

 PRACTICAL SET

Create tables according to the following definition.


1. CREATE TABLE DEPOSIT (ACTNO VARCHAR2(5) ,CNAME
VARCHAR2(18) , BNAME VARCHAR2(18) , AMOUNT NUMBER(8,2)
,ADATE DATE);
2. CREATE TABLE BRANCH(BNAME VARCHAR2(18),CITY VARCHAR2(18));
3. CREATE TABLE CUSTOMERS(CNAME VARCHAR2(19) ,CITY
VARCHAR2(18));
4. CREATE TABLE BORROW(LOANNO VARCHAR2(5), CNAME
VARCHAR2(18), BNAME VARCHAR2(18), AMOUNT NUMBER (8,2));

DEPOSIT
ACTNO CNAME BNAME AMOUNT ADATE
100 ANIL VRCE 1000.00 1-MAR-95
101 SUNIL AJNI 5000.00 4-JAN-96
102 MEHUL KAROLBAGH 3500.00 17-NOV-95
104 MADHURI CHANDI 1200.00 17-DEC-95
105 PRMOD M.G.ROAD 3000.00 27-MAR-96
106 SANDIP ANDHERI 2000.00 31-MAR-96
107 SHIVANI VIRAR 1000.00 5-SEP-95
108 KRANTI NEHRU PLACE 5000.00 2-JUL-95
109 MINU POWAI 7000.00 10-AUG-95

BRANCH
BNAME CITY
VRCE NAGPUR

9
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

AJNI NAGPUR
KAROLBAGH DELHI
CHANDI DELHI
DHARAMPETH NAGPUR
M.G.ROAD BANGLORE
ANDHERI BOMBAY
VIRAR BOMBAY
NEHRU PLACE DELHI
POWAI BOMBAY

CUSTOMERS

CNAME CITY
ANIL CALCUTTA
SUNIL DELHI
MEHUL BARODA
MANDAR PATNA
MADHURI NAGPUR
PRAMOD NAGPUR
SANDIP SURAT
SHIVANI BOMBAY
KRANTI BOMBAY
NAREN BOMBAY

BORROW
LOANNO CNAME BNAME AMOUNT
201 ANIL VRCE 1000.00
206 MEHUL AJNI 5000.00
311 SUNIL DHARAMPETH 3000.00
321 MADHURI ANDHERI 2000.00
375 PRMOD VIRAR 8000.00
481 KRANTI NEHRU PLACE 3000.00

From the above given tables perform the following queries:

1. Describe tables deposit and branch.


2. Describe tables borrow and customers.
3. List all data from table DEPOSIT.
4. List all data from table BORROW.
5. List all data from table CUSTOMERS.
6. List all data from table BRANCH.
7. Display all the table names currently in database.
8. Give account no and amount of depositors.
9. Give borrower details having branch name ‘Andheri’.
10. Give name of depositors having amount greater than 4000.

10
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

11. Give name of customers who opened account after date '1-12-96'.
12. Display customer names at branch ‘Virar’
13. Display all the branches in city Bombay.
14. List all the customers from city ‘Nagpur’.
15. Display the borrower detail in branch ‘Ajni’.
16. Display distinct cities from branch table.
17. Add contact_no. field in table customers with data type varchar2 and size 15.
18. Change the data type of contact_no field to number and size to 20.
19. Drop contact no. field in table customers

11
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 2

OBJECTIVE: To study various Data Constraints.

Theory:

CONSTRAINTS

Constraints are part of the table definition that limits and restriction on the value
entered into its columns.

TYPES OF CONSTRAINTS:
1) Primary key
2) Foreign key/references
3) Check
4) Unique
5) Not null
6) Null
7) Default

CONSTRAINTS CAN BE CREATED IN THREE WAYS:


1) Column level constraints
2) Table level constraints
3) Using DDL statements-alter table command

1. Primary key: is used to uniquely identify a tuple in table. Can’t have null value.
a) At column level

Syntax:
CREATE TABLE <TABLE NAME>(<COL1><DATATYPE>(<SIZE>) PRIMARY
KEY, <COL2> <DATATYPE>(<SIZE>),……);

Ex:
SQL> create table std1(idno number(1) primary key, name varchar(10));
Table created.

SQL> insert into std1 values(&idno,'&name');


Enter value for idno: 1
Enter value for name: abc
old 1: insert into std1 values(&idno,'&name')
new 1: insert into std1 values(1,'abc')
1 row created.

SQL> /
Enter value for idno: 1
Enter value for name: xyz

12
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

old 1: insert into std1 values(&idno,'&name')


new 1: insert into std1 values(1,'xyz')
insert into std1 values(1,'xyz')
*
ERROR at line 1:
ORA-00001: unique constraint (DINESH.SYS_C008972) violated

b) At Table level

Syntax:
CREATE TABLE <TABLE NAME>(<COL1><DATATYPE>(<SIZE>), <COL2>
<DATATYPE>(<SIZE>), …, PRIMARY KEY(<COL1>,<COL2>));

Ex:
SQL> create table st1(idno number(1),name varchar(10), primary key(idno));
Table created.

SQL> insert into st1 values(&idno,'&name');


Enter value for idno: 1
Enter value for name: abc
old 1: insert into st1 values(&idno,'&name')
new 1: insert into st1 values(1,'abc')
1 row created.

SQL> /
Enter value for idno: 1
Enter value for name: def
old 1: insert into st1 values(&idno,'&name')
new 1: insert into st1 values(1,'def')
insert into st1 values(1,'def')
*
ERROR at line 1:
ORA-00001: unique constraint (DINESH.SYS_C008973) violated

c) Composite Primary Key

SQL> create table p_s(idno number(1) primary key, name varchar(10) primary
key);

create table p_s(idno number(1) primary key, name varchar(10) primary key)
*
ERROR at line 1:
ORA-02260: table can have only one primary key

13
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> create table p_s1(idno number(1), name varchar(10), primary


key(idno,name));
Table created.

SQL> desc p_s1


Name Null? Type
------------------------------- -------- ----
IDNO NOT NULL NUMBER(1)
NAME NOT NULL VARCHAR2(10)

SQL> insert into p_s1 values(&idno,'&name');


Enter value for idno: 1
Enter value for name: abc
old 1: insert into p_s1 values(&idno,'&name')
new 1: insert into p_s1 values(1,'abc')
1 row created.

SQL> /
Enter value for idno: 1
Enter value for name: def
old 1: insert into p_s1 values(&idno,'&name')
new 1: insert into p_s1 values(1,'def')
1 row created.

SQL> /
Enter value for idno: 1
Enter value for name: abc
old 1: insert into p_s1 values(&idno,'&name')
new 1: insert into p_s1 values(1,'abc')
insert into p_s1 values(1,'abc')
*
ERROR at line 1:
ORA-00001: unique constraint (DINESH.SYS_C008976) violated

->at column level CPK is not possible

2. Foreign key/references: is used create referential integrity with other table.

a) Column level
SQL> create table f_std1(idno number(1) references std1,cpi number(4,2));
Table created.

SQL> insert into f_std1 values(&idno,&cpi);


Enter value for idno: 1
Enter value for cpi: 6.89
old 1: insert into f_std1 values(&idno,&cpi)

14
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

new 1: insert into f_std1 values(1,6.89)


1 row created.

SQL> /
Enter value for idno: 3
Enter value for cpi: 3.4
old 1: insert into f_std1 values(&idno,&cpi)
new 1: insert into f_std1 values(3,3.4)
insert into f_std1 values(3,3.4)
*
ERROR at line 1:
ORA-02291: integrity constraint (DINESH.SYS_C008974) violated - parent key
not found.

b) Table level
SQL> create table f_st1(idno number(1),cpi number(4,2), foreign key(idno)
references st1(idno));

Table created.

3. Check

a) Column level

SQL> create table std1(idno number(1),name varchar(10),cpi number(4,2)

check (cpi>=0.0 and cpi<=10.0));


Table created.

SQL> create table std1(idno char(2) check(idno like 'i%'),name varchar(10),


cpi number(4,2));
Table created.

SQL> insert into std1 values('&idno','&name',&cpi);


Enter value for idno: i1
Enter value for name: abc
Enter value for cpi: 3.6
old 1: insert into std1 values('&idno','&name',&cpi)
new 1: insert into std1 values('i1','abc',3.6)
1 row created.

SQL> /
Enter value for idno: 2
Enter value for name: def
Enter value for cpi: 5.9

15
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

old 1: insert into std1 values('&idno','&name',&cpi)


new 1: insert into std1 values('2','def',5.9)
insert into std1 values('2','def',5.9)
*
ERROR at line 1:
ORA-02290: check constraint (DINESH.SYS_C008989) violated

b) Table level

SQL> create table std1(idno number(1),name varchar(10),cpi


number(4,2),constraint ck check(cpi>=0.0 and cpi<=10.0));

Table created.

SQL> create table std1(idno char(2),name varchar(10),cpi number(4,2),


check(idno like 'i%'));
Table created.

4. Unique

a) Column Level

SQL> drop table f_std1;


Table dropped.

SQL> drop table std1;


Table dropped.

SQL> create table std1(idno number(1) unique,name varchar(10));


Table created.

SQL> insert into std1 values(&idno,'&name');


Enter value for idno: 1
Enter value for name: abc
old 1: insert into std1 values(&idno,'&name')
new 1: insert into std1 values(1,'abc')
1 row created.

SQL> /
Enter value for idno: 1
Enter value for name: def
old 1: insert into std1 values(&idno,'&name')
new 1: insert into std1 values(1,'def')
insert into std1 values(1,'def')
*
ERROR at line 1:

16
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

ORA-00001: unique constraint (DINESH.SYS_C008981) violated

SQL> insert into std1(name) values('def');


1 row created.

SQL> select * from std1;

IDNO NAME
---------- ----------
1 abc
def

b) Table Level

SQL> drop table std1;


Table dropped.
SQL> create table std1(idno number(1),name varchar(10),unique(idno));
Table created.

->more than one unique key is possible

SQL> create table std1(idno number(1),name


varchar(10),unique(idno),unique(name));
Table created.

5. Not null: is used to disallow null values for attribute.

SQL>CREATE TABLE EMP13


(EMPNO NUMBER(4),
ENAME VARCHAR2(20) NOT NULL,
DESIGN VARCHAR2(20),
SAL NUMBER(3));

6. Default: is used to set some default value for attribute.

SQL>CREATE TABLE PERSONS


(P_ID NUMBER(4),
LASTNAME VARCHAR(255),
FIRSTNAME VARCHAR(255),
ADDRESS VARCHAR(255),
CITY VARCHAR(255) DEFAULT 'Mumbai'
)

17
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

 PRACTICAL SET

1. Demonstrate the use of PRIMARY KEY constraint at column level and write
your comments about the result.
2. Demonstrate the use of PRIMARY KEY constraint at table level and write
your comments about the result.
3. Demonstrate the use of FOREIGN KEY constraint at column level and write
your comments about the result.
4. Demonstrate the use of FOREIGN KEY constraint at table level and write
your comments about the result.
5. Demonstrate the use of FOREIGN KEY constraint with ON DELETE
CASCADE option and write your comments about the result.
6. Demonstrate the use of FOREIGN KEY constraint with ON DELETE SET
NULL option and write your comments about the result.
7. Demonstrate the use of UNIQUE constraint at column level and write your
comments about the result.
8. Demonstrate the use of UNIQUE constraint at table level and write your
comments about the result.
9. Demonstrate the use of NOT NULL constraint and write your comments about
the result.
10. Demonstrate the use of CHECK constraint and write your comments about
the result.
11. Demonstrate the use of DEFAULT constraint and write your comments about
the result.
12. Demonstrate the addition of primary key constraint in an already existing
table.
13. Demonstrate the deletion of primary key constraint.
14. Demonstrate assigning user defined names to a constraints.
15. Demonstrate the addition of constraint other than primary key in an already
existing table.
16. Demonstrate the deletion of constraint other than primary key.

Create the below given tables and insert the data accordingly.

1. Create Table Job (job_id, job_title, min_sal, max_sal)

COLUMN NAME DATA TYPE Constraint


job_id Varchar2(15) Primary key

18
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

job_title Varchar2(30)
min_sal Number(7,2)
max_sal Number(7,2)

2. Create table Branch (branch_no, bname,city)

COLUMN NAME DATA TYPE Constraint


branch_no Varchar2(3) Primary key
bname Varchar2(18)
City Varchar2(18)

3. Create table Employee (emp_no, emp_name, emp_sal, emp_comm,


dept_no)

COLUMN NAME DATA TYPE Constraint


emp_no Number(3) Primary key
emp_name Varchar2(30)
job_id Varchar2(15) Foreign key
emp_sal Number(8,2)
emp_comm Number(6,1)
branch_no Number(3) Foreign key
dept_no Number(3)

4. Create table deposit(a_no,cname,bname,amount,a_date)

COLUMN NAME DATA TYPE Constraint


a_no Varchar2(5) Primary key
Cname Varchar2(15)
branch_no Varchar2(3) Foreign key
Amount Number(7,2)

19
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

a_date Date

5. Create table borrow (loanno,cname,bname,amount)

COLUMN NAME DATA TYPE Constraint


Loanno Varchar2(5) Primary key
Cname Varchar2(3)
branch_no Varchar2(3) Foreign key
Amount Number(7,2)

Insert following values in the table job.

job_id job_name min_sal max_sal


IT_PROG Programmer 4000 10000
MK_MGR Marketing 9000 15000
manager
FI_MGR Finance manager 8200 12000
FI_ACC Account 4200 9000
LEC Lecturer 6000 17000
COMP_OP Computer 1500 3000
Operator

Insert following values in the table branch.

branch_no bname City


B1 VRCE NAGPUR
B2 AJNI NAGPUR
B3 KAROLBAGH DELHI
B4 CHANDI DELHI
B5 DHARAMPETH NAGPUR
B6 M.G.ROAD BANGLORE
B7 ANDHERI BOMBAY
B8 VIRAR BOMBAY
B9 NEHRU PLACE DELHI
B10 POWAI BOMBAY

Insert following values in the table Employee.

20
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

emp_no emp_name Job_id emp_sal emp_com branch_n dept _no


m o
101 Smith FI_ACC 5000 B1 20
102 Snehal MK_MGR 11000 24,500 B9 25
103 Adama LEC 9000 0 B5 20
104 Aman FI_MGR 10000 500 B8 15
105 Anita MK_MGR 13000 50,000 B2 10
106 Sneha COMP_OP 8500 B5 10
107 Anamika IT_PROG 2975 B7 30

Insert following values in the table deposit

a_no cname branch_no amount date

101 Anil B7 7000 01-jan-06

102 Sunil B3 5000 15-jul-06

103 Jay B2 6500 12-mar-06

104 Vijay B7 8000 17-sep-06

105 Keyur B5 7500 19-nov-06

106 Mayor B9 5500 21-dec-06

Insert following values in the table borrow

loanno Cname branch_no amount


201 Anil B1 1000.00
206 Mehul B2 5000.00
311 Sunil B5 3000.00
321 Madhuri B7 2000.00
375 Prmod B8 8000.00
481 Kranti B9 3000.00

21
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 3

OBJECTIVE: To study various data manipulation (delete, update etc.) commands,


sorting concepts, Range searching and arithmetic, logical and
relational operators.
Commands:

1. DML Delete command

a) Remove all rows

Syntax:
DELETE FROM <TABLENAME>;

Ex:
SQL> delete from emp;

b) Removal of a specified row/s

Syntax:
DELETE FROM <TABLENAME> WHERE <CONDITION>;

Ex:
SQL> delete from emp where empno=103;

2. DML Update command

a) Updating all rows

Syntax:
UPDATE <TABLENAME> SET <COL>=<EXP>,<COL>=<EXP>;

Ex:
SQL> update emp set ename='Suresh';

b) Updating selected records.

Syntax:
UPDATE <TABLENAME> SET <COL>=<EXP>, <COL>=<EXP>
WHERE <CONDITION>;

Ex:
SQL> update emp set ename='Suresh' where empno=101;

22
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

3. Sorting (using ORDER BY clause)

ORDER BY: used to sort data of table.


SQL> select * from std;

IDNO NAME MARKS


---------- ---------- ----------
1 ramesh 78
2 ram 56
2 ram 56
3 syam 70

SQL> select * from std order by marks;

IDNO NAME MARKS


---------- ---------- ----------
2 ram 56
2 ram 56
3 syam 70
1 ramesh 78

SQL>select * from std order by marks desc;

IDNO NAME MARKS


---------- ---------- ----------
1 ramesh 78
3 syam 70
2 ram 56
2 ram 56

SQL> select * from std order by name desc;

IDNO NAME MARKS


---------- ---------- ----------
3 syam 70
1 ramesh 78
2 ram 56

4. Creating Table from existing Table

SQL>select * from std;

IDNO NAME MARKS


---------- ---------- ----------
1 ramesh 78
2 ram 56

23
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

2 ram 56
3 syam 70

SQL> create table std2(idno,marks) as select idno,marks from std;


Table created.

SQL> select * from std2;

IDNO MARKS
---------- ----------
1 78
2 56
2 56
3 70

SQL> create table std3 as select * from std;


Table created.

SQL> select * from std3;

IDNO NAME MARKS


---------- ---------- ----------
1 ramesh 78
2 ram 56
2 ram 56
3 syam 70

5. Creating Empty Table from existing Table

SQL> create table std4 as select * from std where 1=2;


Table created.

SQL> select * from std4;


no rows selected

SQL> desc std4;


Name Null? Type
----------------------------------------- -------- ----------------------------
IDNO NUMBER(1)
NAME VARCHAR2(10)
MARKS NUMBER(3)

SQL> insert into std4 select idno,name,marks from std;


4 rows created.

24
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> select * from std4;


IDNO NAME MARKS
---------- ---------- ----------
1 ramesh 78
2 ram 56
2 ram 56
3 syam 70
SQL> create table std5 as select * from std where 1=2;
Table created.

SQL> insert into std5 select * from std where marks>57;


2 rows created.

SQL> select * from std5;

IDNO NAME MARKS


---------- ---------- ----------
1 ramesh 78
3 syam 70

SQL> insert into std5 select * from std where name like 'r%';
3 rows created.

SQL> select * from std5;

IDNO NAME MARKS


---------- ---------- ----------
1 ramesh 78
3 syam 70
1 ramesh 78
2 ram 56

6. Arithmetic operators: They are +, - , /, *, ** (Exponential). They can be used


while retrieving, inserting, updating records.

(1) Display ename, salary per annum for employees.


SQL> select ename, (salary*12) salaryperannum from emp;
O/P:
ename salaryperannum
---------- --------------
RANI 24000
RAM 60000
RAJA 84000
MEHUL 120000
SAMIR 144000

25
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

7. Logical operators: They are AND, OR, NOT. They can be used while
retrieving, updating records in WHERE clause.

(1) Select all employees either having salary more than 7000 or of department 5.
SQL>select * from emp where salary>7000 and dno=5;
eno ename salary dno pno
----- ---------- ---------- ---------- -------
e004 mehul 10000 5 2

8. Relational operators: They are =, >, <, >=, <=. They can be used while
retrieving, updating records in WHERE clause.

9. Range searching: It can be done using BETWEEN and NOT BETWEEN


operators.

(1) Display all employees having salary between 5000 to 10000.


SQL>select * from emp where salary between 5000 and 10000;
eno ename salary dno pno
----- ---------- ---------- ---------- ----------
e002 ram 5000 2 1
e003 raja 7000 5 2
e004 mehul 10000 5 2

10. IN and NOT IN operators:


(1) Show all employees’ details who are having salary either 2000 or 7000 or
12000.
SQL>select * from emp where salary in (2000,7000,12000);
eno ename salary dno pno
----- ---------- ---------- ---------- ----------
e001 rani 2000 2 1
e003 raja 7000 5 2
e005 samir 12000 4 2

(2) Show all employees’ details who are having salary other than
2000,7000,12000.
SQL>select * from emp where salary not in (2000,7000,12000);
eno ename salary dno pno
----- ---------- ---------- ---------- ----------
e002 ram 5000 2 1
e004 mehul 10000 5 2

26
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

 PRACTICAL SET

1. Create table supplier from employee with all the columns.


2. Create table sup1 from employee with first two columns.
3. Create table sup2 from employee with no data
4. Delete all the rows from sup1.
5. Delete the detail of supplier whose sup_no is 103.
6. Rename the table sup2.
7. Destroy table sup1 with all the data.
8. Show details of branch in ascending order of branch name.
9. Display the list of employees with salary highest to lowest.
10. Display branch cities in ascending order and branches in it in descending
order.
11. Update the value of employee name whose employee number is 103.
12. Update the minimum salary of programmer to 3500 and maximum salary to
15000.
13. Display the depositors in branch ‘Andheri’ with amount<8000.
14. Display the employees whose job_id is ‘MK_MGR’ or dept_no is 10.
15. Display all the employees whose job_id is ‘MK_MGR’ and salary is less than
12000 or all those employees whose salary is greater than 3000 and less than
10000.
16. Display customer details who do not have account in branch ‘B7’.
17. Display all the customers who do not have loan between 3000 and 7000.

27
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 4

OBJECTIVE: To study LIKE predicate, dual table concept and various


aggregation functions.

Commands:

1. Pattern matching (using LIKE predicate):


a) Retrive all employees whose name starts with R.
SQL>select * from emp where ename like 'r%';
eno ename salary dno pno
----- ---------- ---------- ---------- ----------
e001 rani 2000 2 1
e002 ram 5000 2 1
e003 raja 7000 5 2

b) Retrive all employees whose name starts with R and of 4 characters.


SQL>select * from emp where ename like 'r___';
eno ename salary dno pno
----- ---------- ---------- ---------- ----------
e001 rani 2000 2 1
e003 raja 7000 5 2

2. Dual table

SQL> desc dual;


Name Null? Type
----------------------------------------- -------- ----------------------------
DUMMY VARCHAR2(1)

SQL> select * from dual;

D
-
X

SQL> select 2*3 from dual;

2*3
----------
6
SQL> select 2/3 from dual;

2/3

28
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

----------
.666666667

SQL> select sysdate from dual;

SYSDATE
---------
01-FEB-07

SQL> select round(15.91) from dual;

ROUND(15.91)
------------
16

SQL> SELECT TO_NUMBER('12345') FROM DUAL;

TO_NUMBER('12345')
------------------
12345

SQL> SELECT TO_CHAR(12345,'$099,999') FROM DUAL;

TO_CHAR(1
---------
$012,345

SQL> SELECT TO_CHAR(123,'$0999') FROM DUAL;

TO_CHA
------
$0123

SQL> CREATE TABLE T1(DT DATE);


Table created.

SQL> INSERT INTO T1 VALUES('12-JUN-2006');


1 row created.

SQL> SELECT * FROM T1;


DT
---------
12-JUN-06

29
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> SELECT TO_CHAR(DT,'MONTH DD,YYYY') "NEW DATE FORMAT"


FROM T1;
NEW DATE FORMAT
-----------------
JUNE 12,2006
SQL> SELECT TO_CHAR(DT,'MONTH DD,YY') "NEW DATE FORMAT" FROM
T1;

NEW DATE FORMAT


---------------
JUNE 12,06

SQL> CREATE TABLE T2(ID CHAR(1),DOB DATE);


Table created.

SQL> INSERT INTO T2 VALUES('1',TO_DATE('30-JUL-2006 10:30 A.M.','DD-


MON-YY HH:MI A.M.'));
1 row created.

SQL> SELECT * FROM T2;

I DOB
- ---------
1 30-JUL-06

SQL> SELECT ADD_MONTHS(SYSDATE,4) FROM DUAL;

ADD_MONTH
---------
03-DEC-06

SQL> SELECT SYSDATE,LAST_DAY(SYSDATE) FROM DUAL;

SYSDATE LAST_DAY(
--------- ---------
03-AUG-06 31-AUG-06

SQL> SELECT MONTHS_BETWEEN('21-FEB-2006','23-JAN-2007') FROM


DUAL;

MONTHS_BETWEEN('21-FEB-2006','23-JAN-2007')
-------------------------------------------
-11.06452

30
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> SELECT MONTHS_BETWEEN('21-FEB-2008','23-JAN-2007') FROM


DUAL;
MONTHS_BETWEEN('21-FEB-2008','23-JAN-2007')
-------------------------------------------
12.935484
SQL> SELECT NEXT_DAY('03-AUG-2006','SATURDAY') FROM DUAL;

NEXT_DAY(
---------
05-AUG-06

SQL> SELECT * FROM T2;

I DOB
- ---------
1 30-JUL-06
2 22-JAN-05
3 03-APR-03

SQL> SELECT ID,TO_CHAR(DOB,'DD-MM-YY') FROM T2 ORDER BY


TO_CHAR(DOB,'MM');

I TO_CHAR(
- --------
2 22-01-05
3 03-04-03
1 30-07-06

SQL> SELECT ID,TO_CHAR(DOB,'DDTH-MON-YY') FROM T2;

I TO_CHAR(DOB
- -----------
4 22ND-MAY-98

SQL> SELECT ID,TO_CHAR(DOB,'DDSP') FROM T2;

I TO_CHAR(DOB,
- ------------
4 TWENTY-TWO

SQL> SELECT ID,TO_CHAR(DOB,'DDSPTH') FROM T2;

I TO_CHAR(DOB,'D
- --------------
4 TWENTY-SECOND

31
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> SELECT UID FROM DUAL;

UID
---------
510

SQL> SELECT USER FROM DUAL;


USER
------------------------------
BHAVINI

3. Aggregation Functions:

SQL> select count(idno) from student;

COUNT(IDNO)
-----------
3

SQL> select count(marks) from student;


COUNT(MARKS)
------------
3

SQL> select count(idno) from student where name like 'y%';

COUNT(IDNO)
-----------
1

SQL> select count(idno) from student where name like 'y%';

COUNT(IDNO)
-----------
1

SQL> select sum(marks) totalmarks from student;

TOTALMARKS
----------
202

SQL> select sum(marks)/count(idno) avgmarks from student;

32
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

AVGMARKS
----------
67.3333333

SQL> select avg(marks) avgmarks from student;

AVGMARKS
----------
67.3333333

SQL> select max(marks) from student;

MAX(MARKS)
----------
89

SQL> select min(marks) from student;

MIN(MARKS)
----------
35

SQL> select * from student;

IDNO CPI NAME MARKS


---------- ---------- ---------- ----------
1 6.8 yash 78
2 8.6 raj 89
3 4.7 chicks 35

SQL> select * from student where name like '_a%';

IDNO CPI NAME MARKS


---------- ---------- ---------- ----------
1 6.8 yash 78
2 8.6 raj 89

SQL> create table std(idno number(1),name varchar(10),marks number(3));


Table created.

SQL> select * from std;

IDNO NAME MARKS


---------- ---------- ----------

33
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

1 ramesh 78
2 ram 56
2 ram 56
3 syam 70

SQL> select distinct * from std;

IDNO NAME MARKS


---------- ---------- ----------
1 ramesh 78
2 ram 56
3 syam 70

SQL> select distinct idno,name from std;

IDNO NAME
---------- ----------
1 ramesh
2 ram
3 syam

34
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

 Practical Set

1. Give details of account no. and deposited rupees of customers having


account opened between dates 01-01-06 and 25-07-06.
2. Display employee no, name and department details of those employee
whose department lies in(10,20)
3. Display all employee whose name start with ‘A’ and third character is ‘a’.
4. Display name, number and salary of those employees whose name is 5
characters long and first three characters are ‘Ani’.
5. Display the non-null values of employees and also employee name second
character should be ‘n’ and string should be 5 character long.
6. Display the null values of employee and also employee name’s third
character should be ‘a’.
7. What will be output if you are giving LIKE predicate as ‘%\_%’ ESCAPE ‘\’
8. Update the value dept_no to 10 where second character of emp_name is ‘m’.
9. Insert the data into sup2 from employee whose second character should be
‘n’ and string should be 5 characters long in employee name field.
10. Calculate and display the result of 2*2.
11. Write a query to display the current date. Label the column Date
12. List total deposit from deposit.
13. List total loan from karolbagh branch
14. Give maximum loan from branch vrce.
15. Count total number of customers
16. Count total number of customer’s cities.
17. Display name and salary of employee whose department no is 20. Give alias
name to name of employee.

35
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 5

OBJECTIVE: To study Single-row functions

Commands:

Concatenation of data from table


SQL> select name || ' has social security number ' || ssn || ' and woking in dept. no ' ||
dno from empl;

NAME||'HASSOCIALSECURITYNUMBER'||SSN||'ANDWOKINGINDEPT.NO'||DNO
--------------------------------------------------------------------------------
john has social security number 1 and woking in dept. no 5
frank has social security number 2 and woking in dept. no 5
alicia has social security number 3 and woking in dept. no 4
jenifer has social security number 4 and woking in dept. no 4
ramesh has social security number 5 and woking in dept. no 5
joyce has social security number 6 and woking in dept. no 5
ahmad has social security number 7 and woking in dept. no 4
james has social security number 8 and woking in dept. no 1
8 rows selected.

 Practical Set

1. For each employee, display the employee number, job, salary, and salary
increased by 15% and expressed as a whole number. Label the column New
Salary
2. Modify your query no 4.(1) to display the subtraction of the old salary from the
new salary. Label it as Increase.
3. Write a query that displays the employee’s names with the first letter
capitalized and all other letters lowercase, and the length of the names, for all
employees whose name starts with J, A, or M. Give each column an
appropriate label. Sort the results by the employees’ last names.
4. Write a query that produces the following for each employee: <employee first
name> earns <salary> monthly. (Hint: use CONCAT() function).
5. Display the date on which the account was opened of customer in a format
that appears as Seventh of June 1994 12:00:00 AM. (Hint: use
TO_CHAR(date, 'fmDdspth "of" Month YYYY fmHH:MI:SS AM' )
6. Write a query to calculate the annual compensation of all employees
(sal+comm.).

36
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 6

OBJECTIVE: Displaying data from Multiple Tables (join)

Commands:

INNER JOIN

Query 1: retrieve name of the manager of each department.

Method 1:Theta-style

SQL> select dname,name from empl,deprt where empl.ssn=deprt.mgrssn;


DNAME NAME
-------- --------
research frank
admin jenifern
headqatr james

Method 2:Ansi-style

SQL> select dname,name from empl inner join deprt on empl.ssn=deprt.mgrssn;


DNAME NAME
-------- --------
research frank
admin jenifer
headqatr james

Query 2:

Method 1:Theta-style

SQL> select dname,name from empl,deprt where empl.ssn=deprt.mgrssn and


empl.name like 'j%';

DNAME NAME
-------- --------
admin jenifer
headqatr james

Method 2:Ansi-style

SQL> select dname,name from empl inner join deprt on empl.ssn=deprt.mgrssn


where empl.name='frank';

DNAME NAME

37
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

-------- --------
research frank

Query 3:

SQL> select dname,name from empl,deprt where empl.ssn=deprt.mgrssn and


empl.name
like 'j%' order by empl.name;

DNAME NAME
-------- --------
headqatr james
admin jenifer

SQL> select dname,name from empl,deprt where empl.ssn=deprt.mgrssn and


empl.name
like 'j%' order by deprt.dname;

DNAME NAME
-------- --------
admin jenifer
headqatr james

OUTER JOIN

[1] LEFT OUTER JOIN

Query: list of all employee names & also name of departments they manage.
SQL> select e.name,d.dname from empl e,deprt d where e.ssn=d.mgrssn(+);
NAME DNAME
-------- --------
john
frank research
alicia
jenifer admin
ramesh
joyce

ahmad
james headqatr
8 rows selected.

[2] RIGHT OUTER JOIN

Query: list of all employee names & also name of departments they manage.

38
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> select e.name,d.dname from empl e,deprt d where d.mgrssn(+)=e.ssn;


NAME DNAME
-------- --------
john
frank research
alicia
jenifer admin
ramesh
joyce
ahmad
james headqatr
8 rows selected.

CROSS JOIN

Query: to retrieve for each employee a list of the names of their dependants.

SQL> select e.name,d.depname from empl e cross join depen d where


e.ssn=d.essn;
NAME DEPNAME
-------- --------
frank alice
frank theod
frank joy
jenifer abner
john michel
john alice
john eliza
7 rows selected.

Query: supervisor of each employee

SQL> select e.name "employee",s.name "supervisor" from empl e,empl s where


e.superssn=s.ssn;

employee supervis
-------- --------
john frank
frank james
alicia jenifer
jenifer james
ramesh frank
joyce frank
ahmad jenifer

39
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

7 rows selected.

 Practical Set

1. Give details of customers ANIL.


2. Give name of customer who are borrowers and depositors and having living
city Nagpur.
3. Display the customer name and city at which the customer has account.
4. Display the employee name, department number and designation of
employees whose names start with letter S.
5. Display the name, department number and salary of all employees who work
in ‘Bombay’.

40
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 7

OBJECTIVE: To apply the concept of Aggregating Data using Group functions.

Commands:

SQL> create table empl(name varchar(8),ssn number(1),salary number(6),superssn


number(1),dno number(1),primary key(ssn));
Table created.

SQL> create table deprt(dname varchar(8),dnumber number(1),mgrssn number(1));


Table created.

SQL> create table d_loc(dnumber number(1),dloc varchar(8),foreign key(dnumber)


references deprt(dnumber));
Table created.

SQL> create table prjt(pname varchar(8),pnumber number(2),dnum


number(1),primary
key(pnumber),foreign key(dnum) references deprt(dnumber);
Table created.

SQL> create table w_n(essn number(1),pno number(2),foreign key(essn) references


empl(ssn),foreign key(pno) references prjt(p
Table created.

SQL> create table depen(essn number(1),depname varchar(8),foreign key(essn)


references empl(ssn);
Table created.

SQL> select * from empl;

NAME SSN SALARY SUPERSSN DNO


-------- --------- --------- --------------- ---------
john 1 30000 2 5
frank 2 40000 8 5
alicia 3 25000 4 4
jenifer 4 43000 8 4
ramesh 5 38000 2 5
joyce 6 25000 2 5

8 rows selected.

SQL> select * from deprt;

DNAME DNUMBER MGRSSN

41
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

-------- --------- ---------


research 5 2
admin 4 4
headqatr 1 8

SQL> select * from w_n;

ESSN PNO
--------- ---------
1 1
1 2
5 3
6 1
6 2
2 2
2 3
2 10
2 20
3 30
3 10
7 10
7 30
4 30
4 20
8 20

16 rows selected.

SQL> select * from prjt;

PNAME PNUMBER DNUM


-------- --------- ---------
p-x 1 5
p-y 2 5
p-z 3 5
c 10 4
r 20 1
n 30 4

SQL> select * from depen;

ESSN DEPNAME
--------- --------
2 alice
2 theod

42
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

2 joy
4 abner
1 michel
1 alice
1 eliza

7 rows selected.
SQL> select * from d_loc;

DNUMBER DLOC
--------- --------
1 hos
4 staffrd
5 bell
5 sugland
5 hos

SQL> select dno,count(ssn) " no of emps",avg(salary) "avg. salary" from empl group
by
dno;
DNO no of emps avg. salary
---------- ----------- -----------
1 1 55000
4 3 31000
5 4 33250

SQL> select dno,count(ssn) " no of emps",avg(salary) "avg. salary" from empl group
by
dno having avg(salary)>32000;

DNO no of emps avg. salary


------------- ----------- -----------
1 1 55000
5 4 33250

SQL> select dno,count(ssn) " no of emps",avg(salary) "avg. salary" from empl group
by
dno having count(ssn)=1;

DNO no of emps avg. salary


---------- ----------- -----------
1 1 55000

43
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> select dno,count(ssn) " no of emps",avg(salary) "avg. salary" from empl group
by
rollup(dno,ssn);

DNO no of emps avg. salary


---------- ----------- -----------
1 1 55000
1 1 55000
4 1 25000
4 1 43000
4 1 25000
4 3 31000
5 1 30000
5 1 40000
5 1 38000
5 1 25000
5 4 33250

DNO no of emps avg. salary


---------- ----------- -----------
8 35125
12 rows selected.
SQL> select dno,count(ssn) " no of emps",avg(salary) "avg. salary" from empl group
by
cube(dno,ssn);

DNO no of emps avg. salary


---------- ----------- -----------
1 1 55000
1 1 55000
4 1 25000
4 1 43000
4 1 25000
4 3 31000

44
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

 Practical Set

1. List total deposit of customer having account date after 1-jan-96.


2. List total deposit of customers living in city Nagpur.
3. List maximum deposit of customers living in bombay.
4. Display the highest, lowest, sum, and average salary of all employees. Label
the columns Maximum, Minimum, Sum, and Average, respectively. Round
your results to the nearest whole number.
5. Write a query that displays the difference between the highest and lowest
salaries. Label the column DIFFERENCE.
6. Create a query that will display the total number of accounts opened in 1995,
1996, 1997, and 1998.
7. Find the average salaries for each department without displaying the
respective department numbers.
8. Write a query to display the total salary being paid to each job title, within
each department.
9. Find the average salaries > 2000 for each department without displaying the
respective department numbers.
10. Display the job and total salary for each job with a total salary amount
exceeding 3000, in which excludes lecturer and sorts the list by the total
salary.
11. List the branches having sum of deposit more than 5000 and located in city
bombay.

45
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 8

OBJECTIVE: To solve queries using the concept of sub query.

Commands:

SUBQUERIES

SQL> create table stdt(id number(1),name varchar(8));


Table created.

SQL> select * from stdt;

ID NAME
---------- --------
1 abc
2 pqr
3 xyz
4 def
5 ijk

SQL> create table stadd(id number(1),addr varchar(15),cpi number(4,2));


Table created.

SQL> select * from stadd;

ID ADDR CPI
---------- --------------- ----------
1 anand 8
2 baroda 7
3 ahmedabad 8.9
4 surat 5.9
5 rajkot 7.8

SQL> alter table stdt add primary key(id);


Table altered.

SQL> alter table stadd add constraint dev foreign key(id) references stdt;
Table altered.

SQL> select id,addr from stadd where id in(select id from stdt where name='def');

ID ADDR
---------- ---------------
4 surat

46
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> select id,addr from stadd where id not in(select id from stdt where name='def');
ID ADDR
---------- ---------------
1 anand
2 baroda
3 ahmedabad
5 rajkot

MULTI COLUMN SUBQUERY

Query: all the teacher having same name as student.

SQL> create table teacher(tid number(1),fname varchar(8),lname varchar(8));


Table created.

SQL> select * from teacher;

TID FNAME LNAME


--------- -------- --------
1 yash patel
2 raj dave

SQL> create table stu(id number(1),fname varchar(8),lname varchar(8));


Table created.

SQL> select * from stu;

ID FNAME LNAME
--------- -------- --------
1 sunil shah
2 yash patel

SQL> select fname,lname from teacher where(fname,lname) in(select fname,lname


from
stu);

FNAME LNAME
-------- --------
yash patel

USING EXISTS / NOT EXISTS OPERATOR

47
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> select id,fname,lname from stu s where exists(select fname from teacher
where
tid=s.id);

ID FNAME LNAME
--------- -------- --------
1 sunil shah
2 yash patel

SQL> select id,fname,lname from stu s where exists(select fname,lname from


teacher
where tid=s.id);

ID FNAME LNAME
--------- -------- --------
1 sunil shah
2 yash patel

SQL> select * from stu;

ID FNAME LNAME
--------- -------- --------
1 sunil shah
2 yash patel
3 syam jain
4 akash gosai

SQL> select * from teacher;

TID FNAME LNAME


--------- -------- --------
1 yash patel
2 raj dave

SQL> select id,fname,lname from stu s where exists(select fname from teacher
where
tid=s.id);

ID FNAME LNAME
--------- -------- --------
1 sunil shah
2 yash patel

48
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

SQL> select id,fname,lname from stu s where exists(select fname,lname from


teacher
where tid=s.id);

ID FNAME LNAME
--------- -------- --------
1 sunil shah

2 yash patel

SQL> select * from teacher;

TID FNAME LNAME


--------- -------- --------
1 yash patel
2 raj dave
3 gaurav panchal

SQL> select * from stu;

ID FNAME LNAME
--------- -------- --------
1 sunil shah
2 yash patel
3 syam jain
4 akash gosai

SQL> select id,fname,lname from stu s where exists(select fname,lname from


teacher
where tid=s.id);

ID FNAME LNAME
--------- -------- --------
1 sunil shah
2 yash patel
3 syam jain

SQL> select id,fname,lname from stu s where not exists(select fname,lname from
teacher
where tid=s.id);

ID FNAME LNAME
--------- -------- --------
4 akash gosai

49
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

USING SUBQUERY IN THE FROM CLAUSE

SQL> create table acct_mstr(accno char(3),branchno char(2),curbal number(8));


Table created.

SQL> select * from acct_mstr;

ACC BR CURBAL
--- -- ---------
sa1 b1 25000
sa2 b2 350000
sa3 b1 3200
ca1 b1 450000
ca2 b1 112000
ca3 b2 2100
6 rows selected.

Query: list accounts along with the current balance, the branch to which it belongs &
avg. balance of that branch, to which the account belongs.

SQL> select a.accno,a.curbal,a.branchno,b.avgbal from acct_mstr a,(select


branchno,avg(curbal) avgbal from acct_mstr group by branchno) b where
a.branchno=b.branchno;

ACC CURBAL BR AVGBAL


--- --------- -- ---------
sa1 25000 b1 147550
sa3 3200 b1 147550
ca1 450000 b1 147550
ca2 112000 b1 147550
sa2 350000 b2 176050
ca3 2100 b2 176050
6 rows selected.

USING CORRELATED SUB-QUERIES

Query: list accounts along with the current balance & the branch no which it belongs,
having a balance more than the average balance of the branch, to which the account
belongs.

SQL> select accno,curbal,branchno from acct_mstr a where curbal>(select


avg(curbal) from acct_mstr where branchno=a.branchno);

ACC CURBAL BR
--- --------- --

50
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

sa2 350000 b2
ca1 450000 b1

USING SUBQUERY IN AN ORDER BY CLAUSE

SQL> create table branch_mstr(branchno char(2),name varchar(15));


Table created.

SQL> select * from branch_mstr;


BR NAME
-- ---------------
b1 abc
b2 def
b3 pqr
b4 xyz
b5 lmn
b6 ijk
6 rows selected.
SQL> alter table branch_mstr add primary key(branchno);
Table altered.

SQL> create table emp_mstr(empno char(2),branchno char(2),fname


varchar(10),lname varchar(10),dept varchar(10),primary key(empno),foreign
key(branchno) references branch_mstr);
Table created.

SQL> select * from branch_mstr;

BR NAME
-- ---------------
b1 abc
b2 def
b3 pqr
b4 xyz
b5 lmn
b6 ijk
6 rows selected.

SQL> select * from emp_mstr;

EM BR FNAME LNAME DEPT


-- -- ---------- ---------- ----------
e1 b1 yash patel marketing
e2 b1 mahesh panchal loan
e3 b2 ramesh dave admin

51
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

e4 b3 suresh parmar loan

Query: List the employees of the bank in the order of the branch names at which
they are employed

SQL> select empno,(fname || '' ||lname) "name" ,dept from emp_mstr e order
by(select
name from branch_mstr b where e.branchno=b.branchno);
EM name DEPT
-- -------------------- ----------
e1 yashpatel marketing
e2 maheshpanchal loan
e3 rameshdave admin
e4 sureshparmar loan

 Practical Set

1. Write a query to display the name and salary of any employee in the same
department as smith. Exclude smith.
2. Give name of customers who are depositors having same branch city of mr.
anil.
3. Give deposit details and loan details of customer in same city where pramod
is living.
4. Create a query to display the employee numbers and last names of all
employees who earn more than the average salary. Sort the results in
ascending order of salary.
5. Give names of depositors having same living city as mr. anil and having
deposit amount greater than 2000.
6. Display the department number, name, and job for every employee with job
same of snehal.
7. List the name of branch having highest number of depositors.
8. Give the name of cities where in which the maximum numbers of branches
are located.
9. Give name of customers living in same city where maximum depositors are
located.

52
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 9

OBJECTIVE: To solve queries by manipulating Data.

 Practical List

1. Give 10% interest to all depositors.


2. Give 10% interest to all depositors having branch vrce
3. Give 10% interest to all depositors living in nagpur and having branch city
bombay.
4. Write a query which changes the department number of all employees with
empno 7788’s job to employee 7844’current department number.
5. Give 100 Rs more to all depositors if they are maximum depositors in their
respective branch.
6. Delete depositors of branches having number of customers between 1 to 3.
7. Delete deposit of vijay.
8. Delete borrower of branches having average loan less than 1000.

53
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 10

OBJECTIVE: To apply the concept of security and privileges.

THEORY: oracle provides security in oreder to safeguard information stored in


table,view.depending on user’s status & responcibility ,appropriate rights on
oracle’s reasource can be assigned to user by DBA.they are called privileges.

Commands:

[1] GRANT

User1: bhavini

SQL> desc s;
Name Null? Type
------------------------------- -------- ----
SNO NOT NULL CHAR(3)
SNAME VARCHAR2(8)

SQL> select * from s;

SNO SNAME
--- --------
s1 abc
s2 def
s3 pqr
s4 xyz
s5 ijk
s6 lmn

6 rows selected.

SQL> grant select on s to a1;

Grant succeeded.

User2: a1

SQL> select * from bhavini.s;

SNO SNAME
----- -------
s1 abc
s2 def
s3 pqr

54
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

s4 xyz
s5 ijk
s6 lmn

6 rows selected.

SQL> insert into bhavini.s values('s7','dgh');


insert into bhavini.s values('s7','dgh')
*
ERROR at line 1:
ORA-01031: insufficient privileges

User1: bhavini

SQL> grant insert on s to a1;


Grant succeeded.

User2: a1

SQL> insert into bhavini.s values('s7','dgh');


1 row created.

SQL> select * from bhavini.s;

SNO SNAME
--- --------
s1 abc
s2 def
s3 pqr
s4 xyz
s5 ijk
s6 lmn
s7 dgh

7 rows selected.

User1: bhavini

SQL> select * from s;

SNO SNAME
------- --------
s1 abc
s2 def

55
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

s3 pqr
s4 xyz
s5 ijk
s6 lmn

6 rows selected.

User2: a1

SQL> commit;
Commit complete.

User1: bhavini

SQL> select * from s;

SNO SNAME
--- --------
s1 abc
s2 def
s3 pqr
s4 xyz
s5 ijk
s6 lmn
s7 dgh

7 rows selected.

[2] REVOKE

User1: bhavini

SQL> revoke insert on s from a1;

Revoke succeeded.

User2: a1

SQL> insert into bhavini.s values('s8','asd');


insert into bhavini.s values('s8','asd')
*
ERROR at line 1:
ORA-01031: insufficient privileges

56
Government Engineering College, Patan
Computer Science and Engineering Department
Database Management System (3130703)

PRACTICAL NO: 11

OBJECTIVE: To study Transaction control commands.

TCL (TRANSACTION CONTROL LANGUAGE)


COMMIT
ROLL BACK
SAVE POINT

PROCEDURE
STEP 1: Start
STEP 2: Create the table with its essential attributes.
STEP 3: Insert the record into table
STEP 4: Update the existing records into the table
STEP 5: Delete the records in to the table
STEP 6: use save point if any changes occur in any portion of the record to undo its
original state.
STEP 7: use rollback for completely undo the records
STEP 6: use commit for permanently save the records.

COMMIT:
COMMAND DESCRIPTION: COMMIT command is used to save the
Records.

ROLLBACK:
COMMAND DESCRIPTION: ROLL BACK command is used to undo the
Records.

SAVE POINT:
COMMAND DESCRIPTION: SAVE POINT command is used to undo the
Records in a particular transaction.

57

You might also like