0% found this document useful (0 votes)
11 views54 pages

DBMS Lab Manual(Final)

The Database Management Systems Lab Manual provides a comprehensive guide for II B. Tech students, detailing course objectives, outcomes, and a series of experiments related to database design and SQL commands. Key topics include ER design, DDL, DML, DCL, and TCL commands, as well as PL/SQL concepts such as triggers and stored procedures. The manual also includes a description of a sales database and various SQL queries to manipulate and retrieve data.

Uploaded by

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

DBMS Lab Manual(Final)

The Database Management Systems Lab Manual provides a comprehensive guide for II B. Tech students, detailing course objectives, outcomes, and a series of experiments related to database design and SQL commands. Key topics include ER design, DDL, DML, DCL, and TCL commands, as well as PL/SQL concepts such as triggers and stored procedures. The manual also includes a description of a sales database and various SQL queries to manipulate and retrieve data.

Uploaded by

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

DATABASE MANAGEMENT

SYSTEMS
LAB MANUAL (14BT40521)

II B. Tech – II Semester (2016-


17)
Prepared
By

MR.M.THRILOK REDDY
ASST.PROFESSOR
DEPT.OF IT
SVEC

&
MS.E.SANDHYA
ASST.PROFESSOR
DEPT.OF IT
SVEC

DEPARTMENT OF INFORMATION TECHNOLGY


SREE VIDYANIKETHAN
ENGINEERING COLLEGE
(AUTONOMOUS)
Sree Sainath Nagar, A. Rangampet – 517 102

2016-17
Prepared by: Mr.M.Thrilok Reddy Page 1
SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
Lab Manual, II B. Tech – II Semester (2016-17)
Database Management Systems Lab

COURSE DESCRIPTION:
Hands on experience on developing ER Design, DDL, DML commands, DCL and TCL Commands,
Query processing using Aggregate operators, Subqueries, Joins, Date Manipulation functions, PL/
SQL concepts: Triggers, Functions, Cursors, Stored Procedures and basic Programs.

COURSE OBJECTIVES:
CEO1. To impart basic knowledge on E-R design and Normal forms impact in Database design.
CEO2. To develop skills in query processing using DML Commands and security to a database
using TCL, DCL Commands.
CEO3. To apply the concepts and principles of PL/SQL to implement complex integrity constraints
in a database application with Triggers and cursors.

COURSE OUTCOMES:
After the successful completion of the course, the student will be able to:
1. Design and implement a database schema for the sales database.
2. Apply normalization on sales database.
3. Analyze and evaluate the databases using SQL DML/DDL commands.
4. Develop solutions to database problems using programming PL/ SQL including stored
procedures, stored functions, cursors and triggers.

LIST OF EXPERIMENTS:

DESCRIPTION OF SALES DATABASE:

ABC is a company operating in the country with a chain of shopping centers in various cities.
Everyday large numbers of items are sold in different shopping centers. The Sales database
comprises of various tables like CUST, PROD, SALES_DETAIL, STATE_NAME with the
following schemas.

Prepared by: Mr.M.Thrilok Reddy Page 2


CUST TABLE
Name Type Remark
CID VARCHAR2(6) PRIMARY KEY
CNAME VARCHAR2(10)
CCITY VARCHAR2(8)

PROD TABLE
Name Type Remark
PID VARCHAR2(6) PRIMARY KEY
PNAME VARCHAR2(6)
PCOST NUMBER(4,2)
PROFIT NUMBER(3)

SALES DETAIL
Name Type Remark
CID VARCHAR2(6) COMPOSITE PRIMARY KEY
PID VARCHAR2(6) COMPOSITE PRIMARY KEY
SALE NUMBER(3)
SALEDT DATE COMPOSITE PRIMARY KEY

STATE NAME
Name Type Remark
CCITY VARCHAR2(8) PRIMARY KEY
STATE VARCHAR2(15)

1. Data Retrieval
a) Write a query to display all columns of CUST table.
b) Write a query to display pname of all records. Sort all records by pname. (use order by
clause)
c) Write a query to display cname and ccity of all records. Sort by ccity in descending order.
d) Write a query to display cname, ccity who lives in mysore.
e) Write a query to display cname, pname, sale, saledt for all customers.
f) Write a query to display cname who have purchased Pen.
g) Write a query to display saledt and total sale on the date labeled as sale of all items sold after
01-sep-2010.
h) Write a query to display saledt and total sale on the date labeled as sale of all items other than
DVD.
i) Write a query to display cname and ccity of all customers who live in Kolkata or Chennai .

Prepared by: Mr.M.Thrilok Reddy Page 3


2. Use of Distinct, between, in clause, like operator, Dual.
a) Write a query to display the pname and pcost of all the customers where pcost lies between 5
and 25.
b) Find the product ids in sale_detail table (eliminating duplicates).
c) Write a query to display distinct customer id where product id is p3 or sale date is '18-mar-
2011'.
d) Write a query to display cname, pid and saledt of those customers whose cid is in c1 or c2 or
c4 or c5.
e) Write a query to display cname, pid, saledt of those customers whose pid is p3 or sale date is
'20-dec-2009'.
f) Write a query to display system date.
g) Write a query to display all records of prod table in which first and third character of pname
is any character and second character is 'E'.
h) Write a query to display all cname which includes two 'A' in the name.

3. Constraints
Implement table level and Column level constraints like NOT NULL, UNIQUE, PRIMARY KEY,
FOREIGN KEY, CHECK.

4. Single Row Functions: DATE Function

a) Write a query to display the system date by rounding it to next month.


b) Write a query to display the system date by rounding it to next year.
c) Write a query to display the last date of the system date.
d) Write a query to display the next date of system date which is Friday.
e) Write a query to display sale date and date after 02 months from sale date.
f) Write a query to display system date, sale date and months between two dates.
g) Write a query to display the greatest date between sale date and
h) system date, name it as BIG, also display sale date and SYSDATE.
i) Write a query to display the least date between sale date and system date name it as SMALL,
also display sale date and SYSDATE.

5. Single Row Functions: Numeric and Character Function

a) Write a query to display the product name along with the rounded value of product cost for
product name is "Pencil".

Prepared by: Mr.M.Thrilok Reddy Page 4


b) Write a query to display product cost along with MOD value if divided by 5.
c) Write a query to display cname in uppercase, lowercase, titlecase from cust table where
customer name is "rohan".
d) Write a query to display all concatenated value of cname, ccity by converting cname into
titlecase and ccity into uppercase.
e) Write a query to display the first 3 characters of cname.
f) Write a query to display the position of 'M' in the cname of the customer whose name is
"SAMHITA".
g) Write a query to display the length of all customer names.
h) PAD # character in left of product cost to a total width of 5 character position.
6. Group Functions and SET Functions
a) Write a query to display the total count of customer.
b) Write a query to display the minimum cost of product.
c) Write a query to display average value of product cost rounded to 2nd decimal places.
d) Write a query to display product name with total sale detail in descending order.
e) Write a query to display product name, sale date and total amount collected for the product.
f) Write a query to display sale date and total sale date wise which was sold after "14-jul-08".
g) Write a query to display the customer name who belongs to those places whose name is
having I or P.
h) Write a query to display customer name who belongs to a city whose name contains
characters 'C' and whose name contains character 'A'.
i) Write a query to display the customer name who does not belong to PUNE.
7. PL/SQL basic programs
a) Write a PL/SQL program to find largest number among three.(Hint: Use Conditional
Statement)
b) Write a PL/SQL program to display the sum of numbers from 1 to N using for loop,
loop...end and while...loop.
8. SQL Cursor based programs
a) Write a PL/SQL program to display the costliest and cheapest product in PROD table.
b) Write a PL/SQL program which will accept PID and display PID and its total sale value i.e.
sum.

9. Functions
a) Write a function that accepts two numbers A and B and performs the following operations.

Prepared by: Mr.M.Thrilok Reddy Page 5


i. Addition
ii. Subtraction
iii. Multiplication
iv. Division
b) Write a function that accepts to find the maximum PCOST in PROD table.
10. Procedures
a) Write a procedure that accepts two numbers A and B add them and print.
b) Write procedures to demonstrate IN, IN OUT and OUT parameter.

11. Triggers
a) Develop a PL/SQL program using BEFORE and AFTER triggers.
b) Create a row level trigger for the PROD table that would fire for INSERT or UPDATE or
DELETE operations performed on the PROD table. This trigger will display the profit
difference between the old values and new values.
12. Implicit and Explicit Cursors
Declare a cursor that defines a result set. Open the cursor to establish the result set. Fetch the data
into local variables as needed from the cursor, one row at a time. Close the cursor when done.

REFERENCE BOOKS:

1. Satish Ansari, "Oracle Database 11g: Hands-on SQL and PL/SQL," PHI Publishers, 2010.
2. Pranab Kumar Das Gupta, "Database Management System Oracle SQL and PL/SQL," PHI
Learning Private Limited, 2009.

Prepared by: Mr.M.Thrilok Reddy Page 6


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: DDL commands

Introduction to DBMS
Data:-
Data is a collection of raw facts that may / may not be meaning full.
Information:-
Processed / organized data.
Raw data –this could be “85” –doesn’t have meaning when it stands alone. It might mean something
if you knew it was weight of a man in Kilograms.
Database: - collection of related information.
DBMS:-
 A database consists of an organized collection of interrelated data for one or more uses,
typically in digital form. Examples of databases could be: Database for Educational Institute
or a Bank, Library, Railway Reservation system etc.
 Management System is a set of programs to access those data. A Database Management
System (DBMS) is a software package designed to store and manages databases.
DBS=database + DBMS software
DBMS software:-
 DB2
 MySQL
 SQL Server
 Sybase
 Ingress
 Postgre SQL
 MS Access and Oracle.
Structured Query Language:-
 (SQL) is the language used to interact with Oracle databases.
 SQL is a non-procedural language – you specify the data you want but not how Oracle
should retrieve it.

Prepared by: Mr.M.Thrilok Reddy Page 7


 SQL is standardized by the American National Standards Institute (ANSI), and Oracle’s SQL
meets ANSI standards.

PL/SQL:-
Oracle’s proprietary, procedural extension to SQL that gives you procedural control structures like
WHILE loops and IF statements.
SQL*Plus :-
 The Oracle tool commonly used to interact with Oracle databases.
 With SQL*Plus you can run all SQL statements, PL/SQL programs, format query results,
and administrate the database.

SQL:-
SQL is a data sub language to perform operations in the database software.

DDL COMMANDS:-
Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and
dropping the structure of database objects.

DML COMMANDS:-
Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving,
modifying, and deleting data.

Prepared by: Mr.M.Thrilok Reddy Page 8


DCL COMMANDS:-
Data Control Language (DCL) - These SQL commands are used for providing security to database
objects.

Transaction Control Language (TCL) - These SQL commands are used for managing changes
affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.

Attribute Data Types:-


 Numeric data types
 Character Data types
 Date/ Time data types
 Large object data types
Numeric data types:-
 number
 number(s,p)
o pprecision
o sscale
 integer
 float
 smallint
 int
Character data types:-

Prepared by: Mr.M.Thrilok Reddy Page 9


 Char
 Char(size)
 Varchar(size)
 Varchar2(size)

Naming Rules:-
Table names and column names:
 Must begin with a letter
 Must be 1–30 characters long
 Must contain only A–Z, a–z, 0–9, _, $, and #
 Must not duplicate the name of another object owned by the same user
 Must not be an Oracle server reserved word

DDL COMMANDS & THEIR SYNTAX


The CREATE TABLE statement allows you to create and define a table.
Syntax:-
CREATE TABLE table_name
(
Column_name1 column_datatype(size),
Column_name2 column_datatype(size),
……
);
 It contains:
 Table name
 Column name, column data type, and column size

EX:-
CREATE TABLE customers
(
customer_id number(10),
customer _name varchar2(50),
Address varchar2(50),
);
The ALTER TABLE Statement:-
Use the ALTER TABLE statement to:
Prepared by: Mr.M.Thrilok Reddy Page 10
 Add a new column
 Modify an existing column
 Define a default value for the new column
 Drop a column

Prepared by: Mr.M.Thrilok Reddy Page 11


Prepared by: Mr.M.Thrilok Reddy Page 12
Prepared by: Mr.M.Thrilok Reddy Page 13
SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: DML commands

DML COMMANDS:-
Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving,
modifying, and deleting data.

INSERT SELECT UPDATE DELETE

OBJECTIVES:-
 Describe each DML statement
 Insert rows into a table
 Update rows in a table
 Delete rows from a table

The INSERT Statement Syntax:-


Add new rows to a table by using the INSERT statement.
Syntax:-
1. INSERT INTO table_name (col1,col2,col3,…) VALUES(val1,’val2’,val3….);
Ex:- INSERT INTO departments(department_id, department_name,manager_id,
location_id)VALUES(70, 'Public Relations', 100, 1700);
1 row created.
Note:- Only one row is inserted at a time with this syntax.
2. INSERT INTO table_name VALUES(val1,’val2’,…..);
Ex:- INSERT INTO departments(department_id, department_name,) VALUES(70, 'Public
Relations');

Prepared by: Mr.M.Thrilok Reddy Page 14


3. INSERT INTO table_name(col1,col2,col3) VALUES(&val1,’&val2’,val3);
Ex:-
INSERT INTO departments (department_id, department_name, location_id)
VALUES (&department_id, '&department_name', &location);

The UPDATE Statement Syntax:-


Modify existing rows with the UPDATE statement.
Syntax:-
UPDATE <table_name>
SET column=value, column=value…
WHERE <condition>;
 Update more than one row at a time, if required
 Specific row or rows are modified if you specify the WHERE clause.
 All rows in the table are modified if you omit the WHERE clause.

The DELETE Statement:-


 You can remove existing rows from a table by using the DELETE statement.
Syntax:-
1. DELETE FROM <table_name>;
 It deletes all the rows from the table.
Ex: - DELETE FROM emp;
2. DELETE FROM <table_name> WHERE <condition>;
 Specific rows are deleted if you specify the where clause.
Ex: - DELETE FROM EMP WHRE empid=101;
Note: - If you omit the WHERE clause it deletes all the rows from the table.

SELECT:-
The SELECT statement allows you to retrieve records from one or more tables in your database.
Syntax:-
1. SELECT <attribute list> FROM <table_name>;
2. SELECT <attribute list> FROM <table_name> WHERE <condition>;
3. SELECT * FROM <table_name>;
4. SELECT * FROM <table_name> WHERE <condition>;

Prepared by: Mr.M.Thrilok Reddy Page 15


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Oracle operators

Oracle provides operators for performing various mathematical, comparison and logical operations.
List of Oracle Operators:-
1. Arithmetic (mathematical) operators {+,-,*, /}
2. Logical (Boolean) operators {AND, OR, NOT}
3. (Comparison) operators {<,>, <=,>=, =, != or <>}
4. Special operators {LIKE, IN, IS, BETWEEN}

Mathematical Operators: - are used for performing mathematical operations like addition,
subtraction, multiplication, division etc.
Boolean Operators:-
If we want to check for more than one condition in a single select query then we need to use the
boolean operators
Comparison Operators:-
The operators used to compare the values are called comparison operators.

SQL> create table student


(
sid number(4),
sname varchar2(20),
sub1 number(3),
sub2 number(3),
sub3 number(3)
);
Table created.
SQL> insert into student values(&sid,'&sname',&sub1,&sub2,&sub3);
Enter value for sid: 1201
Enter value for sname: ramana
Enter value for sub1: 75
Enter value for sub2: 65
Enter value for sub3: 34
old 1: insert into student values(&sid,'&sname',&sub1,&sub2,&sub3)
new 1: insert into student values(1201,'ramana',75,65,34)
Prepared by: Mr.M.Thrilok Reddy Page 16
1 row created.

SQL> select * from student;

SID SNAME SUB1 SUB2 SUB3


--------- -------------- ---------- -------- --------
1201 ramana 75 65 34
1202 vibhav 50 75 67
1203 radha 88 28 43
1204 sneha 90 76 54
1205 chaitanya 77 66 55
1206 paparao 88 44 32
1207 naresh 34 45 66

7 rows selected.

SQL> select sid,sname,sub1+sub2+sub3 from student;

SID SNAME SUB1+SUB2+SUB3


---------- -------------------- --------------
1201 ramana 174
1202 vibhav 192
1203 radha 159
1204 sneha 220
1205 chaitanya 198
1206 paparao 164
1207 naresh 145

7 rows selected.

SQL> select sid,sname,sub1+sub2+sub3 as total from student;

SID SNAME TOTAL


---------- -------------------- ----------
1201 ramana 174
1202 vibhav 192
1203 radha 159
1204 sneha 220
1205 chaitanya 198
1206 paparao 164
1207 naresh 145

7 rows selected.

SQL> select sid,sname,sub1+sub2+sub3 as "total" from student;

SID SNAME total


---------- -------------------- ----------
1201 ramana 174

Prepared by: Mr.M.Thrilok Reddy Page 17


1202 vibhav 192
1203 radha 159
1204 sneha 220
1205 chaitanya 198
1206 paparao 164
1207 naresh 145

7 rows selected.

SQL> select sid,sname,sub3,sub3*1.2 as "newsub3" from student;

SID SNAME SUB3 newsub3


---------- -------------------- ---------- ----------
1201 ramana 34 40.8
1202 vibhav 67 80.4
1203 radha 43 51.6
1204 sneha 54 64.8
1205 chaitanya 55 66
1206 paparao 32 38.4
1207 naresh 66 79.2

7 rows selected.

SQL> select sid,sname,sub3,round(sub3*1.2) as "newsub3" from student;

SID SNAME SUB3 newsub3


---------- -------------------- ---------- ----------
1201 ramana 34 41
1202 vibhav 67 80
1203 radha 43 52
1204 sneha 54 65
1205 chaitanya 55 66
1206 paparao 32 38
1207 naresh 66 79

7 rows selected.

SQL> select sid,sname,sub1,sub2,sub3,((sub1+sub2+sub3)/300)*100 as average from


student;

SID SNAME SUB1 SUB2 SUB3 AVERAGE


---------- -------------------- ---------- ---------- ---------- ----------
1201 ramana 75 65 34 58
1202 vibhav 50 75 67 64
1203 radha 88 28 43 53
1204 sneha 90 76 54 73.3333333
1205 chaitanya 77 66 55 66
1206 paparao 88 44 32 54.6666667
1207 naresh 34 45 66 48.3333333

Prepared by: Mr.M.Thrilok Reddy Page 18


7 rows selected.

SQL> select sid,sname,sub1,sub2,sub3,round(((sub1+sub2+sub3)/300)*100) as average from


student;

SID SNAME SUB1 SUB2 SUB3 AVERAGE


---------- -------------------- ---------- ---------- ---------- ----------
1201 ramana 75 65 34 58
1202 vibhav 50 75 67 64
1203 radha 88 28 43 53
1204 sneha 90 76 54 73
1205 chaitanya 77 66 55 66
1206 paparao 88 44 32 55
1207 naresh 34 45 66 48

7 rows selected.

Special Operators:-

Oracle provides some special operators which enhance the capabilities of SQL statements.

IN:- it can be used to compare multiple values.


Ex:-
select * from emp where deptno=10 or deptno=30;
select * from emp where deptno=10,30;(wrong)
select * from emp where deptno=(10,30);(wrong)
select * from emp where deptno IN(10,30);
select * from emp where deptno NOT IN(10,30);

BETWEEN:- Is Used For Checking The Range Of Values

List the employees who salary is between 2000 to 10000


select * from emp where salary>=2000 and salary<=10000;
select * from emp where salary BETWEEN 2000 AND10000;

LIKE:- Is used for pattern matching searches.%,_


% is called wild card character which represents any number or characters including zero
_ used for single character matching
Ex:- select * from emp where ename LIKE ‘%o%E’;

IS operator:- in order to work with against null values.

select * from emp where ename IS null;

Prepared by: Mr.M.Thrilok Reddy Page 19


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Data Retrieval Exp. No: 1

AIM: Write SQL queries for Data Retrieval


a) Write a query to display all columns of cust table.
SQL> select * from cust_table;
b) Write a query to display pname of all records. Sort all records by pname. (use order by
clause)
SQL> select pname from prod_table order by pname;
c) Write a query to display cname and ccity of all records. Sort by ccity in descending order.
SQL> select pname from prod_table order by pname desc;
d) Write a query to display cname, ccity who lives in mysore
SQL> select cname,ccity from cust_table where ccity = 'mysore';
e) Write a query to display cname, pname, sale, saledt for all customers
SQL> Select cname,pname,sale,saledt
From cust_table c,prod_table p,sales_details s
Where s.cid=c.cid and s.pid=p.pid;
f) Write a query to display cname who have purchased Pen.
SQL> select c.cname from cust_table c, prod_table p, sales_details sd
where sd.cid=c.cid and sd.pid=p.pid and p.pname='pen';
g) Write a query to display saledt and total sale on the date labeled as sale of all items sold
after 01-sep-2010
SQL> select saledt,sum(sale) as totalsale from prod_table
where saledt>’01-sep-2010’;
h) Write a query to display saledt and total sale on the date labeled as sale of all items other
than DVD.
SQL> select saledt,sum(sale) as totalsale
from prod_table where pname=’dvd’;
i) Write a query to display cname and ccity of all customers who live in Kolkata or Chennai
SQL> select cname,ccity from cust_table where (ccity in ('kolkata', 'chennai'));

Prepared by: Mr.M.Thrilok Reddy Page 20


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Use of Distinct, between, in clause, like operator, Dual Exp. No: 2

AIM: Write the queries in SQL using Distinct, between, in clause, like operator, Dual.
PROCEDURE:
a) Write a query to display the pname and pcost of all the customers where pcost lies between
5 and 25.
SQL>select pname,pcost from prod_table where pcost between 5 and 25;
b) Find the product ids in sale_detail table(eliminating duplicates).
SQL>select distinct pid from prod_table;
c) Write a query to display distinct customer id where product id is p3 or sale date is ‘18-mar-
2011’.
SQL>select distinct cid from prod_table p,sale_details s where s.pid=p.pid and p.pid=3 or
s.saledt=’18-mar- 2011’;
d) Write a query to display cname, pid and saledt of those customers whose cid is inc1 or c2 or
c4 or c5.

SQL>select cname,pid,saledt from cust_table c,prod_table p,sales_detail s where s.cid=c.cid


and s.pid=p.pid and c.cid in(‘c1’,’c2’,’c4’,’c5’);
e) Write a query to display cname, pid, saledt of those customers whose pid is p3 or sale
date is &#39;20-dec- 2009&#39;.
SQL>select cname,pid,saledt from cust_table c,prod_table
p,sale_detail s where s.cid=c.cid and s.pid=p.pid and
p.pid=’p3’ or p.saledt=’20-dec- 2009’ ;
f) Write a query to display system date.
SQL> select sysdate from dual;
g) Write a query to display all records of prod table in which first and third character of
pname is any character and second character is ‘E’.
SQL>select * from prod_table where pname=’_E_’;

Prepared by: Mr.M.Thrilok Reddy Page 21


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Constraints Exp. No: 3

Aim: Implement table level and Column level constraints like NOT NULL, UNIQUE, PRIMARY
KEY, FOREIGN KEY, CHECK.
Procedure:
 The concept of enforcing business rules into database table is called data integrity.
 Integrity Constraint(IC) is a condition specified on a database schema and restricts the data
that can be stored in an instance of the database.
 If the database instance satisfies all the IC’s specified on the database schema, it is a legal
instance.
 A DBMS enforces integrity constraints, in that it permits only legal instances to be stored in
the database.

SQL CREATE TABLE + CONSTRAINT Syntax

CREATE TABLE table_name


(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);

In SQL, we have the following constraints:

 NOT NULL - Indicates that a column cannot store NULL value


 UNIQUE - Ensures that each row for a column must have a unique value
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column
(or combination of two or more columns) have a unique identity which helps to find a
particular record in a table more easily and quickly

Prepared by: Mr.M.Thrilok Reddy Page 22


 FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in
another table
 CHECK - Ensures that the value in a column meets a specific condition
 DEFAULT - Specifies a default value for a column

Classification of Constraints:-
***************************
Constraints can be broadly classified as:
1. Column level-->constraint is applied to a single column
2. Table level-->constraint is applied to more than one column.
Primary key:-
*************
 It can be defined as the single column or combination of columns which uniquely identify a
row in a table.
Ex:-
SQL> create table student_master
(
rollno number(4) primary key,
name varchar2(20)
);

Table created.
SQL> insert into student_master values(1201,'Amulya');
1 row created.
SQL> insert into student_master values(1202,'Bhanu');
1 row created.
SQL> insert into student_master values(1201,'Vinod');
insert into student_master values(1201,'Vinod')
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C004032) violated
SQL> insert into student_master values(null,'Vinod');
insert into student_master values(null,'Vinod')

ERROR at line 1:
ORA-01400: cannot insert NULL into ("SYSTEM"."STUDENT_MASTER"."ROLLNO")

Prepared by: Mr.M.Thrilok Reddy Page 23


2. Composite Primary Key:-
 When a primary key consists of multiple columns then it is called a Composite Primary Key.
SQL> create table student_master2
(
rollno number(4),
name varchar2(20),
college_code varchar2(20),
primary key(college_code,rollno)
);

SQL> insert into student_master1 values(1206,'Danu','12');


1 row created.
SQL> insert into student_master1 values(1207,'Eswar','12');
1 row created.
SQL> insert into student_master1 values(1207,'Fasiha','12');
insert into student_master1 values(1207,'Fasiha','12')
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C004035) violated
Note:
a table can have only one primary key.

II.NOT NULL
 To restrict null values into column.
Ex:-
SQL> create table staff
(
sid integer,
sname varchar2(20) not null
);
Table created.

SQL> insert into staff values(1,'Guru');


1 row created.
SQL> insert into staff(sid) values(3);
insert into staff(sid) values(3)
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SYSTEM"."STAFF"."SNAME")

Prepared by: Mr.M.Thrilok Reddy Page 24


UNIQUE:-
 Unique constraint column doesn’t allow duplicate values but one NULL value allowed.
Ex:-
SQL> create table staff1
(
sid number(2) unique,
sname varchar2(20)
);
Table created.
SQL> insert into staff1 values(12,'Kumar');
1 row created.
SQL> insert into staff1(sname) values('Vamsi');
1 row created.
SQL> insert into staff1 values(12,'Seetal');
insert into staff1 values(12,'Seetal')
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C004037) violated
testing:-
SQL> select * from staff1;
SID SNAME
---------- --------------------
12 Kumar
Vamsi
SQL> select nvl(sid,2) from staff1;
NVL(SID,2)
----------
12
2
DEFAULT:-
 if we do not specify a value for column in the INSERT statement, then the value specified in
default clause gets inserted.

SQL> create table staff2


(
sid number(2),
sname varchar2(20),
dept_id number(2) DEFAULT 12
);
Table created.

Prepared by: Mr.M.Thrilok Reddy Page 25


SQL> insert into staff2 values(1,'Kumar',11);
1 row created.
SQL> insert into staff2(sid,sname) values(2,'Kumar');
1 row created.
SQL> select * from staff2;
SID SNAME DEPT_ID
-------- ------------ ----------
1 Kumar 11
2 Kumar 12

CHECK:-
 Check constraint used to check the values in a column with user defined conditions.
syntax:-
column_name datatype check(expression)
SQL> create table staff3
(
sid number(2),
sname varchar2(20),
scity varchar2(20) CHECK(scity='tpt' or scity='chennai')
);
Table created.
SQL> insert into staff3 values(1,'Kumar','tpt');
1 row created.

SQL> insert into staff3 values(2,'Prabhas','chennai');


1 row created.
SQL> crea
insert into staff3 values(3,'Vishal','hyd')
ERROR at line 1:
ORA-02290: check constraint (SYSTEM.SYS_C004038) violated
******************************************************************************
i.entity integrity-->can be achived with the help of primary key and unique.
ii.domain integrity--> not null,check,default
iii.referrential integrity-->foreign key

Prepared by: Mr.M.Thrilok Reddy Page 26


Adding,Removing and Altering Constraints:-
-------------------------------------------------------------
1. Adding Constraint in existing table
SQL> desc student;
Name Null? Type
-------------------------------- -------- -------------------
SID NUMBER(4)
SNAME VARCHAR2(20)
SUB1 NUMBER(3)
SUB2 NUMBER(3)
SUB3 NUMBER(3)
SQL> alter table student add primary key(SID);

Table altered.
SQL> desc student;
Name Null? Type
------------------------------- -------------- -------------------------
SID NOT NULL NUMBER(4)
SNAME VARCHAR2(20)
SUB1 NUMBER(3)
SUB2 NUMBER(3)
SUB3 NUMBER(3)

EX2:-
SQL> desc student1;
Name Null? Type
----------------------------------- -------- ---------------------
RNO CHAR(10)
NAME VARCHAR2(25)

SQL> alter table student1 add primary key(rno,name);

Table altered.
SQL> desc student1;
Name Null? Type
----------------------------------- -------- ---------------------
RNO NOT NULL CHAR(10)
NAME NOT NULL VARCHAR2(25)

Note:- to know the constraints on all the tables

SQL>select constraint_name,constraint_type,table_name from user_constraints;

Prepared by: Mr.M.Thrilok Reddy Page 27


2. Removing Constraints:-
*************************
SQL> alter table student drop primary key;
Table altered.
SQL> desc student;
Name Null? Type
---------------------------------- -------- ---------------------
SID NUMBER(4)
SNAME VARCHAR2(20)
SUB1 NUMBER(3)
SUB2 NUMBER(3)
SUB3 NUMBER(3)
Ex:-
SQL> alter table student add constraint myconstaint primary key(sid);
Table altered.
SQL> desc student;
Name Null? Type
------------------------------ -------- ---------------------
SID NOT NULL NUMBER(4)
SNAME VARCHAR2(20)
SUB1 NUMBER(3)
SUB2 NUMBER(3)
SUB3 NUMBER(3)

Disabling and enabling constraints:-


*********************************
SQL> alter table student disable constraint myconstaint;

Table altered.
SQL> desc student;
Name Null? Type
----------------------------------------- -------- ---------------
SID NUMBER(4)
SNAME VARCHAR2(20)
SUB1 NUMBER(3)
SUB2 NUMBER(3)
SUB3 NUMBER(3)

SQL> alter table student enable constraint myconstaint;

Table altered.

Prepared by: Mr.M.Thrilok Reddy Page 28


SQL> desc student;
Name Null? Type
------------------------------ -------- ----------------
SID NOT NULL NUMBER(4)
SNAME VARCHAR2(20)
SUB1 NUMBER(3)
SUB2 NUMBER(3)
SUB3 NUMBER(3)
FOREIGN KEY:-
Foreign key is nothing but a column referencing values from another table primary key column (or)
unique constraint column. By default foreign key column also duplicate values.
Foreign key column data type should be same as primary key column.
Syntax:-
create table parenttable
(
did number(2) primary key,
dname varchar2(23)
);

create table childtable


(
sid number(2) primary key,
sname varchar2(20),
did number(2) references parenttable(did)
);

create table childtable


(
sid number(2) primary key,
sname varchar2(20),
foreign key(did) references parenttable(did)
);

Lab Program:

SQL> create table state_name1


(
ccity varchar2(8) primary key,
state varchar2(15)
);
Table created.
SQL> create table cust_table1
(
cid varchar2(6) primary key,
cname varchar2(10),
ccity varchar2(8) references state_name1(ccity)

Prepared by: Mr.M.Thrilok Reddy Page 29


);
Table created.
SQL> create table prod_table1
(
pid varchar2(6) primary key,
pname varchar2(10),
pcost number(4,2),
profit number(3)
);
Table created.
SQL> create table sales_details1
(
cid varchar2(6) references cust_table1(cid),
pid varchar2(6) references prod_table1(pid),
sale number(3),
saledt date,
primary key(cid,pid,saledt)
);
Table created.

SQL> desc state_name1;


Name Null? Type
----------------------- ----------------- -------- ----------------------------
CCITY NOT NULL VARCHAR2(8)
STATE VARCHAR2(15)

SQL> desc cust_table1;


Name Null? Type
---------------------- ---------------- -------- ----------------------------
CID NOT NULL VARCHAR2(6)
CNAME VARCHAR2(10)
CCITY VARCHAR2(8)

SQL> desc prod_table1;


Name Null? Type
----------------------------------------- -------- ----------------------------
PID NOT NULL VARCHAR2(6)
PNAME VARCHAR2(10)
PCOST NUMBER(4,2)
PROFIT NUMBER(3)

SQL> desc sales_details;


Name Null? Type
----------------------------------------- -------- ----------------------------
CID NOT NULL VARCHAR2(6)
PID NOT NULL VARCHAR2(6)
SALE NUMBER(3)
SALEDT NOT NULL DATE

Prepared by: Mr.M.Thrilok Reddy Page 30


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Single Row Functions: DATE Function Exp. No: 4

AIM: Write SQL queries using DATE Function

PROCEDURE:

LAB PROGRAMS:

a) Write a query to display the system date by rounding it to next month


SQL> select sysdate,round(sysdate,'month') from dual;

b) Write a query to display the system date by rounding it to next year.


SQL> select sysdate,round(sysdate,'year') from dual;

c) Write a query to display the last date of the system date


SQL> select sysdate,last_day(sysdate) from dual;

d) Write a query to display the next date of system date which is Friday.
SQL> select sysdate,next_day(sysdate,'friday') from dual;

e) Write a query to display sale date and date after 02 months from sale date
SQL> select saledt,add_months(saledt,2) from sales_details;

f) Write a query to display system date, sale date and months between two dates.
SQL> select saledt,add_months(saledt,2) from sales_details;

g) Write a query to display the greatest date between sale date and system date, name it as
BIG, also display sale date and SYSDATE..
select sysdate,saledt,months_between(sysdate,saledt) from sales_details;

h) Write a query to display the least date between sale date and system date name it as
SMALL, also display sale date and SYSDATE.
SQL> select saledt,sysdate,greatest(saledt,sysdate) as big from sales_details;

Prepared by: Mr.M.Thrilok Reddy Page 31


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Single Row Functions: Numeric and Character Function Exp. No: 5

AIM: Write SQL queries using Numeric and Character Functions

PROCEDURE:

a) Write a query to display the product name along with the rounded value of product cost
for product name is "pencil".
SQL> select pname,round(pcost) from prod_table where pname='pencil';
b) Write a query to display product cost along with MOD value if divided by 5.
SQL> select mod(pcost,5) from prod_table;
c) Write a query to display cname in uppercase,lowercase,titlecase from cust table where
customer name is "rohan".
SQL> select upper(cname),lower(cname),initcap(cname) from cust_table where cname
='rohan';
d) Write a query to display all concatenated value of cname,ccity by converting cname into
titlecase and ccity into uppercase.
SQL> select concat(upper(cname),initcap(ccity)) from cust_table;
e) Write a query to display the first 3 characters of cname.
SQL> select substr(cname,1,3) from cust_table;
f) Write a query to display the position of 'M' in the cname of the customer whose name is
"SAMHITHA".
SQL> select instr(cname,'M',1) from cust_table where cname='SAMHITHA';
g) Write a query to display the length of all customer names
SQL> select length(cname) from cust_table;
h) PAD # character in left of product cost to a total width of 5 character position.
SQL> select lpad(pcost,5,'#') from prod_table;

Prepared by: Mr.M.Thrilok Reddy Page 32


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Group Functions and SET Functions Exp. No: 6

AIM: Write SQL queries using Group and Set Functions

a) Write a query to display the total count of customer.


SQL> select count(cid) from cust_table;
b) Write a query to display the minimum cost of product.
SQL> select min(pcost) from prod_table;
c) Write a query to display average value of product cost rounded to 2nd decimal places.
SQL> select round(avg(pcost),2) from prod_table;
d) Write a query to display product name with total sale detail in descending order.
SQL> select p.pname,sum(s.sale)
from sales_details s,prod_table p
where s.pid=p.pid group by p.pname order by p.pname desc;
e) Write a query to display product name, sale date and total amount collected for the
product.
SQL> select p.pname,s.saledt,sum(sale) as "total sale"
from sales_details s s,prod_table p
where p.pid=s.pid group by p.pname,s.saledt;
f) Write a query to display sale date and total sale date wise which was sold after "14-jul-08".
SQL> select saledt,sum(s.sale) as "total sale"
from sales_details s
group by saledt
having saledt>'14-jul-08';
g) Write a query to display the customer name who belongs to those places whose name is
having I or P.
SQL> select cname,ccity from cust_table where cname like '%P%'
UNION
select cname,ccity from cust_table where cname like '%I%';

Prepared by: Mr.M.Thrilok Reddy Page 33


h) Write a query to display customer name who belongs to a city whose name contains
characters 'C' and whose name contains character 'A'.

SQL> select cname,ccity


from cust_table
where cname like '%A%'

INTERSECT
select cname,ccity
from cust_table
where cname like '%C%';

i) Write a query to display the customer name who does not belong to PUNE
SQL> select cname,ccity
from cust_table

MINUS

select cname,ccity
from cust_table
where ccity='PUNE';

Prepared by: Mr.M.Thrilok Reddy Page 34


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: PL/SQL basic programs Exp. No: 7

AIM:
a) Write a PL/SQL program to find largest number among three. (Hint: Use Conditional
Statement)
b) Write a PL/SQL program to display the sum of numbers from 1 to N using for loop, loop…
end and while…loop.
PROCEDURE:
Introduction PL/SQL
 PL/SQL stands for Procedural SQL.
 PL/SQL is the extension to SQL with design features of programming languages.
 Data manipulation and query statements of SQL are included within procedural units of code.
Drawbacks of SQL
 SQL does not have procedural capabilities such as Conditional, Looping & branching
statements etc.
 All SQL statements are passed to Oracle DB Engine one at a time for compilation &
execution.
 SQL displays its own built-in error messages but PL/SQL can assign our own error
messages.
Advantages of PL/SQL
 Procedural concepts like conditional, looping & branching statements.
 Embedded SQL: Allows SQL statements within a PL/SQL program.
 Declare variables within PL/SQL blocks & use them for intermediate calculations.
 A block structured language so that entire block of statements are passed to Oracle Engine
for compilation & execution.
 Allows to define own error messages than built-in error messages
 Modularize program development & portable.
 Easy maintenance & Improved data security and integrity
 Improved performance & Improved code clarity

Prepared by: Mr.M.Thrilok Reddy Page 35


Structure of PL/SQL Block
PL/SQL programs are structured in blocks and have the following format:
DECLARE
variable_declarations
BEGIN
procedural_code
EXCEPTION
error_handling
END;
 Declare: variables & constants are declared and initialize them with values.
 Begin: All PL/SQL statements with programming logic includes conditional statements like
If…Else, Looping statements like For, While & branching statements like GOTO &
calculations.
 Exception: handles errors generated on execution of PL/SQL statements due to syntax,
logical, failure of validation rules.
 Begin & End are compulsory sections
 Declare & Exception are optional sections.
Sample Program
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN dbms_output.put_line(message);
END;
/
 The end; line signals the end of the PL/SQL block.
 To run the code from the SQL command line, you may need to type / at the beginning of the
first blank line after the last line of the code.
 When the above code is executed at the SQL prompt, it produces the following result −
Hello World
PL/SQL procedure successfully completed.
PL/SQL Comments
 The PL/SQL supports single-line and multi-line comments. All characters available inside
any comment are ignored by the PL/SQL compiler.

Prepared by: Mr.M.Thrilok Reddy Page 36


 The PL/SQL single-line comments start with the delimiter -- (double hyphen) and multi-line
comments are enclosed by /* and */.
Example
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/* PL/SQL executable statement(s) */ dbms_output.put_line(message);
END;
/
Variable Declaration in PL/SQL
 The syntax for declaring a variable is −
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
Eg:
sales number(10, 2);
pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);
Initializing Variables in PL/SQL
Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you want to
initialize a variable with a value other than the NULL value, you can do so during the declaration,
using either of the following
 The DEFAULT keyword
 The assignment operator
For example −
 counter binary_integer := 0;
 greetings varchar2(20) DEFAULT 'Have a Good Day';

a) Write a PL/SQL program to find largest number among three. (Hint: Use Conditional
Statement)
declare
a number(3);
b number(3);

Prepared by: Mr.M.Thrilok Reddy Page 37


c number(3);
begin
a:=&a;
b:=&b;
c:=&c;
if (a>b) and (a>c) then
dbms_output.put_line('greater is:'||a);
else if (b>a) and (b>c) then
dbms_output.put_line('greater is:'||b);
else
dbms_output.put_line('greater is:'||c);
end if;
end if;
end;
/
Enter value for a : 200
Enter value for b : 400
Enter value for c : 250
greater is : 400
PL/SQL procedure successfully completed.
b) Write a PL/SQL program to display the sum of numbers from 1 to N using for loop, loop…
end and while…loop.
i) Simple loop.
declare
i number(3);
n number(3);
total number(3);
begin
i:=0;
n:=&n;
total:=0;
loop
total:=total+i;

Prepared by: Mr.M.Thrilok Reddy Page 38


i:=i+1;
exit when i>n;
end loop;
dbms_output.put_line('sum is:'||total);
end;
/
Enter value for n : 5
Sum is: 15
PL/SQL procedure successfully completed.
ii) for loop
declare
i number(3);
n number(3);
total number(3);
begin
i:=1;
n:=&n;
total:=0;
for i in 1..n loop
total:=total+i;
end loop;
dbms_output.put_line('sum is:'||total);
end;
/
Enter value for n : 5
sum is:15
PL/SQL procedure successfully completed.
iii) while loop
SQL> declare
i number(3);
n number(3);
total number(3);
begin

Prepared by: Mr.M.Thrilok Reddy Page 39


i:=1;
n:=&n;
total:=0;
while (i<=n) loop
total:=total+i;
i:=i+1;
end loop;
dbms_output.put_line('sum is:'||total);
end;
/
Enter value for n : 10
sum is: 55
PL/SQL procedure successfully completed.

Prepared by: Mr.M.Thrilok Reddy Page 40


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: SQL Cursor based programs Exp. No: 8

AIM:
a) Write a PL/SQL program to display the costliest and cheapest product in PROD table.
b) Write a PL/SQL program which will accept PID and display PID and its total sale value
i.e. sum.
a) SQL> declare
cursor minmaxc is
select min(pcost),max(pcost) from product2;
minc number(3);
maxc number(3);
begin
open minmaxc;
fetch minmaxc into minc,maxc;
dbms_output.put_line('minimum cost is:'||minc);
dbms_output.put_line('maximum cost is:'||maxc);
close minmaxc;
end;
/
minimum cost is:3
maximum cost is:51

PL/SQL procedure successfully completed.

Prepared by: Mr.M.Thrilok Reddy Page 41


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Functions Exp. No: 9

AIM:
a) Write a function that accepts two numbers A and B and performs the following operations.
i. Addition ii. Subtraction iii. Multiplication iv. Division
b) Write a function that accepts to find the maximum PCOST in PROD table.
PROCEDURE:
 Stored functions are logically grouped PL/SQL statements used to perform a specific task.
 PL/SQL blocks that take parameters & perform some action & return a single value to the
calling program.
 Components:
• Declarative section (Declare the variables & constants)
• Executable section (PL/SQL statements perform a specific task)
• Exception handling section (errors can handle in this section)
 Eg: create or replace function function_name
return data_type is
/*local variables declaration*/
Begin
PL/SQL Statements;
………….
exception
PL/SQL Statements handling errors
End;
/
 The local variable declaration is not preceded by DECALRE section.
//*A function to calculate cube of a given number*//
Eg: create or replace function fn_cube(p int)
return int is
y number;
begin
Prepared by: Mr.M.Thrilok Reddy Page 42
y:=p*p*p; return y;
end;
/
//*calling a function using SELECT statement *//
 Select fn_cube(4) from dual; (Ans: 64)
 Declare //* calling a function within a PL/SQL program to find volume of a cube*//
side number: = &side;
vol number;
Begin
vol : = fn_cube(side);
dbms_output.put_line ('vol is‘ || vol);
End;
/
a) Write a function that accepts two numbers A and B and performs the following operations.
i. Addition ii. Subtraction iii. Multiplication iv. Division

SQL> create or replace function add_two( a int, b int)


return int is
c number;
begin
c:=a+b;
return c;
end;
/
Function created.
SQL> select add_two(12,13) from dual;
ADD_TWO(12,13)
--------------
25
SQL> create or replace function sub_two( a int, b int)
return int is
c number;
begin
c:=a-b;

Prepared by: Mr.M.Thrilok Reddy Page 43


return c;
end;
/
Function created.
SQL> select sub_two(25,12) from dual;
SUB_TWO(25,12)
--------------
13
SQL> create or replace function mul_two( a int, b int)
return int is
c number;
begin
c:=a*b;
return c;
end;
/
Function created.
SQL> select mul_two(6,21) from dual;
MUL_TWO(6,21)
-------------
126
SQL> create or replace function div_two( a int, b int)
return int is
c number;
begin
c:=a/b;
return c;
end;
/
Function created.
SQL> select div_two(12,2) from dual;
DIV_TWO(12,2)
-------------
6
b) Write a function that accepts to find the maximum PCOST in PROD table.

Prepared by: Mr.M.Thrilok Reddy Page 44


SQL> create or replace function max_pcost
return number is
z number:=0;
begin
select max(pcost) into z from product2;
return z;
end;
/
Function created.
SQL> declare
c int:=0;
begin
c:=max_pcost;
dbms_output.put_line('max pcost is'||c);
end;
/
max pcost is20

PL/SQL procedure successfully completed.

Prepared by: Mr.M.Thrilok Reddy Page 45


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Procedures n Exp. No: 10

AIM :
a) Write a procedure that accepts two numbers A and B, add them and print
b) Write procedures to demonstrate IN, IN OUT and OUT parameter.

PROCEDURE:
 A procedure is a logically grouped set of SQL & PL/SQL statements that perform a specific
task.
 A PL/SQL block that is compiled & stored into the database.
 Oracle stores both the source code & compiled code of procedures in database so they are
called “stored procedures”.
 Components:
• Declarative Section (Declare the variables & constants)
• Executable Section (PL/SQL statements perform specific task)
• Exception Handling Section (Errors can handle in this section)
Advantages
 Modular programming – Break a large program into smaller, manageable units.
 Reusable – Different users can use same procedures repeatedly.
 Improve Database Security – users access data through stored procedures only.
 Performance – Oracle keeps compiled code for procedures which improves performance.

Syntax for procedural declaration


create or replace procedure procedure_name (parameters) is
/*local variables declaration*/
Begin
PL/SQL Statements;
………….
Exception

Prepared by: Mr.M.Thrilok Reddy Page 46


PL/SQL Statements handling errors
End;
/
Compiling & Executing a Procedure
 Compilation:
SQL> @procedure1
Procedure created.
 Execution: use “exec” to execute the procedure.
SQL> exec disp_ab(15,25);
output: a+b = 40
PL/SQL procedure successfully completed. (or)
SQL> call disp_ab(15,25);
a+b=:40
Call completed.
Parameter Passing
 There are 3 modes in which a parameter can be passed from a calling program to called
program namely IN, OUT & IN OUT.
 IN Mode: - a default mode of parameter passing.
- pass a value from calling program to IN parameter of called pgm
- it can’t be assigned a value within the called program.
 OUT Mode:
 Used to return value from the called program to calling program.
 Must be assigned some value within the called program.
 The calling program must pass a variable name for OUT parameter.
 IN OUT Mode:
 Pass values from the calling program to called program & at the same time called
program should return value then use IN OUT .
 IN -> passing by value & OUT-> pass by reference.
a) Write a procedure that accepts two numbers A and B, add them and print

create or replace procedure disp_ab(a int, b int) is


begin
dbms_output.put_line('a+b=:‘ || (a+b));
end;
Prepared by: Mr.M.Thrilok Reddy Page 47
b) Write procedures to demonstrate IN, IN OUT and OUT parameter.
IN mode:-
SQL> create or replace procedure disp_ab(a IN int ,b IN int)
is
begin
dbms_output.put_line('a+b:='||(a+b));
end;
/
Procedure created.
SQL> exec disp_ab(15,25);
a+b:=40
PL/SQL procedure successfully completed.
OUT mode:-
SQL> create or replace procedure grt_ab(a int,b int,c out int) is
begin
if a>b then
dbms_output.put_line('a is greater :='||a);
else
dbms_output.put_line('b is greater :='||b);
end if;
end;
/
Procedure created.
SQL> declare
c int;
begin
grt_ab(15,23,c);
end;
/
b is greater :=23
PL/SQL procedure successfully completed.

Prepared by: Mr.M.Thrilok Reddy Page 48


INOUT mode:-
SQL> create or replace procedure doublen(n IN OUT int)
is
begin
n:=n*2;
end;
/
Procedure created.
SQL> declare
r int;
begin
r:=4;
doublen(r);
dbms_output.put_line('doubed value of r is'||r);
end;
/
doubed value of r is8

Prepared by: Mr.M.Thrilok Reddy Page 49


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Triggers Exp. No: 11

AIM :
a) Develop a PL/SQL program using BEFORE and AFTER triggers.
b) Create a row level trigger for the PROD table that would fire for INSERT or UPDATE or
DELETE operations performed on the PROD table. This trigger will display the profit
difference between the old values and new values.

PROCEDURE:
a) Develop a PL/SQL program using BEFORE and AFTER triggers.

AFTER TRIGGER:-
SQL> create table audit_cust1
(
tablename varchar2(20),
dml_operation varchar2(20),
day date
);
Table created.
SQL> create or replace trigger audit_cust1
after insert or update or delete
on cust_table
begin
if inserting then
insert into audit_cust1 values('cust_table','insert',sysdate);
end if;
if updating then
insert into audit_cust1 values('cust_table ','update',sysdate);
end if;
if deleting then

Prepared by: Mr.M.Thrilok Reddy Page 50


insert into audit_cust1 values('cust_table ','delete',sysdate);
end if;
end;
/
Trigger created.

SQL> insert into cust_table values('c23','sree','hyd');


1 row created.
SQL> update cust_table
set ccity='mysore'
where cid='c23';
1 row updated.
SQL> delete from cust_table where cid='c13';
1 row deleted.
SQL> select * from audit_cust1;
TABLENAME DML_OPERATION DAY
-------------------- -------------------- ---------
cust_table insert 21-MAR-17
cust_table update 21-MAR-17
cust_table delete 21-MAR-17

BEFORE TRIGGER:-
SQL> create or replace trigger emp_sal_gt_comm
before insert or update
on employee
for each row
begin
if inserting then
if :new.salary<:new.commission then
raise_application_error('-20000','INSERT ERROR:cannot insert
commission greater than salary');
end if;
end if;

Prepared by: Mr.M.Thrilok Reddy Page 51


if updating then
if :new.salary<:new.commission then
raise_application_error('-20000','UPDATE ERROR:cannot insert
commission greater than salary');
end if;
end if;
end;
/
Trigger created.

SQL> insert into employee values(105,'satish',8000,2000);


1 row created.

SQL> insert into employee values(106,'PeterRob',2000,8000);


insert into employee values(106,'PeterRob',2000,8000)
*
ERROR at line 1:
ORA-20000: INSERT ERROR:cannot insert commission greater than salary
ORA-06512: at "SYSTEM.EMP_SAL_GT_COMM", line 4
ORA-04088: error during execution of trigger 'SYSTEM.EMP_SAL_GT_COMM'

SQL> update employee set salary=3000 where empid=105;


1 row updated.

SQL> update employee set salary=1000 where empid=105;


update employee set salary=1000 where empid=105
*
ERROR at line 1:
ORA-20000: UPDATE ERROR:cannot insert commission greater than salary
ORA-06512: at "SYSTEM.EMP_SAL_GT_COMM", line 9
ORA-04088: error during execution of trigger 'SYSTEM.EMP_SAL_GT_COMM'

Prepared by: Mr.M.Thrilok Reddy Page 52


b) Create a row level trigger for the PROD table that would fire for INSERT or UPDATE or
DELETE operations performed on the PROD table. This trigger will display the profit
difference between the old values and new values.

create or replace trigger prod_trg


after insert or update or delete
on prod_table
for each row
declare
profit_diff number;
begin
if inserting then
dbms_output.put_line('row inserted');
end if;
if deleting then
dbms_output.put_line('row deleted');
end if;
if updating then
profit_diff:=:new.profit-:old.profit;
dbms_output.put_line('difference is:'||profit_diff);
end if;
end;
/

SQL> insert into prod_table values('p11','mobile',10,7);


row inserted
1 row created.
SQL> update prod_table set profit=7 where pid='p3';
difference is:6
1 row updated.
SQL> delete from prod_table where pid='p11';
row deleted
1 row deleted.

Prepared by: Mr.M.Thrilok Reddy Page 53


SREE VIDYANIKETHAN ENGINEERING COLLEGE
Sree Sainath Nagar, A. Rangampet – 517 102
Department of Information Technology
II B. Tech – II Semester
Database Management Systems Lab

Title: Implicit and Explicit Cursors Exp. No: 12

AIM: Declare a cursor that defines a result set. Open the cursor to establish the result set. Fetch the
data into local variables as needed from the cursor, one row at a time. Close the cursor when done.
SQL> DECLARE
l_total ITEGER := 10000;
CURSOR employee_id_cur
IS
SELECT employee_id
FROM employees
ORDER BY salary ASC;
l_employee_id employee_id_cur%ROWTYPE;
BEGIN
OPEN employee_id_cur;
LOOP
FETCH employee_id_cur INTO l_employee_id;
EXIT WHEN employee_id_cur%NOTFOUND;
assign_bonus (l_employee_id, l_total);
EXIT WHEN l_total <= 0;
END LOOP;
CLOSE employees_cur;
END;
/

Prepared by: Mr.M.Thrilok Reddy Page 54

You might also like