DBMS - Lab Manual - RECORD

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 56

PROGRAMS LIST:

1) Creation, altering and droping of tables and inserting rows into a table (use constraints
while Creating tables) examples using SELECT command.
2) Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSECT, Constraints.
Example:- Select the roll number and name of the student who secured fourth rank in the
class.
3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.
4) Queries using Conversion functions (to_char, to_number and to_date), string functions
(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date
functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest,
trunc, round, to_char, to_date)
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)
ii)Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in
PL/SQL block.
6) Develop a program that includes the features NESTED IF, CASE and CASE expression.
The program can be extended using the NULLIF and COALESCE functions.
7) Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE-
APPLICATION     ERROR.
8) Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.
9) Program development using creation of stored functions, invoke functions in SQL
Statements and write complex functions.
10) Program development using creation of package specification, package bodies, private
objects, package variables and cursors and calling stored packages.
11) Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR,
WHERE CURRENT of clause and CURSOR variables.
12) Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers

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

ORACLE

Oracle was first developed by Relational Software in the year 1979 later came to be known as
oracle Corporation. This company produces the most widely used, server based, multi user
RDBMS named Oracle

SQL (Structured Query Language)

• This is a language that provides an interface to relational database systems.


• The language developed by IBM to manipulate the data stored within Codds model was
originally called as Structured English query language (SEQUEL) later called as SQL.
• SQL encompasses DDL(Data Definition Language), DML(Data Manipulation Language) ,
TCL(Transaction Control Language) and DCL(Data Control Language).

DDL

• This part of SQL is a syntax for database tables to be created or deleted. We can also define
indexes, specify links between tables, and impose constraints between database tables
• The important DDL statements are
– CREATE Table
– ALTER Table
– DROP Table
– TRUNCATE Table
– RENAME Table
DML

• This part of SQL is a syntax for executing queries. But the SQL language also include a
syntax to update, insert and delete records.
• The important DML Statements are
– SELECT – Extracts data from a database table
– UPDATE – Updates data in a database table
– DELETE – Deletes data from a database table
– INSERT INTO – Inserts new data into a database Table.
TCL

• This part of SQL is a syntax for control the transactions on a database .


• The important TCL statements are
– COMMIT – Save the changes permanent
– ROLLBACK – Undo the changes on data base
– SAVEPOINT – Save the changes upto this point of time.

DCL

• This part SQL is a syntax to control the flow of data among different users of the database
• The important DCL statements are
– GRANT – Grants permissions to users
– REVOKE – Revokes permissions to users

2
DDL STATEMENTS
CREATE

• Defines each column of the table Uniquley. Each column has minimum of three attributes.
– Name
– Datatype
– Size
• Rules for creating Tables
– A name can have upto 30 Characters
– Alphabets from A-Z,a-z and numbers from 0-9 are allowed.
– A name should begin with an alphabet.
– The use of special characters is allowed lile _ , $ , # .
– SQL reserved words are not allowed
• Syntax
– CREATE TABLE <Table Name> ( <Column name 1> <Datatype>(<size>),
<Column name 2> <Datatype>(<size>),……);
• Check List
– What are the attributes of the row to be stored.
– What are the datatypes of the attribues.
– Which column should be used to build primary key.
– Which column must allow or not allow null values.
– Which column must allow or not allow Duplicates.
Note

• In ORACLE data is case sensitive but syntax is not case sensitive.


– Student_name data like ABC, Abc, aBc and abc will be treated as different names
and are distinct records.
– While we write SQL statements in Capital or small letters they will be considered.
By default what ever case you enter in table names and column names they will
stored in Capital letters in the data base.
– You can test this by displaying the tables.

SQL>create table sailors(sid number(3),sname varchar2(10), rating number(1),age number(3,1));


Table created
SQL>desc sailors;

NAME NULL? TYPE


SID NUMBER(3)
SNAME VARCHAR2(10)
RATIN
NUMBER(1)
G
AGE NUMBER(3,1)

SQL>select * from tab;

SQL>create table boats(bid number(3),bname varchar2(10),color varchar2(10));


Table created
SQL>desc boats;

NAME NULL? TYPE


BID NUMBER(3)
3
BNAM
VARCHAR2(10)
E
COLOR VARCHAR2(10)
SQL>select * from tab;

SQL>create table reserves(sid number(3),bid number(3),day date);

Table created

SQL>desc reserves;

NAME NULL? TYPE


SID NUMBER(3)
BID NUMBER(3)
DAY DATE

SQL>select * from tab;

ALTER

• This Statement modify the structure of the table


• ALTER table works by making a temporary copy of the original table.
• The alteration is performed on the copy, then the original table is deleted and the new one
is renamed.
• Until the alteration is complete no user is allowed to Update or write to the table.
• ALTER table has 3 syntax
• Syntax 1for Adding new Columns
• ALTER TABLE <Table Name> ADD(<NewColumnName> <Datatype>(<size>),
<NewColumnName> <Datatype>(<size>)…);
• Syntax 2 for Dropping a column from a table
• ALTER TABLE <TableName> DROP COLUMN <ColumnName>;
• Syntax 3 for Modifying Existing Columns
• ALTER TABLE <TableName> MODIFY (<ColumnName>
<NewDatatype>(<NewSize>));
• Restrictions on the ALTER Table
• Cannot change the name of the table
• Cannot change the name of the column
• Cannot decrease the size of a column if the table data exists.

SQL>alter table sailors add(address number(10));


Table altered
SQL>desc sailors;

NAME NULL? TYPE


SID NUMBER(3)
SNAME VARCHAR2(10)
RATING NUMBER(1)
AGE NUMBER(3,1)
ADDRESS NUMBER(10)

SQL>alter table sailors modify (address number(2)):


4
Table altered

SQL>desc sailors;

NAME NULL? TYPE


SID NUMBER(3)
SNAME VARCHAR2(10)
RATING NUMBER(1)
AGE NUMBER(3,1)
ADDRESS NUMBER(2)

SQL>alter table sailor drop column address;

Table altered

SQL>desc sailors;

NAME NULL? TYPE


SID NUMBER(3)
SNAME VARCHAR2(10)
RATIN
NUMBER(1)
G
AGE NUMBER(3,1)
RENAME
Rename of table is allowed in oracle

SQL> Rename sailors to sailor1;

DROP

SQL>drop table sailors;


Table dropped

TRUNCATING TABLE
• It empties the table completely . Leave the table structures. Such like Delete all rows from
the table.
• Truncate Drops the table and recreates its. It is faster than Deleting all Rows
• It is not transaction safe
• Deleted rows will not be returned

• Syntax

– TRUNCATE TABLE <TableName>

SQL>truncate table sailors;

5
DML
INSERT

• Syntax
– INSERT INTO <TableName>(<ColumnName> ,<ColumnName>,…) VALUES
(<Expression>, <Expession>,…);
– While inserting there must (‘) for character data and date datatypes
• Rules
– If there are less values being described than there are columns in the table then it is
mandatory to indicate both the columns and there column values
– If there are exactly the same number of values as there are columns and the values
are sequenced in exactly in accordance with the data type of the table columns there
is no need to indicate the column names.
• Inserting Multiple Values
– INSERT INTO <TableName> VALUES (&ColumnName1, &ColumnName2,….);

SQL>insert into sailors values(22,’Dustin’,7,45.0);

1 row inserted

SQL>insert into sailors values(29,’Brutus’,1,33.0);

1 row inserted

SQL>insert into sailors values(31,’Lubber’,8,55.5);

1 row inserted

SQL>insert into sailors values(32,’Andy’,8,25.5);

1 row inserted
------

SQL>select * from sailors;

SID SNAME RATING AGE


22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 25.0
71 Zobra 10 16.0
74 Horatio 9 25.0
85 Art 3 25.5
95 Bob 3 63.5

6
UPDATE
• Syntax 1
– UPDATE <TableName> SET <ColumnName1>=<Expression1>,
<ColumnName2>=<Expression2>,….;
• Syntax 2
– UPDATE <TableName> SET <ColumnName1>=<Expression1>,
<ColumnName2>=<Expression2>,… WHERE Condition;

SQL>update sailors set age = 23.0;

10 rows updated -- this command will update all sailors ages to 23.0

SQL> update sailors set age = 35.0 where sname=’Horatio’;


2 rows updated

SQL>select * from sailors;


SID SNAME RATING AGE
22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zobra 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5

Insert data into Boats and Reserves table


SQL> select * from boats;
BID BNAME COLOR
101 Interlake Blue
102 Interlake red
103 Clipper Green
104 Marine red

SQL> select * from reserves;


SID BID DAY
22 101 10-10-98
22 102 10-10-98
22 103 10-10-98
22 104 10-7-98
31 102 11-10-98
31 103 11-06-98
31 104 11-12-98
64 101 9-5-98
64 102 9-8-98

7
74 103 9-8-98

DELETE
• Syntax 1
– DELETE FROM <TableName>;
• Syntax 2
– DELETE FROM <TableName> WHERE Condition;

SQL>delete from sailors;

10 rows deleted

SQL>select * from sailors;

No rows selected

SQL>delete from reserves where sid=22;


4 rows deleted

SQL>select * from reserves;


SID BID DAY
31 102 11-10-98
31 103 11-06-98
31 104 11-12-98
64 101 9-5-98
64 102 9-8-98
74 103 9-8-98

8
DATA CONSTRAINTS

• Oracle permits data constraints to be attached to table columns via SQL Syntax
• Once data constraints are part of table column construct, the Oracle database engine checks
the data being entered into a table column against the data constraints.
• If the data passes this check, it is stored in the table column else it is rejected.
• Both CREATE TABLE and ALTER TABLE SQL syntax are used to attach constraints
• Once these constraints are attached data must be carefully loaded into the database.

PRIMARY KEY Constraint

• Primary Key is one or more columns in a table used to uniquely identifies a row.
• A single column primary key is called Simple Key.
• A multi column primary key is called Composite Key.
• Primary key will not allow Duplicate values.
• Primary key will not allow Null values.
• It helps in relating tables with one another
• It cannot be LONG or RAW data type
• Only one primary key is allowed per tabel
• Unique index is created automatically if there is a Primary key
• One table can combine upto 16 columns in a composite Primary Key

• Syntax for Simple primary key


<ColumnName> <DataType>(<size>) PRIMARY KEY

• Syntax for Composite primary key


PRIMARY KEY(<ColumnName1>, <ColumnName2>)

• Assigning user defined names to constraints


CONSTRAINT <ConstraintName> <Constraint Definition>

Foreign Key

• It represents relation between table


• It is a column whose values are derived from the primary key or unique key of some other
table or same table also
• Foreign key can be specified on child but not on parent
• Parent record can be deleted provided no child record exists
• Master table can not be updated if child record exists
• The foreign key columns in the master and child tables must be of same data type
• Rejects a INSERT or UPDATE of values if a corresponding value does not currently exist
in the master table

• Syntax
<columnName> <Datatype>(<size>) REFERENCES <TableName>
[(<ColumnName>)] [options];

• Syntax
Foreign key (<ColumnName> [,<ColumnName>]) REFERENCES <TableName>
[(<ColumnName> ,<ColumnName>)]
9
Unique

• Unique key will not allow duplicate values


• A table can have more than one unique key
• Unique key permits multiple enteries of NULL values into a column
• Unique key can combine upto 16 columns to from composite unique key
• Unique key cannot be LONG or RAW datatype
• Syntax for simple Unique key
<ColumnName> <Datatype>(<size>) UNIQUE
• Syntax for composite Unique key
UNIQUE(<ColumnName1>, <ColumnName2> )

NULL

• A null value is not equal to zero we set null when the value is unknown
• Null value can be inserted into columns of any data type
• Syntax
– <ColumnName> <datatype>(<size>) NOT NULL;
– Example
– SQL>Create table student(s_no varchar2(10), s_name char(20) NOT NULL,year
date,branch char(3), subject char(10));
– IT does not allow NULL values to be inserted in s_name

CHECK

Syntax
– <ColumnName> <Datatype>(<size>) CHECK (<Logical Expression>);

It checks while the values are inserted into the table

Assigment:

SQL>drop sailors;

Table dropped

SQL>drop boats;

Table dropped

SQL>drop reserves;

Table dropped

10
SQL>create table sailors(sid number(3) PRIMARY KEY ,sname varchar2(10), rating number(1)
CHECK(rating>=1 and rating<=10),age number(3,1));

Table created

SQL>desc sailors;

NAME NULL? TYPE


SID NOT NULL NUMBER(3)
SNAME VARCHAR2(10)
RATIN
NUMBER(1)
G
AGE NUMBER(3,1)

SQL>select * from tab;

SQL>create table boats(bid number(3) PRIMARY KEY ,bname varchar2(10),color


varchar2(10));

Table created

SQL>desc boats;
NAME NULL? TYPE
BID NOT NULL NUMBER(3)
BNAM
VARCHAR2(10)
E
COLOR VARCHAR2(10)

SQL>select * from tab;

SQL>create table reserves(sid number(3),bid number(3),day date,PRIMARY KEY(sid,bid),


FOREIGN KEY (sid) REFERENCES sailors(sid), FOREIGN KEY (bid) REFERENCES
boats(bid));

Table created

SQL>desc reserves;
NAME NULL? TYPE
SID NOT NULL NUMBER(3)
BID NOT NULL NUMBER(3)
DAY DATE

SAILORS (Parent) BOATS (Parent)


SID SNAME RATIN AGE BID BNAME COLOR
G
PK PK

RESERVES (Child)
SID BID DAY
FK FK

11
Composite PK

Insert data into Sailors, Boats and Reserves table in the same order

SQL>select * from sailors;

SID SNAME RATING AGE


22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zobra 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5

SQL> select * from boats;

BID BNAME COLOR


101 Interlake Blue
102 Interlake red
103 Clipper Green
104 Marine red

SQL> select * from reserves;

SID BID DAY


22 101 10-10-98
22 102 10-10-98
22 103 10-10-98
22 104 10-7-98
31 102 11-10-98
31 103 11-06-98
31 104 11-12-98
64 101 9-5-98
64 102 9-8-98
74 103 9-8-98

PRIMARY Key Field:

We cannot insert NULL Values or Duplicate values in the fields


SID in Sailors

12
BID in Boats
SID,BID in reserves

FOREIGN KEY FIELD:

The following restrictions are followed for fields which are declared as foreign key

INSERT UPDATE DELETE


PARENT No Restriction No Restriction Restriction
CHILD Restriction No Restriction No Restriction

To insert records into sailors and boats there is no restriction , but to insert record into reserves we
must have the particular record with sid and bid values in sailors and boats tables.

SQL>insert into reserves values(33,101,’11-02-98’);


*
Error: Parent record not found

To update a record in sailors whose value is referenced in reserves will not be permited

SQL>update sailors set sid=33 where sid=22;

Error: Child record found

To update a record in reserves we will have the restriction that only the updating are allowed up to
the values in sailors table
SQL>update reserves set sid=33 where sid=22;

Error: Parent record not found

Deletion in reserves has no restriction but to delete a record from sailors and boats the records
must not have references in child.

SQL>delete from sailors;

Error: Child record found

SQL>delete from boats;

Error: Child record found

We can allow the updating and deleting in parent and child by using the following syntax

SQL>create table reserves(sid number(3),bid number(3),day date,


PRIMARY KEY(sid,bid),
FOREIGN KEY (sid) REFERENCES sailors(sid) on DELETE
CASCADE,
FOREIGN KEY (bid) REFERENCES boats(bid) on UPDATE
CASCADE);

13
This syntax will carry updating and deleting in parent to child with out above restrictions.

BASIC QUERYS IN SQL

SELECT

Syntax 1
– Select all Columns and rows
– SELECT * FROM <TableName>;

Syntax 2
– Selected Columns and rows
– SELECT <ColumnName1>,<ColumnName2>,… FROM <TableName>;

Syntax3
– Selected rows and all columns
– SELECT * FROM <TableName> WHERE condition;

Syntax 4
– Selected rows and Columns
– SELECT <ColumnName1>,<ColumnName2>,… FROM <TableName> WHERE
condition;
Syntax 5
– Selecting rows by eliminating duplicate rows
– SELECT DISTINCT <ColumnName1>,<ColumnName2>,… FROM
<TableName>;
Syntax 6
– Selecting data from table in sorted order
– SELECT * FROM <TableName> ORDER BY <ColumnName1>,<
ColumnName2>,.. [sortorder];

Examples on Sailors, Boats and Reserves Tables

Q1) Find the names and ages of all sailors?

SQL>select distinct sname, age from sailors;

SNAME AGE
Dustin 45.0
Brutus 33.0
Lubber 55.5
Andy 25.5
Rusty 35.0
Horatio 35.0
Zobra 16.0

14
Art 25.5
Bob 63.5

9 rows selected

Q2) Find all sailors with a rating above 7?

SQL> select sid, sname, rating, age from sailors where rating>7;

OR

SQL> select * from sailors where rating>7;

SID SNAME RATING AGE


31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
71 Zobra 10 16.0
74 Horatio 9 35.0

5 rows selected

Q3) Find the names of sailors who have reserved boat number 103;?

SQL> select s.sname from sailors s, reserves r where s.sid=r.sid and r.bid=103;

SNAME
Dustin
Lubber
Horatio

Q4) Find the sids of sailors who have reserved a red boat?

SQL> select r.sid from boats b, reserves r where b.bid=r.bid and b.color=’red’;

SID
22
22
31
31
64

SQL> select distinct r.sid from boats b, reserves r where b.bid=r.bid and
b.color=’red’;
SID
22
31
64
Q5) Find the names of sailors who have reserved a red boat?
15
SQL> select distinct s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and b.color=’red’;

SNAME
Dustin
Lubber
Horatio

Q6) Find the colors of boats reserved by lubber?

SQL>select b.color from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid
and s.sname=’lubber’;

COLOR
Red
Green
Red

7) Find the names of sailors who have reserved at least one boat?

SQL> select s.sname from sailors s, reserves r where s.sid=r.sid;


SNAME
Dustin
Lubber
Horatio
Horatio

16
EXP. 2
AIM: Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSECT, Constraints.

NESTED QUERIES

Q1) Find the names of sailors who have reserved a red or a green boat?
SQL> Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and (b.color = ‘red’ or b.color= ‘green’);

Or
SQL> Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and b.color=’red’
UNION
Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid and
b.color=’green’;
SNAME
Dustin
Lubber
Horatio

Q2) Find the names of sailors who have reserved a red and a green boat?

SQL> Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and b.color=’red’
INTERSECT
Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid and
b.color=’green’;

SNAME
Dustin
Lubber
Horatio

Q3) Find the names of sailors who have reserved a red boat but not green boat?

SQL> Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and b.color=’red’
MINUS
Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid and
b.color=’green’;
NO ROWS SELECTED

Q4) Find all sids of sailors who have a rating of 10 or reserved boat 104?

SQL>select s.sid from sailors s where s.rating=10


17
UNION
Select r.sid from reserves r where r.bid=104;

SID
22
31
58
71
Q5) Find the name of sailors who have reserved boat 103

SQL>Select s.name from sailors s where s.sid


IN (select r.sid from reserve r where r.dib=103)

SNAME
Dustin
Lubber
Horatio

Q6) Find the name of sailors who have reserved a red boat

SQL>Select s.sname from sailors s where s.sid


IN (Select r.sid from reserve r where r.bid
IN (Select b.bid from boats B where b.color = ‘red’));

SNAME
Dustin
Lubber
Horatio

Q7) Find the names of sailors who have not reserved a red boat.

SQL>Select s.sname from sailors s where s.sid


NOT IN (Select r.sid from reserve r where r.bid
IN (Select b.bid from boats B where b.color = ‘red’));

SNAME
Brutus
Andy
Rusty
Horatio
Zobra
Art
Bob
Q8) Find the name of sailors who have reserved boat 103

SQL>Select s.sname from sailors s where


EXISTS (select * from reserves r where r.bid=103 and r.sid = s.sid)
SNAME
Dustin
Lubber

18
Horatio

Q9) Find the name of sailors who have not reserved boat 103
SQL>Select s.sname from sailors s where
NOT EXISTS (select * from reserves r where r.bid=103 and r.sid = s.sid) ;
SNAME
Brutus
Andy
Rusty
Horatio
Zobra
Art
Bob

Q10) Find sailors whose rating is better than some sailor called Horation?

SQL>select s.sid from sailors s where


s.rating > ANY ( select s2.rating from sailors s2 where
s2.name=’Horatio’) ;

SID
31
32
58
71
74

Q11) Find sailors whose rating is better than every sailor called Horation?

SQL>select s.sid from sailors s where


s.rating > ALL ( select s2.rating from sailors s2 where
s2.name=’Horatio’) ;

SID
58
71

19
EXP. 3
AIM: Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.

AGGREGATE OPERATORS

1. COUNT ([Distinct] A) : The number of (unique) values in the A column.


2. SUM ([Distinct] A) : The sum of all (unique) values in the A column.
3. AVG ([Distinct] A) : The average of all (unique) values in the A column.
4. MAX (A) : The maximum values in the A column.
5. MIN (A) : The minimum value in the A column.

Q1) Find the average age of all sailors.

SQL> select AVG(age) from sailors ;

AVG(age)
37.4

Q2) Find the average age of sailors with a rating of 10

SQL> select AVG(age) from sailors where rating=10 ;

AVG(age)
25.5

Q3) Find the maximum age of sailors?

SQL> Select MAX(age) from sailors ;

MAX(age)
63.5

Q4) Find the minimum age of sailors?

SQL> Select MIN(age) from sailors ;

MIN(age)
16
Q5) Count the number of sailors

SQL> select COUNT(*) from sailors;


COUNT(*)
10
20
Q6) Count the number of different sailor names

SQL> Select COUNT( DISTINCT sname) from sailors ;

COUNT( DISTINCT sname)


9

Q7) Find the name and age of the oldest sailor

SQL> Select s.sname, s.age from sailors s where


s.age = (select MAX(s2.age) from sailors s2);

SNAME MAX(AGE)
Lubber 55.5

Q8) Find the names of sailors who are older than the oldest sailor with a rating of 10?

SQL> Select s.sname from sailors s where


s.age > (select MAX(s2.age) from sailors s2 where s2.rating =10);

SNAME
Dustin
Lubber
Horatio
Bob

GROUP BY and HAVING Clause:

SELECT [DISTINCT] select-list


FROM from-list
WHERE qualification
GROUP BY grouping-list
HAVING group-qualification

 The select list in the SELECT clause contain


1. A list of column names
2. A list of terms having the form aggop( aggregate operators)
Every column that appear in (1) must also appear in grouping-list
 The expression appearing in the group-qualification in the HAVING clause must have a
single value per group.

Q9) Find the age of the youngest sailor for each rating level.

SQL> Select s.rating, MIN(s.age) from sailors s


GROUP BY s.rating;

RATING AGE
1 33.0
3 25.5
7 35.0
8 25.5
21
9 35.0
10 16.0

Q10) Find the age of the youngest sailor who is eligible to vote for each rating level with at least
two such sailors ?

SQL> select s.rating, MIN(s.age) as minage from sailors s where s.age>=18


GROUP BY s.rating
HAVING COUNT(*) > 1;

RATING AGE
3 25.5
7 35.0
8 25.5

Q11) For each red boat find the number of reservations for this boat?

SQL> Select b.bid, COUNT(*) AS reservationcount from boats b,


reserves r where r.bid=b.bid and b.color=’red’
GROUP BY b.bid;

BID RESERVATIONCOUNT
102 3
104 2

Q12) Find the average age of sailors for each rating level that has at least two sailors ?

SQL> Select s.rating, AVG(s.age) AS avgage from sailors s


GROUP BY s.rating
HAVING COUNT(*) > 1;

RATING AVGAGE
3 44.5
7 40.5
8 40.5
10 25.5

22
VIEWS

In the SQL language, a view is a representation of one or more tables. A view can be used to hide
the complexity of relationships between tables or to provide security for sensitive data in tables. In
the following example, a limited view of the emp table is created. When a view is defined, a SQL
statement is associated with the view name. Whenever the view is accessed, the SQL statement will
be executed.

SQL> create table emp(empno number(5),ename varchar2(10),salary number(5),desg


varchar2(10),dno number(3));

Table Created

SQL> insert into emp values(101,’abc’,1000,’acc’,10);

1 row created

Note : Insert the records in EMP likewise

SQL> Select * from emp;

EMPNO ENAME SALARY DESG DNO


101 abc 1000 acc 10
102 def 2000 clk 10
103 dsa 3000 gar 20
104 ewd 4000 acc 10
105 ewf 5000 clk 20

In the following example, the view emp_1 is created as a limited number of columns
(Empno,Ename,salary) and limited set of data ( WHERE salary > 3000 ) from the EMP table.

SQL> CREATE VIEW emp_1


AS SELECT Empno, Ename, salary
FROM emp
WHERE salary > 3000;

View created.

Once the view is created, it can be queried with a SELECT statement as if it were a table.

SQL> SELECT * FROM emp_1 ;

EMPNO ENAME SALARY


104 ewd 4000
105 ewf 5000

23
Views can be dropped in a similar fashion to tables. The DROP VIEW command provides this
facility. In the following example, the view just created is dropped.

SQL> DROP VIEW emp_1;


View dropped.

View can be again created with the same name emp_1 as a limited number of columns
(Empno,Ename,salary,dno) and limited set of data ( WHERE dno=10 ) from the EMP table.

SQL> CREATE VIEW emp_1


AS SELECT Empno, Ename, salary, dno
FROM emp
WHERE dno=10;

View created.

Once the view is created, it can be queried with a SELECT statement as if it were a table.

SQL> SELECT * FROM emp_1 ;

EMPNO ENAME SALARY DNO


101 abc 1000 10
102 def 2000 10
104 ewd 4000 10

SQL> Insert into emp_1 values (106,’htg’,4500,10);

1 row created

SQL> SELECT * FROM emp_1 ;

EMPNO ENAME SALARY DNO


101 abc 1000 10
102 def 2000 10
104 ewd 4000 10
106 htg 4500 10

Do the same with EMP table

SQL> SELECT * FROM emp ;

EMPNO ENAME SALARY DESG DNO


101 abc 1000 acc 10
102 def 2000 clk 10
103 dsa 3000 gar 20
104 ewd 4000 acc 10
105 ewf 5000 clk 20
106 htg 4500 10

The same record will be inserted into base table also and Vice versa

SQL> Insert into emp_1 values (107,’wqa’,3500,20);


24
1 row created

SQL> SELECT * FROM emp_1 ;

EMPNO ENAME SALARY DNO


101 abc 1000 10
102 def 2000 10
104 ewd 4000 10
106 htg 4500 10

The record will not be visible in view because the record does not satisfy the WHERE dn0=10
condition, but it will be inserted in base table EMP

SQL> SELECT * FROM emp ;

EMPNO ENAME SALARY DESG DNO


101 abc 1000 acc 10
102 def 2000 clk 10
103 dsa 3000 gar 20
104 ewd 4000 acc 10
105 ewf 5000 clk 20
106 htg 4500 10
107 wqa 3500 20

Actually this record must not be accepted while inserted in view EMP_1 because it does not hold
the condition so we can enable this condition by including WITH CHECK OPTION in View
creation.

SQL> Drop view emp_1;

View droped

SQL> CREATE VIEW emp_1


AS SELECT Empno, Ename, salary, dno
FROM emp
WHERE dno=10 WITH CHECK OPTION;

View created.

SQL> SELECT * FROM emp_1 ;

EMPNO ENAME SALARY DNO


101 abc 1000 10
102 def 2000 10
104 ewd 4000 10
106 htg 4500 10

25
SQL> Insert into emp_1 values (108,’okl’,7500,20);

Error: Record not inserted because CHECK constraint violated.

We can make the view read only by the following rules


1) Key fields must not be included in view definition
2) NOT NULL fields must not be included in view definition

SQL> alter table emp add PRIMARY KEY(empno);

Table altered

SQL> CREATE VIEW emp_2


AS SELECT Ename, salary, dno
FROM emp
WHERE dno=10 WITH CHECK OPTION;

View created.

SQL> SELECT * FROM emp_2 ;

ENAME SALARY DNO


abc 1000 10
def 2000 10
ewd 4000 10
htg 4500 10

SQL> Insert into emp_2 values (’okl’,7500,10);

Error: NULL values can not inserted in PRIMARY KEY field EMP.EMPNO

This view can not accept insertion because when it inserts a record it is trying to insert NULL into
primary key field of Base table EMP.

26
EXP.4

AIM:Queries using Conversion functions (to_char, to_number and to_date),


string functions (Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and
instr),
date functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc,
round, to_char, to_date)

Oracle SQL Functions

The Oracle implementation of SQL provides a number of functions that can be used in SELECT
statements. Functions are typically grouped into the following:

 Single row functions - Operate on column values for each row returned by a query.
 Group functions - Operate on a collection (group) of rows.

The following is an overview and brief description of single row functions. x is some number, s is
a string of characters and c is a single character.

Math functions :

 ABS (x) - Absolute Value of x

SQL> select ABS(10.5) from DUAL;

ABS(10.5)

10

 CEIL (x) - Smallest integer greater than or equal to x.


 COS (x) - Cosine of x
 FLOOR (x) - Largest integer less than or equal to x.
 LOG (x) - Log of x
 LN (x) - Natural Log of x
 ROUND (x, n) - Round x to n decimal places to the right of the decimal point.
 SIN (x) - Sine of x
 TAN (x) - Tangent of x
 TRUNC (x, n) - Truncate x to n decimal places to the right of the decimal point.

Character functions:

 CHR (x) - Character for ASCII value x.


 INITCAP (s) - String s with the first letter of each word capitalized.
 LOWER (s) - Converts string s to all lower case letters.
 LPAD (s, x) - Pads string s with x spaces to the left.
 LTRIM (s) - Removes leading spaces from s.
 REPLACE (s1, s2, s3) - Replace occurrences of s1 with s2 in string s.
 RPAD (s, x) - Pads string s with x spaces to the right.
 RTRIM (s) - Removes trailing spaces from s.

27
 SUBSTR (s, x1, x2) - Return a portion of string s starting at position x1 and ending
with position x2. If x2 is omitted, it's value defaults to the end of s
 UPPER (s) - Converts string s to all upper case letters.

Character functions that return numbers:

 ASCII (c) - Returns the ASCII value of c


 INSTR (s1, s2, x) - Returns the position of s2 in s1 where the search starts at position
x.
 LENGTH (s) - Length of s

Conversion functions:

 TO_CHAR (date, format) - Converts a date column to a string of characters. format is a


set of Date formatting codes where:
YYYY is a 4 digit year.
NM is a month number.
MONTH is the full name of the month.
MON is the abbreviated month.
DDD is the day of the year.
DD is the day of the month.
D is the day of the week.
DAY is the name of the day.
HH is the hour of the day (12 hour clock)
HH24 is the hour of the day (24 hour clock)
MI is the minutes.
SS is the seconds.

 TO_CHAR (number, format) - Converts a numeric column to a string of characters.


format is a set of number formatting codes where:
9 indicates a digit position. Blank if position value is 0.
0 indicates a digit position. Shows a 0 if the position value is 0.
$ displays a leading currency indicator.

 TO_DATE (s, format) - Converts a character column (string s to a date. format is a set of
Date formatting codes as above.

 TO_NUMBER (s, format) - Converts a character column (string s to a Number. format is


a set of Number formatting codes as above.

Date functions:

 SYSDATE - Returns the current date (and time if the TO_CHAR function is used) from
the system clock.
 LAST_DAY(Date) – Returns the last days date of the month specified in the Date
 MONTHS_BETWEEN(Date, Date) – Returns the number of months between the given
two dates
 TIMESTAMP – Returns the current date time in hours, minutes, seconds and fractions
AM or PM and time zone with respect to GMT.

28
EXP.5(i)
AIM: Creation of simple PL/SQL program which includes declaration section, executable section
and
exception –Handling section .

PL/SQL

The development of database applications typically requires language constructs similar to those
that can be found in programming languages such as C, C++, or Pascal. These constructs are
necessary in order to implement complex data structures and algorithms. A major restriction of the
database language SQL, however, is that many tasks cannot be accomplished by using only the
provided language elements.

PL/SQL (Procedural Language/SQL) is a procedural extension of Oracle-SQL that offers language


constructs similar to those in imperative programming languages. PL/SQL allows users and
designers to develop complex database applications that require the usage of control structures and
procedural elements such as procedures, functions, and modules.

The basic construct in PL/SQL is a block. Blocks allow designers to combine logically related
(SQL) statements into units. In a block, constants and variables can be declared, and variables can
be used to store query results. Statements in a PL/SQL block include SQL statements, control
structures (loops), condition statements (if-then-else), exception handling, and calls of other
PL/SQL blocks.

PL/SQL blocks that specify procedures and functions can be grouped into packages. A package is
similar to a module and has an interface and an implementation part. Oracle offers several
predefined packages, for example, input/output routines, file handling, job scheduling etc.

Another important feature of PL/SQL is that it offers a mechanism to process query results in a
tuple-oriented way, that is, one tuple at a time. For this, cursors are used. A cursor basically is a
pointer to a query result and is used to read attribute values of selected tuples into variables. A
cursor typically is used in combination with a loop construct such that each tuple read by the
cursor can be processed individually.

In summary, the major goals of PL/SQL are to


• increase the expressiveness of SQL,
• process query results in a tuple-oriented way,
• optimize combined SQL statements,
• develop modular database application programs,
• reuse program code, and
• reduce the cost for maintaining and changing applications.

29
STRUCTURE OF PL/SQL-BLOCK

PL/SQL is a block-structured language. Each block builds a (named) program unit, and blocks can
be nested. Blocks that build a procedure, a function, or a package must be named.

A PL/SQL block has an optional declare section, a part containing PL/SQL statements, and an
optional exception-handling part. Thus the structure of a PL/SQL looks as follows (brackets [ ]
enclose optional parts):

[<Block header>]
[DECLARE
<Constants>
<Variables>
<Cursors>
<User defined exceptions>]
BEGIN
<PL/SQL statements>
[EXCEPTION
<Exception handling>]
END;
The block header specifies whether the PL/SQL block is a procedure, a function, or a package. If
no header is specified, the block is said to be an anonymous PL/SQL block. Each PL/SQL block
again builds a PL/SQL statement. Thus blocks can be nested like blocks in conventional
programming languages. The scope of declared variables (i.e., the part of the program in which
one can refer to the variable) is analogous to the scope of variables in programming languages
such as C or Pascal.

Declarations
Constants, variables, cursors, and exceptions used in a PL/SQL block must be declared in the
declare section of that block. Variables and constants can be declared as follows:
<variable name> [constant] <data type> [not null] [:= <expression>];
Valid data types are SQL data types (see Section 1.1) and the data type boolean. Boolean data may
only be true, false, or null. The not null clause requires that the declared variable must always have
a value di_erent from null. <expression> is used to initialize a variable.

If no expression is specified, the value null is assigned to the variable. The clause constant states
that once a value has been assigned to the variable, the value cannot be changed (thus the variable
becomes a constant).

Example:
Declare hire date date; /* implicit initialization with null */
job title varchar2(80) := ’Salesman’;
emp found boolean; /* implicit initialization with null */
salary incr constant number(3,2) := 1.5; /* constant */
...
30
begin
...
end;
Instead of specifying a data type, one can also refer to the data type of a table column (so-called
anchored declaration). For example, EMP.Empno%TYPE refers to the data type of the column
Empno in the relation EMP. Instead of a single variable, a record can be declared that can store a
complete tuple from a given table (or query result). For example, the data type DEPT
%ROWTYPE specifies a record suitable to store all attribute values of a complete row from the
table DEPT. Such records are typically used in combination with a cursor. A field in a record can
be accessed using <record name>.<column name>, for example, DEPT.Deptno.

Exception Handling

A PL/SQL block may contain statements that specify exception handling routines. Each error or
warning during the execution of a PL/SQL block raises an exception. One can distinguish between
two types of exceptions:

• system defined exceptions


• user defined exceptions (which must be declared by the user in the declaration part of a
block where the exception is used/implemented)

System defined exceptions are always automatically raised whenever corresponding errors or
warnings occur. User defined exceptions, in contrast, must be raised explicitly in a sequence of
statements using raise <exception name>. After the keyword exception at the end of a block, user
defined exception handling routines are implemented. An implementation has the pattern when

<exception name> then <sequence of statements>;

The most common errors that can occur during the execution of PL/SQL programs are handled by
system defined exceptions.

Examples

Q3) Write a PL/SQL program to extract sailors sid and sname for a given sid?

SQL> declare
a number(10);
b varchar2(10);
c number(10) := &c;
begin
select sid,sname into a,b from sailors where sid = c;
dbms_output.put_line('sailors id = '||a||'sailors Name= '||b);
exception
when no_data_found then
dbms_output.put_line('no such sailor found with sid = '||c);
end;
/
Enter value for c: 22
old 4: c number(10) := &c;
new 4: c number(10) := 22;
sailors id = 22 sailors name = Dustin
PL/SQL procedure successfully completed.
SQL>/
31
Enter value for c: 20
old 4: c number(10) := &c;
new 4: c number(10) := 20;
Ino such sailor found with sid = 20

PL/SQL procedure successfully completed.

EXP. 5(ii)
AIM:Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL
block.

TCL
Initially any application will have to connect to the database in order to access the data. It is
important to point out that when a user is issuing DML statements in an application the changes
are not visible to the user until a COMMIT or ROLLBACK has been issued.

COMMIT- makes events within a transaction permanent


ROLLBACK – Erases events within a transaction

SAVEPOINT – We can control transactions by using save points. These break transactions into
pieces so that we can roll back to a specified save point with out roll backing the total transaction.

SYNTAX:
savepoint name;

rollback to savepoint name;

Example:

SQL> create table empl(eid number(10),ename varchar(10),desg archar(10),salary


number(5));

Table created

SQL> begin
savepoint a;
insert into empl values (101,'abc','acc',2000);
savepoint b;
insert into empl values (102,'bcd','clk',3000);
savepoint c;
insert into empl values (103,'sde','gar',1200);
rollback to c;
COMMIT;
end;
/

PL/SQL procedure successfully completed

SQL> select * from empl;

32
EID ENAME DSEG SALARY
101 Abc acc 2000
102 Bcd clk 3000

Here only two records are inserted because we are giving savepoints in above PL/SQL block as A,
B, C and we rollback to point C this will erase event insertion of third record.

EXP. 6
AIM: Develop a program that includes the features NESTED IF, CASE and CASE expression.

CONDITIONAL CONTROL STATEMNETS

In PL/SQL there are three types of conditional control : IF, ELSIF and CASE

IF – THEN Statement
This is the most basic kind of a conditional control and has the following structure

If Condition Then
Statement 1;
….
Statement 2;
End If;
The reserved word IF marks the beginning of the IF statement.

Example:

Q1) Write a PL/SQL block to swap two numbers when the first number is greater
than second number ?

SQL> declare
a number(10) := &a;
b number(10) := &b;
c number(10);
begin
dbms_output.put_line('a value ='||a||' b value ='||b);
if a>b then
c := a;
a := b;
b := c;
end if;
dbms_output.put_line(' After swapping: a value ='||a||' b value ='||b);
end;
/

Enter value for a: 20


old 2: a number(10) := &a;
new 2: a number(10) := 20;
Enter value for b: 10
old 3: b number(10) := &b;
new 3: b number(10) := 10;
a value =20 b value =10
33
After swapping: a value =10 b value =20

PL/SQL procedure successfully completed.

IF – THEN – ELSE
This statement enables you to specify two groups of statements One group of statements is
executed when the condition evaluates to TRUE and the other group of statements is executed
when the condition evaluates to FALSE.

If Condition Then
Statement 1;
ELSE
Statement 2;
End If;
Statement 3;
Example:

Q2) Write a PL/SQL block to test whether the given number is odd or even

SQL> declare
a number(10) := &a;
begin
if mod(a,2)=0 then
dbms_output.put_line('a value is even');
else
dbms_output.put_line('a value is odd');
end if;
end;
/

Enter value for a: 44


old 2: a number(10) := &a;
new 2: a number(10) := 44;
a value is even

PL/SQL procedure successfully completed.


SQL> /
Enter value for a: 33
old 2: a number(10) := &a;
new 2: a number(10) := 33;
a value is odd

PL/SQL procedure successfully completed.

34
ELSIF Statement:
This statement has the following structure

If Condition 1 Then
Statement 1;
ELSIF Condition 2 Then
Statement 2;
ELSIF Condition 3 Then
Statement 3;

ELSE
Statement 4;
END IF;
Example:

Q3) Write a PL/SQL block to find the grade of sailor for a given sid
10, 9, 8 – Grade A
7, 6, 5 – Grade B
other – Grade C

SQL> declare
a number(10) := &a;
c number(10);
begin
select rating into c from sailors where sid = a;
if c in (10,9,8) then
dbms_output.put_line('sailor '||a||' has grade A');
elsif c in (7,6,5) then
dbms_output.put_line('sailor '||a||' has grade B');
else
dbms_output.put_line('sailor '||a||' has grade C');
end if;
end;
/

Enter value for a: 22


old 2: a number(10) := &a;
new 2: a number(10) := 22;
sailor 22 has grade B

PL/SQL procedure successfully completed.

35
CASE:
A case statement has the following structure:

CASE selector
WHEN expression 1 THEN statement 1;
WHEN expression 2 THEN statement 2;
…..
WHEN expression n THEN statement n;
ELSE statement n+1;
END CASE;

The reserved word CASE marks the beginning of the case statement. A selector is a value that
determines which WHEN clause should be executed.

Example:

Q4) Write a PL/SQL block to print the day name for a given date?

SQL> declare
a date := '&a';
b char(10);
begin
b := to_char(a,'D');
case b
when '1' then
dbms_output.put_line('today is sunday');
when '2' then
dbms_output.put_line('today is monday');
when '3' then
dbms_output.put_line('today is thuesday');
when '4' then
dbms_output.put_line('today is wednesday');
when '5' then
dbms_output.put_line('today is thrusday');
when '6' then
dbms_output.put_line('today is friday');
when '7' then
dbms_output.put_line('today is saturday');
end case;
end;
/

Enter value for a: 10-mar-09


old 2: a date := '&a';
new 2: a date := '10-mar-09';
36
today is thuesday

PL/SQL procedure successfully completed.

EXP.7
AIM: Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR
Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE- APPLICATION ERROR.

ITERATIVE CONTROL

In PL/SQL there are three types of loops : Simple LOOP, WHILE loops and Numeric FOR loop

simple LOOP:
A simple loop, as you can see from its name, is the most basic kind of loop and has the following
structure:

LOOP
statement 1;
statement 2;
…….
statement n;
END LOOP;

The reserved word LOOP marks the beginning of the simple loop. Statement 1 through N are a
sequence of statements that is executed repeatedly.

EXIT statement causes a loop to terminate when exit condition evaluates to TRUE.

LOOP
statement 1;
statement 2;
IF condition THEN
EXIT;
END IF;
…….
statement n;
END LOOP;

Example:
Q1) Write a PL/SQL block to print number from 1 to 5 using loop statements

SQL> declare
a number :=0;
begin
loop
a := a+1;
dbms_output.put_line('a value='||a);
if a>5 then
37
exit;
end if;
end loop;
end;
/
a value=1
a value=2
a value=3
a value=4
a value=5
a value=6
PL/SQL procedure successfully completed.
Note: here numbers are printed 1 to 6 because this loop acts as do-while so it executes the
statements and then check the condition next.
LOOP
statement 1;
statement 2;
EXIT WHEN condition;
…….
statement n;
END LOOP;

Q2) Write a PL/SQL block to print number from 1 to 5 using loop statements

SQL> declare
a number :=0;
begin
loop
a := a+1;
dbms_output.put_line('a value'||a);
exit when a>5 ;

end loop;
end;
/

a value1
a value2
a value3
a value4
a value5
a value6

PL/SQL procedure successfully completed.

WHILE LOOPS:

A while loop has the following structure

WHILE condition LOOP


statemnet 1;
statemnet 2;
……
38
statemnet n;
END LOOP;

The reserved word WHILE marks the beginning of a loop construct. The word CONDITION is the
test condition of the loop that evaluates to TRUE or FALSE.

Example:

Q3) Write a PL/SQL block to print number from 1 to 5 using while loop statements

SQL> declare
a number:=1;
begin
while a<5 loop
dbms_output.put_line('a value='||a);
a := a+1;
end loop;
end;
/

a value=1
a value=2
a value=3
a value=4

PL/SQL procedure successfully completed.

NUMERIC FOR LOOP:


A numeric FOR loop is called numeric because it requires an integer as its terminating value. Its
structure is as follows.

FOR loop_counter IN[REVERSE] lower_limit..upper_limit LOOP


statement 1;
statement 2;
……
statement n;
END LOOP;

The reversed word FOR marks the beginning of a FOR loop construct. The variable loop_counter
is an implicitly defined index variable. There is no need to define the loop counter in the
declaration section. The values of the lower_limit and upper_limit are evaluated once for the
iteration of the loop.

Example:
Q4) Write a PL/SQL block to print number from 1 to 5 using for loop statements

SQL> begin
39
for a in reverse 1..5 loop
dbms_output.put_line('a value='||a);
end loop;
end;
/
SQL>
a value=5
a value=4
a value=3
a value=2
a value=1
PL/SQL procedure successfully completed.
Examples:
Q5) To write a PL/SQL block to find Sum of Digits of a given Number.
SQL> DECLARE
num number(5);
rem number(5);
sm number(5):=0;
num1 number(5);
BEGIN
num:=&num;
num1:=num;
while(num>0) loop
rem:=mod(num,10);
sm:=sm+rem;
num:=trunc(num/10);
end loop;
dbms_output.put_line('SUM OF DIGITS OF '||num1||' IS: '||sm);
END;
/
RESULT:
SQL>
Enter value for num: 123
old 7: num:=&num;
new 7: num:=123;
SUM OF DIGITS OF 123 IS: 6
PL/SQL procedure successfully completed.

SQL> /
Enter value for num: 456
old 7: num:=&num;
new 7: num:=456;
SUM OF DIGITS OF 456 IS: 15
PL/SQL procedure successfully completed.

Q6) To write a PL/SQL block to Generate Fibonacci Series


SQL> DECLARE
num number(5);
f1 number(5):=0;
f2 number(5):=1;
f3 number(5);
i number(5):=3;
BEGIN
num:=&num;
40
dbms_RESULT.put_line('THE FIBONACCI SERIES IS:');
dbms_RESULT.put_line(f1);
dbms_RESULT.put_line(f2);
while(i<=num) loop
f3:=f1+f2;
dbms_RESULT.put_line(f3);
f1:=f2;
f2:=f3;
i:=i+1;
end loop;
END;
/
RESULT:
SQL>
Enter value for num: 10
old 8: num:=&num;
new 8: num:=10;
THE FIBONACCI SERIES IS:
0
1
1
2
3
5
8
13
21
34
PL/SQL procedure successfully completed.

Q7) To write a PL/SQL block to Check the Given String is Palindrome or Not.

SQL> DECLARE
name1 varchar2(20);
name2 varchar2(20);
l number(5);
BEGIN
name1:='&name1';
l:=length(name1);
while l>0 loop
name2:=name2||substr(name1,l,1);
l:=l-1;
end loop;
dbms_RESULT.put_line('REVERSE OF STRING IS:'||NAME2);
if(name1=name2) then
dbms_RESULT.put_line(name1||' IS PALINDROME ');
else
dbms_RESULT.put_line(name1||' IS NOT PALINDROME ');
end if;
END;
/
RESULT:
SQL>
Enter value for name1: LIRIL
41
old 6: name1:='&name1';
new 6: name1:='LIRIL';
REVERSE OF STRING IS: LIRIL
LIRIL IS PALINDROME
PL/SQL procedure successfully completed.
SQL> /
Enter value for name1: MADAM
old 6: name1:='&name1';
new 6: name1:='MADAM';
REVERSE OF STRING IS: MADAM
MADAM IS PALINDROME
PL/SQL procedure successfully completed.
EXCEPTION HANDLING

We can distinguish between two types of exceptions:

• System defined exceptions


• User defined exceptions (which must be declared by the user in the declaration part of a block
where the exception is used/implemented)

SYSTEM DEFINED EXCEPTIONS


System defined exceptions are always automatically raised whenever corresponding errors or
warnings occur.

The table below lists some of these exceptions with their names and a short description.

Exception name Number Remark


CURSOR ORA-06511 You have tried to open a cursor which is already
ALREADY OPEN open
INVALID CURSOR ORA-01001 Invalid cursor operation such as fetching from a
closed cursor
NO DATA FOUND ORA-01403 A select . . . into or fetch statement returned no
tuple
TOO MANY ROWS ORA-01422 A select . . . into statement returned more than one
tuple
ZERO DIVIDE ORA-01476 You have tried to divide a number by 0

USER DEFINED EXCEPTIONS

Some type of errors can not be identified by in built exception handlers so we can design our own
exceptions to handle situations

To use a exception first we must declare it in the declaration section of PL/SQL block.

A user defined exception must be raised explicitly i.e., you need to specify in your program under
which circumstances an exception must be raised.

The exception statements associated with this exception are specified in the exception handling
section of the block.

DECLARE
Exception_name EXCEPTION;

42
BEGIN
….
IF condition THEN
RAISE exception_name;
ELSE
….
END IF;
EXCEPTION
WHEN exception_name THEN
--Error-Processing Statement;
END;

Example

Q1) Write a PL/SQL block to handle exception when the given sid is negative using user
defined exception?

SQL> declare
a number(10);
b varchar2(10);
c number(10) := &c;
d exception; --exception variable declaration
begin
if c<0 then
raise d; --raising an exception
else
select sid,sname into a,b from sailors where sid = c;
dbms_output.put_line('sailors id = '||a||'sailors Name= '||b);
end if;
exception
when d then --action to be taken
dbms_output.put_line('sailor id can not be negative');
when no_data_found then
dbms_output.put_line('no such sailor found with sid = '||c);
end;
/

Enter value for c: 22


old 4: c number(10) := &c;
new 4: c number(10) := 22;
sailors id = 22sailors Name= dustin

PL/SQL procedure successfully completed.

SQL> /
Enter value for c: -22
old 4: c number(10) := &c;
new 4: c number(10) := -22;
sailor id can not be negative
PL/SQL procedure successfully completed.

43
RAISE_APPLICATION_ERROR

It is a special built in procedure provided by oracle. This procedure allows programmers to create
meaningful error messages for a specific application. This works with user defined exceptions

RAISE_APPLICATION_ERROR(error_number, error_message);

Q2) Write a PL/SQL block to handle exception when the given sid is negative using
RAISE_APPLICATION_ERROR?

SQL> declare
a number(10);
b varchar2(10);
c number(10) := &c;
begin
if c<0 then
raise_application_error(-20000,'sailor id can not be negative');
else
select sid,sname into a,b from sailors where sid = c;
dbms_output.put_line('sailors id = '||a||'sailors Name= '||b);
end if;
exception
when no_data_found then
dbms_output.put_line('no such sailor found with sid = '||c);
end;
/
SQL>
Enter value for c: 22
old 4: c number(10) := &c;
new 4: c number(10) := 22;
sailors id = 22sailors Name= dustin

PL/SQL procedure successfully completed.

SQL> /
Enter value for c: -22
old 4: c number(10) := &c;
new 4: c number(10) := -22;
declare
*
ERROR at line 1:
ORA-20000: sailor id can not be negative
ORA-06512: at line 7
44
EXP.8
AIM: Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.

PL/SQL MODULES
A PL/SQL module is any complete logical unit of work. There are four types of PL/SQL modules:
1) anonymous blocks that are run with a text script( you have used until now), 2) Procedures, 3)
Functions, and 4) Packages.

There are two main benefits to using modular code: 1) it is more reusable and 2) it is more
manageable.

PROCEDUREDS:
A procedure is a module performing one or more actions: it does not need to return any value. The
syntax for creating a procedure is

CREATE OR REPLACE PROCEDURE name


[(parameter 1 {IN,OUT,INOUT} datatype(size),
parameter 2 {IN,OUT,INOUT} datatype(size),….
parameter n {IN,OUT,INOUT} datatype(size))]
{IS|AS}
[local declaration]
BEGIN
--Executable statements
[EXCEPTION
--exception handler]
END [name];

Example:
Q1) Create a procedure to add two number and call the block with a PL/SQL block?
SQL> create or replace procedure sum(a in number,b in number)
is
c number := 1;
begin
c := a+b;
dbms_output.put_line('c value '||c);
end;
/
Procedure created.

SQL> declare
a number := &a;
b number := &b;
begin
45
sum(a,b);
end;
/
SQL> Enter value for a: 10
old 2: a number := &a;
new 2: a number := 10;
Enter value for b: 20
old 3: b number := &b;
new 3: b number := 20;
c value 30
PL/SQL procedure successfully completed.
Q2) Create a procedure to add two number and return the value to a PL/SQL block?
SQL> create or replace procedure sum1(a in number,b in number,d out number)
is
c number := 1;
begin
c := a+b;
d:=c;
end;
/
Procedure created.
SQL> declare
a number := &a;
b number := &b;
d number;
begin
sum1(a,b,d);
dbms_output.put_line('addition= '||d);
end;
/
SQL> Enter value for a: 10
old 2: a number := &a;
new 2: a number := 10;
Enter value for b: 30
old 3: b number := &b;
new 3: b number := 30;
addition= 40
PL/SQL procedure successfully completed.

Q2) Create a procedure to accept sailors sid and return age of sailor to a PL/SQL block?
SQL> create or replace procedure sail(a in number,b out number)
is
c number;
begin
select age into c from sailors where sid = a;
b := c;
exception
when no_data_found then
dbms_output.put_line('no such sailors');
end;
/
Procedure created.

SQL> declare
46
a number := &a;
b number;
begin
sail(a,b);
dbms_output.put_line('sailors with '||a||' has age '||b);
end;
/
SQL> Enter value for a: 64
old 2: a number := &a;
new 2: a number := 64;
sailors with 64 has age 35
PL/SQL procedure successfully completed.

EXP.9
AIM: Program development using creation of stored functions, invoke functions in SQL
Statements and
write complex functions.

FUNCTIONS

The syntax for creating a function is as follows:

CREATE OR REPLACE FUNCTION name


[(parameter 1 {IN,OUT,INOUT} datatype(size),
parameter 2 {IN,OUT,INOUT} datatype(size),….
parameter n {IN,OUT,INOUT} datatype(size))]
RETURN datatype
{IS|AS}
[local declaration]
BEGIN
Executable statements
[EXCEPTION
exception handler]
END [name];

The function does not necessarily have any parameters, but it must have a RETURN value
declared in the header, and it must return values for all the varying possible execution streams.

Q1) Create a function to add two numberS and return the value to a PL/SQL block?

SQL> create or replace function addfun(a in number, b in number)


return number
as
c number;
begin
c:=a+b;
return c;
end;
/
Function created.

SQL> declare
a number:=&a;
b number:=&b;
47
d number;
begin
d := addfun(a,b);
dbms_output.put_line('Addtion value='||c);
end;
/
SQL> Enter value for a: 20
old 2: a number := &a;
new 2: a number := 20;
Enter value for b: 30
old 3: b number := &b;
new 3: b number := 30;
Addition value= 50
PL/SQL procedure successfully completed.
Q2) Create a function to accept sailors sid and return age of sailor to a PL/SQL block?

SQL> create or replace function sailf(a in number)


return number
as
b number;
begin
select age into b from sailors where sid=a;
return b;
exception
when no_data_found then
dbms_output.put_line('no such sailors exists with given sid= '||a);
end;
/

Function created.

SQL> declare
a number:= &a;
c number;
begin
c := sailf(a);
dbms_output.put_line('sailor with sid '||a||'has age '||c);
end;
/
SQL>
Enter value for a: 58
old 2: a number:= &a;
new 2: a number:= 58;
sailor with sid 58has age 35

PL/SQL procedure successfully completed.

48
EXP. 10:
AIM: Program development using creation of package specification, package bodies, private
objects,
package variables and calling stored packages.

PACKAGES:
We can use package as a method to bundle your functions and procedures, the first being that a
well designed package is a logical grouping of objects – such as functions, procedures, global
variables and cursors.

The package specification:


This contains information about the contents of the package, but not the code for the procedures or
functions. It also contains declarations of global/public variables. Anything placed in the
declarative section of a Pl/SQL block may be coded in a package specification.

The package Body:


The package body contains the actual executable code for the objects described in the package
specification. The package body contains code for all procedures and functions described in the
specification and may additionally contain code for objects not declared in the specification.

Referencing Package Elements:


Use the following notation when calling packaged elements from outside of the package:
package_name.elements.

Example:
Q1) Create a package which contains a procedure to add two numbers and a function which will
subtract two numbers?

SQL> create or replace package packex


as
procedure sum3(a in number, b in number);
function f1(a in number, b in number) return number;
end packex;
/
Package created.
SQL> create or replace package body packex
as
procedure sum3(a in number, b in number)
is
c number;
begin
49
c := a+b;
dbms_output.put_line('additon= '||c);
end;
function f1(a in number, b in number) return number
is
d number;
begin
d:=a+b;
return d;
end;
end packex;
/
Package body created.
SQL> declare
a number := &a;
b number := &b;
d number;
begin
packex.sum3(a,b);
d:= packex.f1(a,b);
dbms_output.put_line('subtraction= '||d);
end;
/
SQL> Enter value for a: 40
old 2: a number := &a;
new 2: a number := 45;
Enter value for b: 40
old 2: b number := &b;
new 2: b number := 30;

addition= 70
subtraction= 10

PL/SQL procedure successfully completed.

50
EXP.11
AIM: Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR,
WHERE CURRENT of clause and CURSOR variables.

CURSOR:

A cursor is a handle or pointer to the context area. Through the cursor a PL/SQL program can
control the context area and what happens to it as the statements is processed.
1) Cursor allow you to fetch and process rows returned by a SELECT statement, one row at a time.
2) A cursor is named so that it can be referenced.

TYPES OF CURSORS:
1. An implicit cursor is automatically declared by oracle every time an SQL statement is
executed. The user will not be aware of this happening and will not be able to control or
process the information in an implicit cursor.
2. An explicit cursor is defined by the program for any query that returns more than one
row of data. That means the programmer has declared the cursor within the PL/SQL
code block. This declaration allows for the application to sequentially process each row
of data as it is returned by the cursor.

IMPLICIT CURSOR
In order to better understand the capabilities of an explicit cursor, you first need to run through the
process of an implicit cursor.
1) Any given PL/SQL block issues an implicit cursor when ever an SQL statement is
executed, as long as an explicit cursor does not exist for that SQL statement.
2) A cursor is automatically associated with every DML statement.
3) All UPDATE and DELETE statements have cursors that identify the set od rows that
will be affected by the operations.
4) An INSERT statement needs a place to receive the data that is to be inserted in the
database; the implicit cursor fulfills this need.
5) The most recently opened cursor is called the ‘SQL%’ cursor.

EXPLICIT CURSOR
The only means of generating an explicit cursor is for the cursor to be named in the DECLARE
section of the PL/SQL block.

1) Declaring the cursor defines the name of the cursor and associatedit with a SELECT
statements CURSOR cursor_name IS SELECT statement
2) Opening the cursor is to process the select statement and set a active pointer to the first
row OPEN cursor_name;
3) Fetching cursor into PL/SQL local variables, these variables are declared as
ROWTYPE in declare section FETCH cursor_name INTO PL/SQL variables
51
4) Closing a cursor by CLOSE cursor_name;
Explicit cursor attributes:
Cursor Syntax Explanation
Attribute
%NOTFOUN Cursor_name A Boolean attribute that returns TRUE if the
D %NOTFOUND previous FETCH did not return a row and FALSE
if it did
%FOUND Cursor_name%FOUND A Boolean attribute that returns TRUE if the
previous FETCH did return a row and FALSE if it
did not
%ROWCOUN Cursor_name No. of records fetched from a cursor at that point in
T %ROWCOUNT time
%ISOPEN Cursor_name%ISOPEN A Boolean attribute that returns TRUE if cursor is
open, FALSE if it is not.

Q1) Create a cursor which fetches data from sailors table whose rating is greater than 5?
SQL> declare
cursor sail is select sid,sname,age from sailors where rating>5;
s sail%rowtype;
begin
open sail;
loop
fetch sail into s;
exit when sail%notfound;
dbms_output.put_line('sailor sid = '||s.sid||' name = '||s.sname||' age =
'||s.age);
end loop;
close sail;
end;
/
SQL> sailor sid = 64 name = horatio age = 35
sailor sid = 22 name = dustin age = 45
sailor sid = 31 name = lubber age = 55.5
sailor sid = 32 name = andy age = 25.5
sailor sid = 58 name = rusty age = 35
sailor sid = 71 name = zobra age = 16
sailor sid = 74 name = horatio age = 35

PL/SQL procedure successfully completed.

Q2) Create a cursor which fetches data from boats table?


SQL> declare
cursor bt is select * from boats;
b bt%rowtype;
begin
open bt;
loop
fetch bt into b;
exit when bt%notfound;
dbms_output.put_line('boat bid = '||b.bid||' name = '||b.bname||' color
= ‘||b.color);

52
end loop;
close bt;
end;

SQL> /
boat bid = 101 name = interlake color = blue
boat bid = 102 name = interlake color = red
boat bid = 103 name = clipper color = green
boat bid = 104 name = marine color = red

PL/SQL procedure successfully completed.

Q3) Create cursor which fetches data from reserves table where sid is22

SQL> declare
cursor reser is select * from reserves where sid=22;
r reser%rowtype;
begin
open reser;
loop
fetch reser into r;
exit when reser%notfound;
dbms_output.put_line('reserve sid = '||r.sid||' bid = '||r.bid||' day = '||
r.day);
end loop;
close reser;
end;
/
SQL>
reserve sid = 22 bid = 101 day = 10-OCT-98
reserve sid = 22 bid = 102 day = 10-OCT-98
reserve sid = 22 bid = 103 day = 10-SEP-98
reserve sid = 22 bid = 104 day = 10-JUL-98

PL/SQL procedure successfully completed.

53
EXP.12
AIM: Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers
TRIGGERS
The Oracle RDBMS has the ability to store procedures within the data dictionary and execute
procedures in the RDBMS. Procedures (Program Units) are written in the PL/SQL language
(Procedural Language), which is proprietary to Oracle. PL/SQL runs in both the database engine as
well as in many of Oracle's development tools such as Oracle Developer.

It is common practice to store general business rule checking in procedures. This allows
applications to check data validity before a transaction is submitted to the database. Triggers can
also call the procedures to check data at the database level. Since the business rules are coded in a
single set of procedures, maintenance of this code is simplified. In this section, we will introduce
the syntax for creating triggers and demonstrate the use of a trigger to enforce a business rule.

Trigger Syntax

Creating a trigger is accomplished with the CREATE TRIGGER statement. There are numerous
options for a trigger that specify when the trigger should fire. These options include:

 The SQL statement (INSERT, UPDATE, DELETE, SELECT) that causes the event. An
event can include more than one SQL statement per trigger.
 The timing when the trigger code is executed. Options here include
o BEFORE - The trigger code is executed before the effects of the SQL statement are
put into place.
o INSTEAD OF - The trigger code is executed instead of the normal SQL statement.
o AFTER - The trigger code is executed after the normal SQL statement is processed.
 Some SQL statements such as UPDATE, DELETE and SELECT may affect more than one
row. Triggers may be specified to fire once for the SQL statement or once for each row
affected by the SQL statement.

Example:
Q1) To write a TRIGGER to ensure that SAILORS TABLE does not contain duplicate of null
values in SID column.

SQL> CREATE OR RELPLACE TRIGGER trig1


before insert on sailors
for each row
DECLARE
a number;
BEGIN
if(:new.sid is Null) then
raise_application_error(-20001,'error::sid cannot be null');

54
else
select count(*) into a from sailors where sid=:new.sid;
if(a=1) then
raise_application_error(-20002,'error:: cannot have duplicate sid');
end if;
end if;
END;
/
Trigger created.

SQL>select * from sailors;

SID SNAME RATING AGE


22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zobra 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5

SQL> insert into sailors values(&sid,'&sname',&rating,&age);


Enter value for sid: null
Enter value for sname: mark
Enter value for rating: 7
Enter value for age: 35.5
old 1: insert into sailors values((&sid,'&sname',&rating,&age)
new 1: insert into sailors values(null,’mark',7,35.5)
insert into sailors values(null,’mark',7,35.5)
*
ERROR at line 1:
ORA-20001: error::sid cannot be null
ORA-06512: at "SCOTT.TRIG1", line 5
ORA-04088: error during execution of trigger 'SCOTT.TRIG1'
SQL> /
Enter value for deptnp: 22
Enter value for dname: mana
Enter value for rating: 9
Enter value for age:25.5
old 1: insert into sailors values((&sid,'&sname',&rating,&age)
new 1: insert into sailors values(22,’mana’,9,25.5)
insert into sailors values(22,’mana’,9,25.5))
*
ERROR at line 1:
ORA-20002: error:: cannot have duplicate sid
ORA-06512: at "SCOTT.TRIG1", line 9
ORA-04088: error during execution of trigger 'SCOTT.TRIG1'
SQL> /
Enter value for deptnp: 30

55
Enter value for dname: mana
Enter value for rating: 9
Enter value for age:25.5
old 1: insert into sailors values((&sid,'&sname',&rating,&age)
new 1: insert into sailors values(30,’mana’,9,25.5)
1 row created

SQL>select * from sailors;

SID SNAME RATING AGE


22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zobra 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5
30 mana 9 25.5

56

You might also like