0% found this document useful (0 votes)
81 views

DBMS Lab R19

The document provides instructions for several database queries and operations using concepts like subqueries, constraints, operators like ANY, ALL, IN, EXISTS and NOT EXISTS. It includes examples of creating tables with constraints, inserting data, retrieving data using a SELECT query with subqueries and comparing values using operators. The key points covered are the syntax for common queries along with examples to retrieve the student name who secured the fourth rank using a subquery and comparing values to a subquery result using operators like ALL and ANY.

Uploaded by

Rathna Kumari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

DBMS Lab R19

The document provides instructions for several database queries and operations using concepts like subqueries, constraints, operators like ANY, ALL, IN, EXISTS and NOT EXISTS. It includes examples of creating tables with constraints, inserting data, retrieving data using a SELECT query with subqueries and comparing values using operators. The key points covered are the syntax for common queries along with examples to retrieve the student name who secured the fourth rank using a subquery and comparing values to a subquery result using operators like ALL and ANY.

Uploaded by

Rathna Kumari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

RAMACHANDRA COLLEGE OF ENGINNERING &

TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE &


ENGINEERING

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

Step2: how to create user in oracle

Step3: grant permissions

Step4: connect user with user details


Experiment1:

Creation, altering and droping of tables and inserting rows into a tables(use
constraints while creating tables) examples using SELECT command.

Syntax for creating tables:

Create table tablename(

Column_name datatype(width),

Column_name datatype(width),

Column_name datatype(width)

);

Example for table creation on student:

SQL>create table student(

Stuid int,

Stuname varchar2(10),

Stusection varchar2(5),

Dob varchar2(10),

Gender varchar2(5)

);

Output:
Insert command:

Insert statement is used to add rows to a table.insertion of data can be executed in


two ways.

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.

Conventional insert: inserting data into all columns of a table.

Direct_path insert: supplying data bat run time.

Type1: Syntax for conventional insert

SQL>insert into tablename values(value1,value2,value3……);

Example:

SQL>insert into student values(stuid,’stuname’,’stusection’,’’dob’,’gender’);

Output:

SQL>insert into student values(501,’raju’,’cse-c’,’’june’,’male’);

SQL>insert into student values(502,’latha’,’cse-b’,’may’,’f’);


Type2: syntax direct_path insert:

SQL>insert into tablename values(&value1,&value2,value3……..);

Example:

SQL>insert into student values


(&stuid,’&stuname’,’&stusection’,’&dob’,’&gender’);

Output:

How to get values/ data retrieval:

It is an operation that receives data from one or more tables or views

Syntax:

Select * from tablename;

Example:

Select * from student;


Desc command:

Syntax:

SQL> desc tablename;

Example:

SQL>desc student;

Altering:

Case1: adding

Syntax for adding a column:

SQL>alter table tablename add(columnname datatype(width));

Example:

SQL>alter table student add(phone int);


case2:modify

syntax for modifyind data:

SQL>alter table tablename modify(old columnname datatype(new size));

Example:

SQL>alter table student modify(gender varchar2(10));

Case3:drop

When we want to delete a certain column of a table we need to use drop command.

Syntax:

Alter table tablename drop column columnname;

Example:

Alter table student drop column dob;


Drop table:

SQL>drop table student;

Output: table dropped.

Case4: update command

The update statement is used to change the existing value in a table. Update object
privilege should be available.

Syntax for update the data in a table:

Update tablename

Set columnname=new datavalue

Where clause;

Example:

Update student

Set phone=1234567890

Where stuid=501;

Output:
Case5: delete command

Delete command is used to remove a rows from a table.

Syntax:

Delete from tablename

Where condition/clause;

Example:

Delete from student

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)
);

✓ Insert into stu values(sid,’sname’,’address’,phone,tmarks,’grade’);


Table2:

Create table course(


cid int primary key/NOT NULL,
cname varchar2(10),
tmarks int,
rank int,
sid int,
constrint fk_stu
foreign key(sid) references stu(sid));
✓ insert into course values(cid,’cname’,tmarks,rank,sid);

Syntax for SELECT: To retrieve the specified column or distinct column.

Select column_name
From tablename
Where condition;
Example:
Select cid
From course
Where rank=4;

Sub queries with the select statement :


Basic syntax:
Select column_name1, column_name2 from table1,table2
Where column_name OPERATOR (
Select column_name ,column_name
from table1,table2
where condition );
Example:
Select sname from stu where sid= (
Select sid from course
Where rank=4);

The SQL ANY operators:


• The ANY and ALL operators allow you to perform a comparision between a single
column value and a range of other values.
• The ANY operator returns a Boolean value as a result, returns true if ANY of the
sub queries values meet the condition.
• ANY means that the condition will be true if the operation is true for any of the
values in the range
Syntax for ANY:
Select column_name from table_name
Where column_name operator ANY(
Select column_name
From table_name
Where condition);
Example:
Select sname,sid from stu where sid<ANY(
Select sid from course
Where rank=4);

The SQL ALL operator:


• The ALL operator returns a Boolean values as a result, returns true if ALL of the
sub query values meet the condition. ALL operator is used with select, where and
having statement.
• ALL means that the condition will be true only if the operation is true for all value
in the range.

ALL syntax with select:


Select ALL column_name
From table_name
Where condition;
ALL syntax with where or having :
Select column_name from table_name
Where column_name operator ALL (
Select column_name
From table_name
where condition);

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);

Example for EXISTS:


Select sname ,sid from stu s where EXISTS(
Select sid from course c
Where c.cname=’java’ and s.sid=c.sid);

NOT IN/ NOT EXISTS:


• NOT IN and NOT EXISTS are the same, meaning they return the same result
sets as long as NULL’s are not involved.
• For checking a small static list, NOT IN is preferred, checking against multiple
columns again NOT EXISTS preferred. If one of the column is Nullable, NOT
EXISTS is preferred.
Example:
Select sname, sid from stu s where NOT EXISTS(
Select cid fom course c
Where c.cnam=’se’ and c.sid=s.sid)
Output:

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:

Select sname from student s, course1 c


Where s.sid=c.sid AND c.cname=’dbms’
TNTERSECT
Select sname from student s, course1 c
Where s.sid=c.sid AND c.rank=3;

Output:
EXPERIMENT-3

Quaries using Aggregate functions(COUNT, SUM, AVG, MAX, and


MIN),GROUP BY, HAVING and creation and droping of vies.

AIM : To use select statement and demonstrate different Aggregate functions


and group by,having. To create, alter, and drop view for given tables.

GROUP FUNCTIONS OR AGGREGATE FUNCTIONS:


Functions are used to manipulate data and return result. Function follow the
format of function_name (argument1, argument2...). An arrangement is user
defined variable or constant. The structure of function is that it accepts zero or
more arguments.
Table creation:
Create table emp3(
Empno int primary key,
Ename varchar2(10),
Job varchar2(10),
Mgr int(5),
Hiredate date,
Sal int,
Comm. Int,
Deptno int
);
Output:

Insertion: insert into emp3 values (


empno,’ename’,’job’,mgr,’hiredate’,sal,comm.,deptno);
Output:
✓ Select * from emp3; for retrieving the data
Output:
Aggregate functions:
SUM: It returns the total value of entire column.
Syntax:
Sum(distinct/all column_name)
Example:
Select sum(sal) from emp3;
Output:

AVG: return average value of n


Syntax:
Avg (distinct/all column_name)
Example:
Select avg(distinct sal) from emp3;
Output:

COUNT: It returns total number of records including NULL values.


Syntax:
Count(*/ all/ distinct column_name)
Example:
1) Select count(*) from emp3;
Output:

2) Select count( distinct job) from emp3 where depno=30;


Output:

3) Select count(distinct ename) from emp3 where deptno=30;


Output:

MAX: It returns highest value among the specified column.


Syntax:
Max( distinct/all column_name);
Example:
1)Select max(sal) from emp3;
Output:

2) slect max(comm.) from emp3;


Output:
MIN: it returns the least value among the specified column.
Syntax:
Min(distinct/all column_name)
Example:
Select min(sal) from emp3;
Output:

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));

Insert into st( sid,’sname’);


✓ Create table marks(sid int,sub1 int,sub2 int,sub3 int);

• Insert into marks values(sid,sub1,sub2,sub3);


Syntax:
CREATE VIEW viewname AS
SELECT column_name, column_name
FROM tablename
WHERE columname=expression_list;

Selecting a data set from a view:


Syntax:
SELECT column_name,column_name
FROM viewname
WHERE search condition;

EXAMPLE:
1) Create view student3 as Select
Sid “ID ”,
Sname name
From st;
Output:

2) Create view stu as


Select
St.sid,st.sname,marks.sub1,marks.sub2,marks.sub3
From st,marks
Where st.sid=marks.sid;
Output:

Retrieving the data from views:


output:

Destroying a view:
Syntax:
DROP VIEW viewname;
Example:

Renaming the column of a views:


Syntax:
CREATE VIEW viewname AS
SELECT newcolumn_name
FROM tablename
WHERE column_name=expression_list;

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;

✓ Select 15.193 num1, round(15.193,1)rounded from dual;


✓ Select 15.193 num1, round(15.193,-1)rounded from dual;

2) Truncated function:
Select 15.79 num1, trunc(15.79,1) truncated from dual;

Select 15.79 num1,trunc(15.79)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;

7) Square root function:


select sqrt(25) squareroot 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;

2)select sysdate, sysdate+3 from dual;

String conversion functions:


1)Concate: This function is used to return the concatenate string.
Syntax: select concat(‘string’,string2) 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:

✓ select ‘page1’ string,lpad(page1,10,’*’) lpadded from dual;

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:

✓ select ‘page1’string,rpad(page1,10,’*’)rpadded from dual;


4)LTRIM: function removes starting character from the given string.
Syntax: select trim(trimcharacter from string) from dual;
Example: select trim(‘A’ from ‘AJAY’) from dual;
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:

6)LOWER: This function covert all characters string to lowercase.


Syntax: select lower(string) from dual;
Example: select lower(‘JEMIMA JONES’) from dual;
Output:

7)UPPER: This function coverts all characters to uppercase.


Syntax: select upper( string) from dual;
Example: select upper( ‘rathna kumari’) 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:

9)LENGTH: This function returns length of string.


Syntax: select columnname,length(string) from dual;
Example: select ename,length(ename) from emp3;
Output:

10)SUB STRING: This function alloes to extract a substring from astring.


Syntax: select substr(string,startposition,endposition) from dual;
Example: select substr(‘ramakrishna’,3,9) from dual;
Output:

11)INSTR: This function returns the location of substring in a string.


Syntax: select instr(string,substring)from dual;
Example: select instr(‘jemmi’,’m’) from dual;
Output:
DATE FUNCTIONS:
1)SYSDATE: This function returns current date.
Example: select sysdate from dual;
Output:

✓ select extract(day from sysdate) as only day from dual;

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;

6)Least: This functionreturns the smallest value in a list of expressions.


Syntax: select least(exp1,exp2,....expn) from dual;
Example: slect least(-2,0,2) from dual;

7)Greatest: This function returns the largest value in a list of expressions.


Syntax: select greatest (exp1,exp2,.....expn) from dual;
Example: select greatest(-2,0,1,2) from dual;

8)Trun: This function returns a date truncated to a specific unit of measure.


Example: select trun(to_date(’26-jul-2017’),’year’) as prev_year from dual;
Output:
9)Round: This function returns a number rounded to a certain number of decimal places.
Example: select round(to_date(’26-jul-2017’),’year’) as new_year 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

5 i)Creation of simple PL/SQL program which includes declaration


section, executable section and exception –Handling section (Ex. Student
marks can be selected from the table and printed for those who secured
first class and an exception can be raised if no records were found)
AIM: Creation of simple PL/SQL program which includes declaration section,
executable section and exception –Handling section
Syntax for pl/sql:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
PL/SQL-> procedure language extention to the sql
Declarations:
This section starts with the keyword DECLARE. It is an optional section and
defines all variables, cursors, subprograms, and other elements to be used in the
program.
Executable Commands:
• This section is enclosed between the keywords BEGIN and END and it is
a mandatory section.
• It consists of the executable PL/SQL statements of the program. It should
have at least one executable line of code, which may be just a NULL
command to indicate that nothing should be executed.
• Create the PL/SQL program using notepad and save it as filename.sql
• At sql command prompt type the command as SET SERVEROUTPUT
ON;
• Close the file at command type’1’ and then enter SQL/ ENTER. The
output will apper an command prompt.
Exception Handling:
This section starts with the keyword EXCEPTION. This section is again
optional and contains exception(s) that handle errors in the program.
Create table class(sid,sname,sclass);
Create table class
(
Sis int,
Sname varchar2(10),
Sclass varchar2(10));
Example:

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

Transaction is nothing but some logical unit of work. A transaction


begins withany executable DML statement and ends with either commit or
rollback commands.

➢ COMMIT: save work done


Syntax: commit;
Commit complete.
➢ SAVEPOINT: identify a point in a transaction to which you can later roll
back.
Syntax: savepoint name;
Savepoint created.
➢ ROLL BACK: restore database to original since the last commit;
Syntax: roll back to savepoint;
Roll back complete.
SQL>begin
Savepoint stu;
Inert into stu values(‘rishi’,’cse’);
Exception
When dup_val_on_index then
Rollback to stu;
Commit;
End;
/
Experiment-6
6) Develop a program that includes the features Nested if,Case and case
expression.The Program can be extended using the NULL if, and
COALESCE functions.
AIM :Develop a program that includes the features NESTED IF, CASE and CASE
expression. The Program can be extended using the NULLIF and COALESCE functions.
CONDITIONAL SELECTION STATEMENTS
Description:
The conditional selection statements, IF and CASE, run different statements for different data
values. The IF statement either runs or skips a sequence of one or more statements,
depending on a condition. The IF statement has these forms:
IF…. THEN
IF… THEN… ELSE
IF….. THEN.. ELSIF
The CASE statement chooses from a sequence of conditions, and runs the corresponding
statement. The CASE statement has these forms:Simple, which evaluates a single expression
and compares it to several potential values. Searched, which evaluates multiple conditions
and chooses the first one that is true. The CASE statement is appropriate when a different
action is to be taken for each alternative.
The IF… THEN statement has this structure:
Syntax:
IF condition THEN
statements
END IF;
Example with output: swapping of two numbers using temp variable.
sql> declare
no_1 number:=’&no_1’;
no_2 number:=’&no_2’;
temp number;
begin
if no_1>no_2 then
temp:=no_1;
no_1:=no_2;
no_2:=temp;
end if;
dbms_output.put_line(‘the swapped number 1 is: ‘||no_1);
dbms_output.put_line(‘the swapped number2 is: ‘||no_2);
end;
/
Output:

• If the condition is true, the statements run; otherwise, the IF statement does nothing.

The IF THEN ELSE statement has this structure:


Syntax:
IF condition THEN
statements
ELSE
else_statements
END IF;
• If the value of condition is true, the statements run; otherwise, the else statements run.

EXAMPLE WITH OUTPUT: finding whether the number is even or odd?


sql>declare
n number:=&n;
begin
if mod(n,2)=0
then
dbms_output.put_line(‘ the given number is even number’);
else
dbms_output.put_line(‘the given number is odd number’);
end if;
end;
/
Output:
The IF THEN ELSIF statement has this structure:
SYNTAX:
IF condition_1 THEN statements_1
ELSIF condition_2 THEN statements_2
[ ELSIF condition_3 THEN statements_3 ]...
[ ELSE
else_statements ]
END IF;

• 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;

example with output:


sql>select store_name,
case store_name
when ‘newyork’ then sales*2
when ‘chicago’ then sales*3
else sales
end
“new sales”
from store_information;
Output:
The searched case statement has this structure:
syntax
CASE [ expression ]
WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2
... WHEN condition_n THEN result_n ELSE result
END from table_name;

Example with output:


select store_name,txn_date case
when sales>=8000 then’congrats get a gift coupn’
when sales>6000 then ‘thanks for shopping’
else ‘good day’
end
“sales status”
from store_information;
Output:

PROGRAM WITH CASE: working on operator?


sql>declare operand1 number:=&operand;
operand2 number:=&operand2;
op varchar2(2):=’&op’;
res number;
begin
case (op)
when ‘+’
then res:=operand1+operand2;
dbms_output.put_line(‘the sum is : ‘||res);
when ‘-‘ then
res:=operand1-operand2;
dbms_output.put_line(‘the subtraction is: ‘||res);
when ‘*’ then
res:=operand1*operand2;
dbms_output.put_line(‘the multiplication is: ‘||res);
when ‘/’ then
res:=operand1/operand2;
dbms_output.put_line(‘the division is: ‘||res);
end case;
end;
/
Output:

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.

The syntax for the NULLIF function in Oracle/PLSQL is:


NULLIF( expr1, expr2 )
EXAPMLE WITH OUTPUT:
Experiment-7

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:

The syntax for the FOR Loop is:


FOR counter IN [REVERSE] lower_bound..higher_bound LOOP
sequence_of_statements
END LOOP;
Example with output:
sql>declare
num number:=&num;
fact num:=1;
begin
for myindex in 1..num
loop
fact:=fact*myindex;
end loop;
dbms_output.put_line(‘the factorial of’ ||num||’ is: ‘|fact);
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:

2)AIM: Simple loop to get sum of 100 numbers

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:

2) AIM: While Loop for sum of 100 odd numbers

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:

3) AIM: if else for finding maximum of three numbers

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

AIM: Programs development using creation of


procedures,passing paramneters IN and OUT of procedures.

A procedure is created with the CREATE OR REPLACE PROCEDURE statement.


syntax for the CREATE OR REPLACE PROCEDURE statement is as follows:
CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT
| IN OUT] type [, ...])] {IS | AS} BEGIN
< procedure_body > END procedure_name;
There are three types of parameters that can be declared:
IN represents that value will be passed from outside and
IN - The parameter can be referenced by the procedure or function. The value of the
parameter
cannot be overwritten by the procedure or function.
OUT represents that this parameter will be used to return a value outside of the procedure.
OUT - The parameter cannot be referenced by the procedure or function, but the value of the
parameter can be overwritten by the procedure or function.
IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter can be overwritten by the procedure or function.
Procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
The AS keyword is used instead of the IS keyword for creating a standalone function.

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;

->create table enquiry(enqno1 number,fname varchar2(30));


->insert into enquiry values(111,'sai');
->insert into enquiry values(112,'sindhu');

/*program*/

create procedure enqnames(enquiryno1 IN number,fname1 OUT varchar2) is


fname2 varchar2(30);
begin
select fname into fname2
from enquiry
where enqno1=enquiryno1; fname1:=fname2;
exception
when no_data-found then
raise_application_error(-20100,'The given number is not present');
end;
/
Output:

/*calling procedure*/

declare
enqno2 number(5);
fname2 varchar2(30);
begin
enqno2:=111;
enqnames(enqno2,fname2);
dbms_output.put_line(fname2);
end;
/
Output:

More Example with output:


• To Find minimum number
/*program*/
sql>declare
a number;
b number;
c number;
procedure findmin(x in number, y in number, z out number)is
begin
if x<y then
z:=x;
else
z:=y;
end if;
end;
begin
a:=23;
b:=45;
findmin(a,b,c);
dbms_output.put_line(‘minimum of (23,45): ‘||c);
end;
/

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;

->create table dept(deptno int,dname varchar(10));


->insert into dept values(1219,'sai');

/*program*/

create or replace function getname(dno number) return varchar2 as


fname1 varchar2(30);
begin
select dname into fname1 from dept
where deptno=dno;
return(fname1);
exception when no_data_found then
raise_application_error(-20100,'The dno is not present');
end;
/
Output:

/*calling function*/

declare
fname2 varchar2(30);
deptno2 number(5);
begin
deptno:=1219;
fname2:=getname(dno);
dbms_output.put_line(fname2);
end;
/
Output:

Another example on table class:

Example to find maximum of two numbers:


sql>declare
a number;
b number;
c number;
function findmax(x in number,y in number) return number is z number;
begin
if x>y then
z:=x;
else z:=y;
end if;
return z;
end;
begin
a:=23;
b:=45;
c:=findmax(a,b);
dbms_output.put_line(‘maximum of(23,45): ‘||c);
end;
/
Output:
Example to find factorial of a number:
sql> declare
num number;
factorial number;
function fact(x number) return number is f numbe;
begin
if x=0 then
f:=1;
else
f:=x*fact(x-1);
end if;
return f;
end;
begin
num:=6;
factorial:=fact(num);
dbms_output.put_line(‘factorial ‘||num||’is ‘||factorial);
end;
/
Output:
Experiment-10
10)Develop programs using features parameters in a CURSOR, FOR UPDATE
CURSOR, WHERE CURRENT of clause and CURSOR variables.

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

Create table emp3(eid,ename,sal);

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:

Select * from customers;


/*program*/

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;

Example for update:


declare
total_rows number(2);
begin
update customer
set salary=salary + 500;
if sql%notfound then
dbms_output.put_line(‘no customer updated’);
else if sql%found then
total_rows:=sql%rowcount;
dbms_output.put_line(total_rows|| ‘customer updated’);
end if;
end;
/
Output:

You might also like