DBMS Lab R19
DBMS Lab R19
TECHNOLOGY
LABORATORY MANUAL
OF
DATABASE MANAGEMENT SYSTEM LAB
FOR
II B.Tech CSE
Prepared by
D.RATHNA KUMARI
Assis Professor
Dbms lab
Step1: create user with oracle database
Creation, altering and droping of tables and inserting rows into a tables(use
constraints while creating tables) examples using SELECT command.
Column_name datatype(width),
Column_name datatype(width),
Column_name datatype(width)
);
Stuid int,
Stuname varchar2(10),
Stusection varchar2(5),
Dob varchar2(10),
Gender varchar2(5)
);
Output:
Insert command:
1) Conventional insert
2) Direct_path insert
• The order of values declared in the values clause should follow thw original
order of the columns in table.
• The char, varchar and date datatype should be declared in single qouts.
Example:
Output:
Example:
Output:
Syntax:
Example:
Syntax:
Example:
SQL>desc student;
Altering:
Case1: adding
Example:
Example:
Case3:drop
When we want to delete a certain column of a table we need to use drop command.
Syntax:
Example:
The update statement is used to change the existing value in a table. Update object
privilege should be available.
Update tablename
Where clause;
Example:
Update student
Set phone=1234567890
Where stuid=501;
Output:
Case5: delete command
Syntax:
Where condition/clause;
Example:
Where stuid=502;
Output:
Experiment-2
EXCERCISE-2: Queries (along with sub Queries) using ANY, ALL, IN, EXISTS,
NOTEXISTS, UNION, INTERSECT, Constraints. Example:- select the roll no and
name of the student who secured fourth rank in the class.
AIM : Queries (along with sub Queries) using UNION,UION ALL,INTERSECT,ANY, ALL,
IN,NOT IN , EXISTS, NOT EXISTS.
Constraints: SQL constraints are rules used to limit the type of data that can go into a
table, to maintain the accuracy and integrity of the data inside table.
• A sub query or inner query or a nested query is a query within another SQL query
and embeddd within the “where” clause.
• A sub query is used to return data that will be used in the main query as a
condition to further restrict the data to be retrived.
• Sub query must be enclosed within parameters.
• Constraints can be divided into two types
1) column level constraints (limits only column data)
2) table level constraints (limits whole table data)
Following are the most used constraints that can be applied to a table
• NOT NULL
• UNIQUE
• Primary key
• Foreign key
• Check
• Default
✓ A Unique constraints field cannot have any duplicate data.
✓ Primary key constraints uniquely identifies each record in a database.
✓ Primary key must contain unique value and it must not contain null value.
✓ Foreign key is used to relate two tables.
✓ The relationship between the two tables matches the primary key in one of the
tables with a foreign key in the second table. Foreign key is also called a
referencing key.
✓ Check constraint is used to restrict the value of a column between a range. It
performs check on the values, before storing them into the database.
✓ A Subquery or Inner query or Nested query is a query within another SQL
query and embedded within the WHERE clause. A subquery is used to return
data that will be used in the main query as a condition to further restrict the data
to be retrieved. Subqueries can be used with the SELECT, INSERT, UPDATE,
and DELETE statements along with the operators like =, <, >,>=, <=, IN,
BETWEEN etc.
Syntax for creation of table:
Create table tablename(
Column_name datatype(width),
Column_name datatype(with),
Column_name datatype(width)
);
Table1:
Create table stu(
Sid int primary key,
Sname varchar2(15),
Address varchar2(15),
Phone int,
Grade varchar2(5)
);
Select column_name
From tablename
Where condition;
Example:
Select cid
From course
Where rank=4;
example:
select sname from stu where sid>ALL(
select sid from course
where rank=4);
IN operator and EXISTS:
• The IN operator is typically used to filter a column for a certain list of values. You
can also use the IN operator to search the values in the result set of a sub query.
• If you have a small list of static values then IN operator is preferred. If you need
to check for existence of values in another table ,EXISTS operator is preferred.
Example for IN:
Select sname,sid from stu where sid IN(
Select sid from course
Where rank=4);
UNION:
✓ Records in query one + records in query two, to form a single set of records.
Syntax for UNION:
SELECT column_name from tablename1 UNION
SELECT column_name from tablename2;
Example:
Select sname from stu
UNION
Select cname from course;
Output:
Syntax for UNION by using where condition:
Select sname from stu s, course c
Where s.sid=c.sid AND c.came=’dbms’
UNION
Select sname from stu s, course c
Where s.sid=c.sid AND c.rank=3;
INTERSECT:
✓ A single set of records which are common in both queries.
Syntax:
SELECT column_name from tablename1 INTERSECT
SELECT column_name from tablename2;
EXAMPLE:
Select sid from stu
INTERSECT
select sid from course;
Syntax for intersect by using where condition:
Output:
EXPERIMENT-3
Greatest: It returns the greatest expression among the given strings or given
numeric values or specified column.
Syntax:
Greatest(expression/value column_name)
Example:
Select greatest(‘oracle’, ’production’) from dual;
Output:
Least: It returns the least expression among the given strings or given numeric
value or specified columns.
Syntax:
Least( expression/value column_name)
Example:
Select least(‘oracle’, ‘production’) from dual;
Output:
Sorting of data in table:
Syntax:
Select column_name, column_name
From table
Order by column;
Example:
Select ename,job
From emp3
Order by ename;
Output:
GROUP BY:
Grouping data from tables:
• There are circumstances where we would like to apply the aggregate
function not only to a single set of tuples, but also to a group of sets of
tuples, we specify this wish in SQL using the group by clause.
• The attribute given in the group by clause are used to form group. Tuple
with the same value on all attributes in the group by clause are placed in
one group.
• The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN,
• SUM, AVG) to group the result-set by one or more columns.
Syntax:
SELECT column_name1,column_name2
FROM tablename
GROUP BY column_name;
OR
SYNTAX:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Example:
Select deptno,sum(sal)
From emp3
GROUP BY deptno;
Output:
HAVING:
The GROUP BY statement is often used with aggregate functions and he
HAVING clause was added to SQL because the WHERE keyword could not be
used with aggregate functions.
Syntax:
SELECT column_name, column_name
FROM tablename
GROUP BY column_name;
HAVING search condition;
Example:
Select deptno,sum(sal)
From emp3
GROUP BY deptno
HAVING sum(sal)>5000;
output:
VIEWs:
Views are masks placed upon tables. This allows the programmer to develop a
method via which we can display pre determined data to users according to our
desire.
Vies may be created for the following reasons:
1. The DBA stores the views as a definition only. Hence there is no
duplication of data.
2. Simplifies Queries.
3. Can be Queried as a base table itself.
4. Provide data security.
5. Avoids data redundancy.
Creation of views:
✓ Create table st (sid int,sname varchar(10));
EXAMPLE:
1) Create view student3 as Select
Sid “ID ”,
Sname name
From st;
Output:
Destroying a view:
Syntax:
DROP VIEW viewname;
Example:
UPDATE VIEW: You can modify the definition of an Oracle VIEW without
dropping it by using the Oracle CREATE OR REPLACE VIEW Statement.
Update a View, Update command for view is same as for tables.
Syntax to Update a View :
UPDATE view-name set value WHERE condition;
Experiment 4
4)Queries using Conversion functions (to_char,to_number and
to_date),stringfunctions(Concatenation, lpad, rpad, ltrim, rtrim,
lower,upper, initcap, length, substr and instr), datefunctions (Sysdate,
next_day, add_months,last_day, months_between, least, greatest,
trunc,round, to_char, to_date)
Conversion functions:
To_char: It returns a character having the ASCII equivalent to n.
Syntax: Chr(n)
Example: select chr(67) from dual;
Output:
ASCII FUNCTION: It returns the ascii represetation of the first character in the given
string.
SYNTAX: ASCII(‘CHAR’/’STRING’)
EXAMPLE: select ascii(‘apple’) from dual;
Output:
Number functions: These functions accept numeric input and return numeric values as
output.
To_ number: select to_number(‘234.87’) from dual;
1) Round function:
✓ Select 15.9 num1,round(15.9) rounded from dual;
2) Truncated function:
Select 15.79 num1, trunc(15.79,1) truncated from dual;
3) Ceil feunction:
Select 15.79 num1,ceil(15.79) ceiled from dual;
4) Floor function:
Select 15.79 num1,floor(15.79) floor from dual;
5) Modulas function:
Select mod(14,4) modulas from dual;
6) Power function:
Select power(2,4) power from dual;
8) Absolute function:
select abs(-125)absolute from dual;
Working with dates:
Write a query to display todays date
1)select sysdate from dual;
Example:
Select ’oracle’ string1, ‘corporations’ string, concat(‘racle’,’corporation’)concat from dual;
✓ select concat(‘rathna’ ‘kumari’) from dual;
2)LPAD FUNCTION: It pads the character value right justified to a total width of ‘n’
character positions. the default padding character is space.
Syntax: lapd( string1, paddedlength,padstring) from dual;
Example: select lpad(empno,10,’*’) from emp3;
Output:
3)RPAD: This is also called as right padding. this function pads the right side of a string
with a specific set of characters. The default padding character is space
Syntax: Rpad(string1,paddedlength,padstring) from tablename;
(OR)
Rpad(string/column,n,’char’)
Example: select rpad(empno,10,’*’) from emp3;
Output:
5)RTRIM: This function removes ending character from the given string.
Syntax: select trim(trimcharacter from string) from dual;
Example: select trim (‘a’ from ‘rama’) from dual;
Output:
8)INITCAP: This function sets the first character in each word to uppercase.
Syntax: select initcap(string) from dual;
Example: select initcap(‘rathna’) from dual;
Output:
2)Next day: This function returns the first weekdat that is greater than a date.
Syntax: select next_day(date,weekday)
Example: select next_day(sysdate,’wednesday’,as next_Wednesday from dual;
Output:
3)Add_month: This function returns a date with a specified number of months added.
Syntax: add_months(date,number of months)
Example: select add_months(sysdate,-1)as prev_month from dual;
Output:
4)Last_day: This function returns the last day of month for a given date.
Syntax: last_day(date_value)
Example: last_day(’14-jun-2017’) as last_day from dual;
5)Months_between: This function returns the number of months between date1 and date2.
Syntax : select lmonths_between(date1,date2) from dual;
example: select months_between(’31-jul-2017’,’28-feb-2017’) from dual;
10)to_char:
Example: select to_char(sysdate,’month dd yyy’) from dual;
11)to_date:
Example: select to_date(‘jan 21 1998’,’month dd yy’) from dual;
Experiment-5
Program:
set serveroutput on
declare
c_sis number;
c_sname varchar2(10);
cuesor c_class is select sis,sname from class where sclass=’first’;
begin
open c_class;
loop
fetch c_class into c_sis,c_sname;
exit when c_class%notfound;
dbms_output.put_line(‘student_id: ‘||c_sis|| ‘student_name: ‘||c_sname);
end loop;
close c_class;
end;
/
Output:
Exercise 5b: TCL command
AIM: Insert data into student table and use COMMIT, ROLLBACK and
SAVEPOINT in PL/SQL Block.
Description: Transaction Control Language (TCL) commands are used to
manage transactions in database. These are used to manage the changes made
by DML statements. There are following commands used to control transactions
Commit
Rollback
Savepoint
• If the condition is true, the statements run; otherwise, the IF statement does nothing.
• The IF THEN ELSIF statement runs the first statements for which condition is true.
Remaining conditions are not evaluated. If no condition is true, the else_statements
run, if they exist; otherwise, the IF THEN ELSIF statement does nothing.
Example with output: finding a leap year?
sql>declare
year number:=&year;
begin
if mod(year,4)=0 then
if mod(year,100)<>0 then
dbms_output.put_line(year|| ‘is a leap year’);
else
if mod(year,400)=0 then
dbms_output.put_line(year|| ‘is a leap year’);
else
dbms_output.put_line(year || ‘is not a leap year’);
end if;
end if;
else
dbms_output.put_line(year||’ is not a leap year’);
end if;
end;
/
Output:
CASE STATEMENT:
The Simple case statement has this structure:
Syntax:
Select case selector
when selector_value_1 then statements_1
when selector_value_2 then statements_2
...
when selector_value_n then statements_n
else_statements
end case;
from table_name;
COALESCE FUNCTION:
The Oracle/PLSQL COALESCE function returns the first non-null expression in the list. If
all expressions evaluate to null, then the COALESCE function will return null.
The syntax for the COALESCE function in Oracle/PLSQL is:
COALESCE( expr1, expr2, ... expr_n )
EXAMPLE WITH OUTPUT:
• The expressions to test for non-null values.The COALESCE function will compare
each value, one by one.
• This returns the first non-NULL expression among its arguements.
NULLIF FUNCTION:
The Oracle/PLSQL NULLIF function compares expr1 and expr2. If expr1 and expr2 are
equal, the NULLIF function returns NULL. Otherwise, it returns expr1.
7)Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE- APPLICATION
ERROR.
AIM : Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT –IN Exceptions, User defined Exceptions, RAISE- APPLICATION
ERROR.
Description:
PL/SQL LOOP statement is an iterative control statement that allows you to execute a sequence
of statements repeatedly like WHILE and FOR loop.The simplest form of the LOOP statement
consists of the LOOP keyword, a sequence of statements and the END LOOP keywords as
shown below:
LOOP
sequence_of_statements;
END LOOP;
The General Syntax WHILE LOOP is:
WHILE condition LOOP
sequence_of_statements
END LOOP;
Example with output:
sql> declare
num number(2):=1;
out varchar2(30);
begin
while num<=5
loop
out:=out||’ ‘||num;
num:=num+1;
end loop;
dbms_output.put_line(out);
end;
/
Output:
PL/SQL – Exceptions:
PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an
appropriate action is taken against the error condition.
There are two types of exceptions:
• System-defined exceptions
• User-defined exceptions
To call RAISE_APPLICATION_ERROR,
use the syntax:
RAISE_APPLICATION_ERROR(ERROR_NUMBER, MESSAGE[, {TRUE | FALSE}]);
1) AIM: Addition at run time
Declare
a number;
b number;
c number;
Begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line('sum of' a and b is ‘ || c);
exception
when no_data_found then
raise_applicaion_error(-20100,’the given number is not valid’);
end;
/
output:
declare
a number;
s1 number default 0;
begin
a:=1;
loop
s1:=s1+a;
exit when(a=100);
a:=a+1;
end loop;
dbms_output.put_line('sum between 1 to 100 is' || s1);
end;
/
output:
SQL> declare
n number;
endvalue number;
sum1 number default 0;
begin
endvalue:=&endvalue;
n:=1;
while(n<endvalue)
loop
sum1:=sum1+n;
n:=n+2;
end loop;
dbms_output.put_line('sum of odd numbers between 1 and ' || endvalue || 'is' || sum1);
end;
/
Output:
SQL> declare
a number;
b number;
c number;
begin
a:=&a;
b:=&b;
c:=&c;
if(a>b)and(a>c)then
dbms_output.put_line('a is maximum');
elsif(b>a)and(b>c)then
dbms_output.put_line('b is maximum');
else
dbms_output.put_line('c is maximum');
end if;
end if;
end;
/
Output:
EXPERIMENT-8
DROP PROCEDURE
Once you have created your procedure in Oracle, you might find that you need to remove it
from the database.
Syntax:
DROP PROCEDURE procedure_name;
/*program*/
/*calling procedure*/
declare
enqno2 number(5);
fname2 varchar2(30);
begin
enqno2:=111;
enqnames(enqno2,fname2);
dbms_output.put_line(fname2);
end;
/
Output:
Output:
To find square root of a number:
/*program*/
sql> declare
a number;
procedure squarenum(x in number)is
begin
x:=x*x;
end;
begin
a:=23;
squarenum(a);
dbms_output.put_line(‘square of (23): ‘||a);
end;
/
Output:
Experiment-9
9)AIM:Program development using creation of stored functions,invoke
functions in SQL statements and write complex functions.
AIM : Program development using creation of stored functions, invoke functions in SQL
Statements and write complex functions.
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows:
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype {IS | AS}
BEGIN
< function_body >
END [function_name];
The syntax to a drop a function in Oracle is:
DROP FUNCTION function_name;
/*program*/
/*calling function*/
declare
fname2 varchar2(30);
deptno2 number(5);
begin
deptno:=1219;
fname2:=getname(dno);
dbms_output.put_line(fname2);
end;
/
Output:
CURSORS
Description:
Cursor is the work area which Oracle reserves for internal processing of SQL statements.
This work area is private for oracles reserved are called cursor.
There are two types of cursors in PL/SQL:
• Implicit Cursor or Internal Cursor: Manage for Oracle itself or internal process itself.
• Explicit Cursor or User-defined Cursor: Manage for user/programmer or external
Processing
The syntax for creating an explicit cursor is :
CURSOR cursor_name IS select_statement;
Step for Using Explicit Cursor::
• Declaring the cursor for initializing in the memory
• Opening the cursor for allocating memory
• Fetching the cursor for retrieving data
• Closing the cursor to release allocated memory
AIM: create an employ table and retrieve the name of employ whose salary is Greater than
1500 by PL/SQL
Program:
declare
emp_rec varchar(30);
cursor emp_cur is select ename
from emp3 where salary>1500;
Begin
Open emp_cur;
Loop
fetch emp_cur into emp_rec;
exit when emp_cur%notfound;
dbms_output.put_line(emp_rec);
end loop;
close emp_cur;
end;
/
Output:
Other example:
Create table customers(id,name,age,address,salary);
/*program*/
declare
toal_rows number(2);
begin
UPDATE customers
set salary= salary+500;
if sql%notfound then
dbms_output.put_line(‘no customer selected’);
elseif sql%found then
total_rows:=sql%rowcount;
dbms_output.put_line(‘total_row || ‘customers selected’);
end if;
end;
/
Output:
declare
c_id customers.id%type;
c_name customers.name%type;
c_address customers.address%type;
cursor c_customers is
select id,name,address from customers;
begin
open c_customers;
loop
fetch c_customers into c_id,c_name,c_address;
exit when c_customers%notfound;
dbms_output.put_line(c_id|| ‘ ‘||cname||’ ‘c_address);
end loop;
close c_customers;
end;
/
Output:
EXPEREMENT-11
AIM:Develop programs using before and after triggers, row and statement triggers
and instead of triggers.
Description:
Oracle engine invokes automatically whenever a specified event occurs.Trigger is stored into
database and invoked repeatedly, when specific condition match.
Triggers are stored programs, which are automatically executed or fired when some events
occur. Triggers are, in fact, written to be executed in response to any of the following events:
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP). Component of Trigger
A trigger has three basic parts:
A triggering event or statement
A trigger restriction
A trigger action
Triggering SQL statement : SQL DML (INSERT, UPDATE and DELETE) statement that
execute and implicitly called trigger to execute.
Trigger Action : When the triggering SQL statement is execute, trigger automatically call and
PL/SQL trigger block execute.
Trigger Restriction : We can specify the condition inside trigger to when trigger is fire.
Type of Triggers
BEFORE Trigger : BEFORE trigger execute before the triggering DML statement (INSERT,
UPDATE, DELETE) execute.
AFTER Trigger : AFTER trigger execute after the triggering DML statement (INSERT,
UPDATE, DELETE) executed.
ROW Trigger : ROW trigger fire for each and every record which are performing INSERT,
UPDATE, DELETE from the database table.
Statement Trigger : Statement trigger fire only once for each statement.
Combination Trigger : Combination trigger are combination of two trigger type,
Before Statement Trigger : Trigger fire only once for each statement before the triggering DML
statement.
Before Row Trigger : Trigger fire for each and every record before the triggering DML
statement.
After Statement Trigger : Trigger fire only once for each statement after the triggering DML
statement executing.
After Row Trigger : Trigger fire for each and every record after the triggering DML statement
executing.
PL/SQL Triggers Syntax:
CREATE [OR REPLACE] TRIGGER trigger_name
BEFORE | AFTER|INSTEAD OF[INSERT| UPDATE| DELETE [COLUMN NAME..]
ON table_name
Referencing [ OLD AS OLD | NEW AS NEW ]
FOR EACH ROW | FOR EACH STATEMENT
[ WHEN Condition ]
DECLARE
[declaration_section
variable declarations;
constant declarations; ]
BEGIN
[executable_section
PL/SQL execute/subprogram body ]
EXCEPTION
[exception_section
PL/SQL Exception block ]
END;
Create a trigger:
create or replace trigger salary_changes
before delete or insert or update on customerr
for each row
when(new.id>0)
declare
sal_diff number;
begin
sal_diff:= :new.salary - :old.salary;
dbms_output.put_line('old salary: ‘|| :old.salary);
dbms_output.put_line(‘new salary: ‘|| :new.salary);
dbms_output.put_line(‘salary difference: ‘||sal_diff);
end;
/
Create trigger:
Insert:
->insert into customerr values(1,’rani’,30,’plkl’,20000);
insert into customerr values(2,’raju’,28,’rjy’,21000);
insert into customerr values(3,’hellena’,28,’rjy’,25000);
insert into customerr values(4,’vimochana’,34,’hyd’,15000);
output:
UPADTE:
->udpate customerr set salary=30000 where name='hellena';
DELETE:
->delete from customerr where id=1;