DBMS Lab Manual(Final)
DBMS Lab Manual(Final)
SYSTEMS
LAB MANUAL (14BT40521)
MR.M.THRILOK REDDY
ASST.PROFESSOR
DEPT.OF IT
SVEC
&
MS.E.SANDHYA
ASST.PROFESSOR
DEPT.OF IT
SVEC
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:
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.
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 .
3. Constraints
Implement table level and Column level constraints like NOT NULL, UNIQUE, PRIMARY KEY,
FOREIGN KEY, CHECK.
a) Write a query to display the product name along with the rounded value of product cost for
product name is "Pencil".
9. Functions
a) Write a function that accepts two numbers A and B and performs the following operations.
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.
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.
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.
Transaction Control Language (TCL) - These SQL commands are used for managing changes
affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.
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
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
DML COMMANDS:-
Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving,
modifying, and deleting data.
OBJECTIVES:-
Describe each DML statement
Insert rows into a table
Update rows in a table
Delete rows from a 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>;
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.
7 rows selected.
7 rows selected.
7 rows selected.
7 rows selected.
7 rows selected.
7 rows selected.
7 rows selected.
Special Operators:-
Oracle provides some special operators which enhance the capabilities of SQL statements.
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.
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.
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")
II.NOT NULL
To restrict null values into column.
Ex:-
SQL> create table staff
(
sid integer,
sname varchar2(20) not null
);
Table created.
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.
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)
Table altered.
SQL> desc student1;
Name Null? Type
----------------------------------- -------- ---------------------
RNO NOT NULL CHAR(10)
NAME NOT NULL VARCHAR2(25)
Table altered.
SQL> desc student;
Name Null? Type
----------------------------------------- -------- ---------------
SID NUMBER(4)
SNAME VARCHAR2(20)
SUB1 NUMBER(3)
SUB2 NUMBER(3)
SUB3 NUMBER(3)
Table altered.
Lab Program:
PROCEDURE:
LAB PROGRAMS:
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;
Title: Single Row Functions: Numeric and Character Function Exp. No: 5
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;
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';
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
a) Write a PL/SQL program to find largest number among three. (Hint: Use Conditional
Statement)
declare
a number(3);
b number(3);
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
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
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.
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
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;
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;
/