Está en la página 1de 39

1.

INTRODUCTION

Every business enterprise maintains large volumes of data for its operations .With
more and more people accessing this data for their work, the need to maintain its
integrity and relevance increases. Normally with the traditional methods of storing
data and information in the files, the chances those data losses its integrity and
validity are very high.

ORACLE is an object relational database management system. It offers


capabilities of both relational and object oriented database systems. Oracle
products are based on a concept known as client/server technology. This
concept involves segregating the processing of an application between two
systems. One performs all activities related to the database (server) and the other
performs activities that help the user to interact with the application (client).

The tools provided by oracle are user friendly. The main tools are:

1. SQL*PLUS

2. PL/SQL

SQL*PLUS

It is structured query language supported by Oracle. Using this we can store,


retrieve, edit, enter and run SQL commands and PL/SQL blocks. We can also
perform calculations on listed definitions for any table and can also format results
in the form of a report.

PL/SQL

It is an extension of SQL. It combines the data manipulating process of SQL with


data processing process of procedural language.

1
2. STRUCTURED QUERY LANGUAGE

SQL was invented and developed by IBM in early 1970’s.Oracle’s database


language is SQL, which is used for storing and retrieving information in oracle.

A table is primary database object of SQL that is used to store data. A table holds
data in the form of rows and columns.

SQL supports the following categories of commands:

Data Definition Language -create, alter, and drop commands.


Data Manipulation Language-insert, delete and update commands.
Data Retrieval Language-select.
Data Control Language- grants and revokes commands.
Transaction Control Language-commit, save point and rollback.

The following are the Benefits on SQL:

1. Non-procedural language because more than one record can be


accesses rather than one record at a time.
2. It is the common language for all relation.
3. Very simple commands for querying, inserting, deleting and modifying
data and objects.

Oracle internal data types

In order to create a table we need to specify a data type for individual columns in
the create table command. Oracle supports the following data types to achieve the
above requirements.
1. Character data types 7. Raw
2. Char data types 8. Long raw
3. Varchar2 data types 9. Large object
4. Long data types 10. CLOB
5. Number data types 11. BLOB
6. Data data types 12. BFILE

Thus in order to create a table we need to specify a data type for individual
columns in the create table command.

Thus Oracle supports the data types to achieve the above requirements.

2
3. DATA DEFINITION LANGUAGE

The DDL is used to create an object (eg. Table), alter the structure of an object
and also to drop the object created.

Table Definition:

A table is a unit of storage that holds data in the form of rows and columns. The
DDL is used for table definition and can classify into:

1. Create table command.


2. Alter table command.
3. Truncate table command.
4. Drop table command.

1. CREATE:

SYNTAX:
Create table<table name>
(column definition1<data type (length)>
column definition1<data type (length)>….);

2. ALTER

SYNTAX:
ALTER table<table name>modify (column definition1);

3. TRUNCATE

SYNTAX:
TRUNCATE table<table name>;

4. DROP

SYNTAX:
DROP table<table name>;

3
4. Use DML statements for database tables.

SQL>create table student2 (rno number (3), name varchar2 (10),


m1 number (3),
m2 number (3),
m3 number (3),
total number (3),
percentage number (5,2));

Table created.

Implementation of insert command.

SQL>insert into student2 (rno, name, m1, m2, m3)


Values (&rno,’&name’, &m1, &m2, &m3);
Enter value for rno:1
Enter value for name: Naresh
Enter value for m1: 75
Enter value for m2: 65
Enter value for m3: 85
old 2: values (&rno, ‘&name’,&m1, &m2, &m3)
new 2: values (1,’Naresh’,75,65,85)

1 row created.
SQL>/
Enter value for rno:2
Enter value for name: Anitha
Enter value for m1: 65
Enter value for m2: 88
Enter value for m3: 56
old 2: values (&rno, ‘&name’,&m1, &m2, &m3)
new 2: values (2,’Anitha’,65,88,56)

1 row created.
SQL>/
Enter value for rno:3
Enter value for name: Padma
Enter value for m1: 45
Enter value for m2: 78
Enter value for m3: 96
old 2: values (&rno, ‘&name’, &m1, &m2, &m3)
new 2: values (3,’Padma’, 45,78,96)

1 row created.

4
SQL>select * from student2;

RNO NAME M1 M2 M3 TOTAL PERCENTAGE


------ --------- ----- ----- ----- -------- ----------------
1 Naresh 75 65 85
2 Anitha 65 88 56
3 Padma 45 78 96

Implementation of update command

SQL>update student2 set total=m1+m2+m3;


3 rows updated.

SQL>select *from student2;

RNO NAME M1 M2 M3 TOTAL PERCENTAGE


------ --------- ----- ----- ----- --------- --------------------
1 Naresh 75 65 85 225
2 Anitha 65 88 56 209
3 Padma 45 78 96 219

SQL>update student2 set percentage=total/3;


3 rows updated.

SQL>select *from student2;

RNO NAME M1 M2 M3 TOTAL PERCENTAGE


------ --------- ----- ------ ----- ----------- --------------------
1 Naresh 75 65 85 225 75
2 Anitha 65 88 56 209 69.67
3 Padma 45 78 96 219 73

Implementation of delete command

SQL>delete from student3 where rno=3;

1 row deleted.

SQL>select *from student2;

RNO AME M1 M2 M3 TOTAL PERCENTAGE


------ --------- ----- ----- ----- ----------- --------------------
1 Naresh 75 65 85 225 75
2 Anitha 65 88 56 209 69.67

5
5. DDL COMMANDS

STUDENT TABLE

1. CREATE A STUDENT TABLE HAVING ROLL NO, NAME, CLASS AND


MARKS IN 3 SUBJECTS

SQL>create table student3 (rno varchar2 (7), name char (10), class varchar2
(10),
m1 number (3),
m2 number (3),
m3 number (3));

Table created.

2. DESCRIPTION OF THE TABLE

SQL>desc student3;

Name Null? Type


--------- --------- --------
RNO VARCHAR2 (7)
NAME CHAR (10)
CLASS VARCHAR2 (10)
M1 NUMBER(3)
M2 NUMBER(3)
M3 NUMBER(3)

3. INSERT CONSTANT VALUES

SQL>insert into student3 (rno, name, class) values (05109094,’Nani’,’mca’);

1 row created.

4. INSERT VARYING VALUES

SQL>insert into student3 (rno, name, class) values (&rno,’&name’,’&class’);


Enter value for rno: 05109008
Enter value for name:Reddy
Enter value for class:msc
old 1:insert into student3(rno,name,class)values(&rno,’&name’,’&class’)
new 1;insert into student3(rno,name,class)values(05109008,’reddy’,’msc’)

1 row created.

6
SQL>/
Enter value for rno: 05109054
Enter value for name:Raj
Enter value for class:mba
old 1:insert into student3(rno,name,class)values(&rno,’&name’,’&class’)
new 1;insert into student3(rno,name,class)values(05109054,’raj’,’mba’)

1 row created.

SQL>/
Enter value for rno: 05109083
Enter value for name:Bobby
Enter value for class:mcom
old 1:insert into student3(rno,name,class)values(&rno,’&name’,’&class’)
new 1;insert into student3(rno,name,class)values(05109083,’bobby’,’mcom’)

1 row created.

5. INSERT A ROW WITH ROLL NO, CLASS, AND MARKS IN 3 SUBJECTS

SQL>insert into
student3(rno,class,m1,m2,m3)values(05109113,’mca’,61,82,77);

1 row created.

6. LIST THE CONTENTS OF THE TABLE

SQL>select*from student3;

RNO NAME CLASS M1 M2 M3


------- ---------- ----------- ----- ----- ------
5109094 NANI mca
5109008 REDDY msc
5109054 RAJ mba
5109083 BOBBY mcom
5109113 mca 61 82 77

7. ADD NEW COLUMN TO THE TABLE AS TOTAL

SQL>alter table student3 add (total number (3));

Table altered.

7
SQL>desc student3;

Name Null? Type


--------- --------- --------
RNO VARCHAR2 (7)
NAME CHAR (10)
CLASS VARCHAR2 (10)
M1 NUMBER(3)
M2 NUMBER(3)
M3 NUMBER(3)
TOTAL NUMBER(3)

8. UPDATE THE TOTAL COLUMN IN THE TOTAL

SQL>update student3 set total=m1+m2+m3;

5 rows updated.

SQL> select*from student3;

RNO NAME CLASS M1 M2 M3 TOTAL


------- ---------- ----------- ----- ----- ------ ------------
5109094 NANI mca
5109008 REDDY msc
5109054 RAJ mba
5109083 BOBBY mcom
5109113 mca 61 82 77 220

9. ALTER THE NAME COLUMN WIDTH TO 25 CHARECTERS

SQL>alter table student3 modify (name char (25));

Table altered.

SQL>desc student3;

Name Null? Type


--------- --------- --------
RNO VARCHAR2 (7)
NAME CHAR (25)
CLASS VARCHAR2 (10)
M1 NUMBER (3)
M2 NUMBER (3)
M3 NUMBER (3)
TOTAL NUMBER (3)

8
10. MAKE DUPLICATE COPY OF THE TABLE

SQL>create table dup_std1 as select * from student3;


Table created.

11. COPY THE CONTENTS ROLL NO<NAME AND CLASS INTO THE NEW
TABLE

SQL>create table new_std1 as select rno,name,class from student3;

Table created.

SQL>desc new_std1;

Name Null? Type


--------- --------- --------
RNO VARCHAR2 (7)
NAME CHAR (25)
CLASS VARCHAR2 (10)

12. DELETE THE CONTENTS OF THE NEW TABLE

SQL>delete from new_std1;

5 rows deleted.

13. DROP THE STUDENT TABLE

SQL>drop table student3;

Table dropped.

9
6. NUMERIC FUNCTIONS

Accepts numeric input and returns values as output.

1. abs (n):
SQL>select abs (-53) from dual;
ABS (-53)
53

2. ceil(n):
SQL>select ceil (53.35) from dual;
CEIL(53.35)
54

3. exp(n):
SQL>select exp (3) from dual;
EXP (3)
20..85537

4. floor (n):
SQL>select floor (53.35) from dual;
FLOOR (53.35)
53

5. power (m,n):
SQL> select power (5,3) from dual;
POWER(5,3)
125

6. mod (m,n):
SQL>select mod (5,3) from dual;
MOD (5,3)
2

7. round (m,n):
SQL>select round (53.2568,2) from dual;
ROUND (53.2568,2)
53.25

8. trunk (m,n):
SQL>select trunk(53.2568,2) from dual;
TRUNC (53.2568,2)
53.25

10
9. sqrt (n):
SQL>select sqrt (4) from dual;
SQRT (4)
2

7. CHARACTER FUNCTIONS

Accepts character input and returns either character or number values.


1.initcap (char):
SQL>select initcap (‘wesley’) from dual;
INITCA
WESLEY

2. lower (char):
SQL>select lower (‘LUCKY’) from dual;
LOWER(‘LUCKY’)
Lucky

3. upper (char):
SQL>select upper (‘anu’) from dual;
UPPER(‘anu’)
ANU

4. rtrim (char,set):
SQL>select rtrim(‘WESLEY COLLEGE’,’COLLEGE’)from dual;
RTRIM (‘WESLEY COLLEGE’,’COLLEGE’)
WESLEY

5. ltrim (char, set):


SQL>select ltrim(‘WESLEY COLLEGE’,’WESLEY’)from dual;
LTRIM (‘WESLEY COLLEGE’,’WESLEY’)
COLLEGE

6. translate (char,from,to):
SQL>select translate (‘brown’,’b’,’c’) from dual;
TRANS
Crown

7. substr (char,m,n) :
SQL>select substr (‘welcome’,4,4) from dual;
SUBS
Come

11
8. soundex: This function words that are spelled differently but sound alike.

SQL>select sname from sailors where soundex(sname)=soundex(‘nani’);


SNAME
NANI

8. CONVERSION FUNCTIONS

1. to char(): It converts date to character.

SYNTAX: to_char (d,[fmt])

SQL>select to_char(sysdate,’ddth ”of” fmmonth yyyy’) from dual;

TO_CHAR
20th of October 2007

2. to date(): it converts character to date.

SYNTAX:to_date (char,[fmt])

SQL>select to_date (‘aug 15 47’,’mon-dd-yy’) from dual;

TO_DATE
15-AUG-47

GENERAL FUNCTIONS:

1. SQL>select greatest (53, 35, 99) from dual;

GREATEST:
99

2. SQL>select least (53, 35, 99) from dual;

LEAST:
35

12
9. DATE FUNCTIONS

1. add months:

Syntax: add_months (d,n) where d is date & n is no. of months.

SQL> select add_months (sysdate,12)from dual;

If sysdate is 21-OCT-08 result is


ADD_MONTH
20-OCT-08

2. last day:

Syntax: last_day (d) displays last day of the month.

SQL>select last_day (sysdate) from dual;

LAST_DAY 31-OCT-07

3. months between:

Syntax: months_between (d1, d2), returns no of months between two dates.

SQL>select months_between (’11-09-06’,’dd-mm-yy’),

(to_date (’20-10-07’,’dd-mm-yy’)))from dual;

MONTHS_BETWEEN
-13.29032

4. next day:

Syntax: next_day (d, day), where d represents date & day represents weekday.

SQL>select next_day (sysdate,’sunday’) from dual;

NEXT_DAY
21-OCT-07

13
5. round:

Syntax: round (d, [fmt])

SQL>select round (to_date (’20-Oct-07’,’dd-mm-yy’),’year’) from dual;

ROUND
01-JAN-08

6. truncate:

Syntax: trunc(d,[fmt])

SQL>select trunk (to_date (’20-OCT-07’,’dd-mm-yy’),’month’) from dual;

TRUNC :
01-OCT-07

7. greatest:

Syntax: gratest(d1,d2),returns latest date present in the arg.

SQL>select greatest (to_date(’20-oct-07’,’dd-mm-yy’),

(to_date(’30-oct-07’,’dd-mm-yy’)))from dual;

GREATEST
31-OCT-07

14
PROGRAM:

10. CREATE QUERIES USING ORDER BY AND GROUP BY CLAUSE.

ORDER BY CLAUSE:
This clause is used to arrange the retrived data in some sorted manner. By default
the sorting is done in ascending order .The clause should be spwcified just before
the statement terminates.

1. List the department numbers and department names sorted on


department name.

SQL>select deptno, dname from dept order by dname;

DEPTNO DNAME
10 ACCOUNTING
40 OPERATIONS
20 RESEARCH
30 SALES

2. Display the employees information in ascending order of salary.

SQL>select * from emp order by sal;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7369 SMITH CLERK 7902 17-DEC-80 800 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-sep-81 1250 1400 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7499 ALLEN SALESMAN 7698 20-FEB-81 2450 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7566 JONES MANAGER 7839 02-APR-81 975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7839 LUCKY PRESIDENT 16-NOV-81 5000 10

14 rows selected.

15
3. Display the employees information in descending order of salary.

SQL>select empno, ename, sal from emp order by sal desc;

EMPNO ENAME SAL


7839 LUCKY 5000
7788 SCOTT 3000
7902 FORD 3000
7566 JONES 2975
7698 BLAKE 2850
7782 CLARK 2450
7499 ALLEN 1600
7844 TURNER 1500
7934 MILLER 1300
7521 WARD 1250
7654 MARTIN 1250
7876 ADAMS 1100
7900 JAMES 950
7369 SMITH 800

14 rows selected.

GROUP BY CLAUSE:

This clause places condition on group of records. Group by clause is used when
aggregate operators to be applied to each of row in a relation where the number
of groups depends on the relation instance.

SYNTAX:

Select [DIATINCT] select-list


From from-list
Where<condition>
Group By grouping-list

1.list the count of different jobs held by employees in Deptno 30.

SQL>select count (job) from emp where deptno=30 group by job;

COUNT(JOB)
1
1
4

2.list the average salary in each department.

16
SQL> select deptno, avg(sal) from emp group by deptno;

DEPTNO AVG(sal)
10 2916.6667
20 2175
30 1566.6667

3. count the employees and calculate the avg salary in each job group in
each Department

SQL> select deptno, job, count (*), avg (sal) from emp group by job, deptno;

DEPTNO JOB COUNT (*) AVG (SAL)


20 ANALYST 2 3000
10 CLERK 1 1300
20 CLERK 2 950
30 CLERK 1 950
10 MANAGER 1 2450
20 MANAGER 1 2975
30 MANAGER 1 2850
10 PRESIDENT 1 5000
30 SALESMAN 4 1400

9 rows selected.

HAVING CLAUSE:

This clause is used to specify condition/ qualifications over group. The


expressions appearing in the group qualification of having clause must a single
value of group i.e, having clause determines whether row is to be generated for a
given group

SYNTAX:

Select [DIATINCT] select-list


From from-list
Where<condition>
Group By grouping-list
Having group-qualification.

1. .find the average salary in each department.where dept has atleast 2


employees

17
SQL> select deptno, avg(sal) from emp group by deptno having count(*)>1;

DEPTNO AVG(sal)
10 2916.6667
20 2175
30 1566.6667

PROGRAM:

11. CREATE QUERIES USING EQUI JOINS, OUTER JOINS, SELF JOIN and
CARTESIAN JOIN.

JOINS:

Join is a select command that combines rows from two or more tables i.e. It
extracts information from more than one table

Types of joins:
1. Equijoin
2. Non-equijoin.

A. EQUIJOIN:

Equijoins exits when there is a common attribute in both the table.

Types of joins:
a. self join
b. outer join.

1. List employee name, department name of all employees displaying in


a sorted order of dept Name.

SQL>select ename, dname from emp, dept where emp.deptno=dept.deptno


order by dname;

ENAME DNAME
CLARK ACCOUNTING
LUCKY ACCOUNTING
MILLER ACCOUNTING
SMITH RESEARCH
ADAMS RESEARCH
FORD RESEARCH
SCOTT RESEARCH
JONES RESEARCH

18
ALLEN SALES
BLAKE SALES
MARTIN SALES
JAMES SALES
TURNER SALES
WARD SALES

14 rows selected.

B. SELF JOIN:

A join between a table and itself is called a self join.

1. Display employee number and name along with their manager’s


number and name.

SQL>select e.empno, e.ename, e.mgr, m.ename from emp e, emp m where


e.mgr=m.empno;

EMPNO ENAME MGR ENAME


7369 SMITH 7902 FORD
7499 ALLEN 7698 BLAKE
7521 WARD 7698 BLAKE
7566 JONES 7839 LUCKY
7654 MARTIN 7698 BLAKE
7698 BLAKE 7839 LUCKY
7782 CLARK 7839 LUCKY
7788 SCOTT 7566 JONES
7844 TURNER 7698 BLAKE
7876 ADAMS 7788 SCOTT
7900 JAMES 7698 BLAKE
7902 FORD 7566 JONES
7934 MILLER 7782 CLARK

13 rows selected.

C.OUTER JOIN:

19
Outer join displays all information from both the tables.

1. List all department numbers, names along with their employee names.

SQL>select ename, dname from emp, dept where emp.deptno=dept.deptno &


dept.deptno in
(30,40);
ENAME DNAME
ALLEN SALES
WARD SALES
MARTIN SALES
BLAKE SALES
TURNER SALES
JAMES SALES

6 rows selected.

D.NON-EQUI JOIN

Exits when there are no common attributes in the tables.

1. Display employee numbers, names and grade of all employees.

SQL>select empno, ename, job, grade from emp, salgrade where sal between
losal & hisal;

EMPNO ENAME JOB GRADE


7369 SMITH CLERK 1
7876 ADAMS CLERK 1
7900 JAMES CLERK 1
7521 WARD SALESMAN 2
7654 MARTIN SALESMAN 2
7934 MILLER CLERK 2
7499 ALLEN SALESMAN 3
7844 TURNER SALESMAN 3
7566 JONES MANAGER 4
7698 BLAKE MANAGER 4
7782 CLARK MANAGER 4
7788 SCOTT ANALYST 4
7902 FORD ANALYST 4
7839 LUCKY PRESIDENT 5

14 rows selected

20
E.CARTESIAN JOIN:

The output of this join takes one row from the 1st table and combines with all the
rows of 2nd table. Likewise all rows of 1st table get combined with all the rows of
2nd table.

EXAMPLE:

A= {1, 2, 3}
B= {4, 5}

The Cartesian product of {A,B} is={(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)}

SQL> select empno, ename, dname , loc from emp, dept;

EMPNO ENAME DNAME LOC


7369 SMITH ACCOUNTING NEWYORK
7499 ALLEN ACCOUNTING NEWYORK
7521 WARD ACCOUNTING NEWYORK
7566 JONES ACCOUNTING NEWYORK
------- ---------- -------------------- ---------------
------- ---------- -------------------- ---------------
56 rows selected.

PROGRAM

12. Use commands on locks.

LOCKS:

A lock is a small book-keeping object associated with a database

There are 2 types of locks


1. Row level Lock
2. Table level Lock.

IMPLEMENTATION OF LOCKS

1. Row level Lock:

SQL> select * from sailors where Sid=95 for update of age;

SID SNAME RATING AGE


95 Lucky 3 64

2. Table level Lock:

21
SQL>lock table sailors in share mode;

Table(s) Locked.

SQL>lock table sailors in share update mode;

Table(s) Locked.

SQL>lock table sailors in exclusive mode;

Table(s) Locked.

PROGRAM:

13.Create queries on multiple tables.

1. List employee name, department name of all employees displaying in a


sorted order of dept name.

SQL>select e.ename, d.deptno, d.dname from emp e, dept d where


e.deptno=d.deptno;

ENAME DEPTNO DNAME


SMITH 20 RESEARCH
ALLEN 30 SALES
WARD 30 SALES
JONES 20 RESEARCH
MARTIN 30 SALES
BLAKE 30 SALES
CLARK 10 ACCOUNTING
SCOTT 20 RESEARCH
LUCKY 10 ACCOUNTING
TURNER 30 SALES
ADAMS 20 RESEARCH
JAMES 30 SALES
FORD 20 RESEARCH
MILLER 10 ACCOUNTING

14 rows selected.

2. List all employees who are working in CHICAGO.

22
SQL>select ename from emp e, dept d where e.deptno=d.deptno and
loc=’Chicago’;

ENAME
ALLEN
WARD
MARTIN
BLAKE
TURNER
JAMES

6 rows selected.

14. CREATE QUERIES USING ROW FUNCTIONS.

FUNCTION:

A function takes one or more arguments and returns a value. Functions supported
by SQL are classified into:
a. Single row functions.
b. Group functions.

SINGLE ROW FUNCTIONS:

A single row function or a scalar function returns only one value for a row queried
in the table. Single row functions can appear in a select command and also
Can be included in a where clause.

NOTE:

“Dual” is a system table which is automatically created by ORACLE. It has one


column defined to be of varchar2 type and contains only one row with value ‘x’.

There are 5 types of single row functions.

a. Numeric Functions.
b. Character Functions.
c. Conversion Functions.
d. General Functions.
e. Date Functions.

PROGRAM;

23
15.Create views, synonyms, sequences, indexes.

1.VIEWS:

A view is a virtual table. It does not actually exist in the database, but is accessed
Just like a normal table.

Creating Views:

SQL>create view emp_view as select empno,ename from emp;


View created.

SQL>select * from emp_view;

EMPNO ENAME
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 LUCKY
7844 TURNER
7876 ADAMS
7900 JAMES
7901 FORD
7934 MILLER

14 rows selected.

2. SYNONYM:

A synonym is an alternative name(or alias) for a database object such as a


Table or view. They are useful for references purposes, providing security
Etc.

Creating Synonym:

SQL> create synonym dept-syn for dept;


Synonym created.

SQL> select * from dept_syn;

DEPTNO DNAME LOC


10 ACCOUNTING NEWYORK

24
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
4 rows selected.

3. SEQUENCE:

Oracle generates a series of numbers for a particular table in the database. For
e.g: Generating unique numbers such as invoice numbers or customer ID
numbers. While defining a sequence specify the starting value.

Creating Sequencing:

SQL>create sequence emp_seq start with 5000 increment by 1;


Sequence created.

SQL>select emp_seq.nextval from dual;

NEXTVAL
5000

SQL>select emp_seq.nextval from dual;

NEXTVAL
5001

SQL>select emp_seq.nextval from dual;

NEXTVAL
5002

4.INDEXES:

Indexes are special objects that oracle creates to provide rapid access (lookups)
to Tables in database.

Creating Indexes:

SQL>create index emp_ind on emp (ename);


Index created.

PL/SQL

25
16. INTRODUCTION TO PL/SQL

PL/SQL stands for Procedural Language /SQL. PL/SQL by adding control


structures found in other procedural language.PL/SQL is unique as it combines
the flexibility of SQL with the power and configurability of a third generation
language.

PL/SQL BLOCK

Declare: Declaration of memory variables, constants, cursors etc in PL/SQL.

Begin: SQL executable statements PL/SQL executable statements.

Exception: PL/SQL code to handle errors that may arise during the execution of a
code Block between begin and exception.

End: End of the code.

THE CHARACTER SET

The basic character set includes the following:

• Upper case alphabets: {A-Z}.


• Lower case alphabets: {a, b}.
• Numerals: {0, 9}.
• Symbols: (),+,-,/,<,>,=,!,;,:,.,@.%,#,$,^.

LITERALS

A literal is a numeric values or a character string used to represent itself. There


are 4 types of literals. They are:
> Numeric literal
> String literal
> Character literal
> Logical (Boolean literal)

DATA TYPES

The default data types are integers, chars, date, Boolean and they can have
NULL values

The % type attribute is used to declare the variables based on definitions of


columns in a table

Variable in PL/SQL blocks are ’named’ variables.

26
DBMS-OUTPUT

Is a package that includes a no. of procedures and functions that accumulate


Information in a buffer so that it can be retrived later. These functions can also be
used to display a message to the user.

PUT-LINE

Put-line puts a piece of information in the buffer followed by an end of line


marker. It can also be used to display a message (i.e. it is the message string) to
the user. Put-line accepts only parameter of character data type.

To display message to the user server output should be set to ON.

SYNTAX: SQL> SET SERVEROUTPUT (ON/OFF);

CONDITION CONTROL IN PL/SQL

Sequence of statements can be executed based on certain condition using the ‘ if


statement’. There are 3 forms of statements namely

• If then
• If then else
• If then else if

ITERATIVE CONTROL
A sequence of statements can be executed any number of times using loop
constructs. Loop can be classified into:

• Simple loop
• For loop
• While loop

SEQUENTIAL CONTROL
The “goto” statement allows us to branch to a label unconditionally.

27
17. PROCEDURE

Procedure is a set of logical instructions. Which perform a task, because a


procedure is stored?
In the database it must be named. This distinguishes it from other stored
procedures and make
It possible for application to call it.

Each procedure in a scheme must have a unique name & the name must be a
legal PL/SQL.

SYNTAX:

CREATE [OR REPLACE] PROCEDURE<PROCEDURE NAME>


(<ARG 1 [MODE] DATA TYPE, -------------------------------------- )
IS/AS [LOCAL DECLARATION]
BEGIN [EXCEPTION HANDLING]
END [POCEDURE NAME].

DROPING A PROCEDURE

SYNTAX SQL>DROP PROCEDURE <PROCEDURE NAME>;

PARAMETER MODES

There are 3 types of parameter modes

• IN [DEFAULT]-pass values to procedure.

• OUT -return values to called procedures

• INOUT -pass initial values to stored procedures


& returns updated values from stored procedures.

18. Give an employee no display job n salary should be > 20000.

28
Declare
No emp.empno%type:=&no;
Name emp.ename%type;
Salary emp.sal%type;
Begin
Select ename, sal into name, salary from emp where empno=no;
If salary > 20000 then dbms_output.put_line (‘ename:”||name||”sal:”||salary);
Else dbms_output.put_line (‘since sal<20000, hence it is not displayed’);
End if;
End;

OUTPUT

SQL>/
Enter value for no: 9999
Since sal<20000, hence it is not displayed

PL/SQL procedure successfully completed.

PROGRAM:

19.Write a pl/sql program to display the grade and rank of a student.

29
Fields of std table are(rno, name, c1, c2, c3, total, percentage, result, grade).

SQL> create table std(rno number (3),


name varchar2 (10),
c1 number (3),
c2 number (3),
c3 number (3),
total number (3),
percentage number (5,2));
result varchar2(10),
grade varchar2(10));

Table created.

SQL>insert into student2 (rno, name, c1, c2, c3)


Values (&rno, ’&name’, &c1, &c2, &c3);
Enter value for rno:1
Enter value for name: Nani
Enter value for m1: 60
Enter value for m2: 70
Enter value for m3: 80
old 2: values (&rno, ‘&name’,&c1, &c2, &c3)
new 2: values (1,’Nani’,60,70,80)

1 row created.

SQL>/
Enter value for rno:2
Enter value for name: Anu
Enter value for m1: 71
Enter value for m2: 81
Enter value for m3: 91
old 2: values (&rno, ‘&name’,&c1, &c2, &c3)
new 2: values (2,’Anu’,71,81,91)

1 row created.

SQL>/
Enter value for rno:3
Enter value for name: Lucky
Enter value for m1: 67

30
Enter value for m2: 77
Enter value for m3: 78
old 2: values (&rno, ‘&name’,&c1, &c2, &c3)
new 2: values (3,’Lucky’,67,77,78)

1 row created.

SQL>/
Enter value for rno:4
Enter value for name: Rahul
Enter value for m1: 69
Enter value for m2: 79
Enter value for m3: 87
old 2: values (&rno, ‘&name’,&c1, &c2, &c3)
new 2: values (4,’Rahul’,60,70,80)

1 row created.

SQL>select * from std;

RNO NAME C1 C2 C3 TOTAL PERCENTAGE RESULT GRADE


1 Nani 60 70 80
2 Anu 71 81 91
3 Lucky 67 77 78
4 Rahul 69 79 8

PL/SQL PROGRAM

SQL> set server output on;

31
1 Declare
2 sno number(3);
3 sname varchar2(10);
4 s1 number(3);
5 s2 number(3);
6 s3 number(3);
7 sum1 number(3);
8 per number(5,2);
9 res varchar2(10);
10 grd varchar2(10);
11 Begin
12 select eno, name, c1, c2, c3
13 into
14 sno, sname, s1, s2, s3
15 from std where rno=&sno;
16 sum1:=s1+s2+s3;
17 per:=sum1/3;
18 if s1>34 and s2>34 and s3>34 then
19 res:=’pass’;
20 if(per>60) then
21 grd:=’first’;
22 elseif(per>50) then
23 grd:=’second’;
24 else grd:=’third’;
25 end if;
26 end if;
27 update std set total=sum1, percentage=per,result=res,grade=grd
28 where rno=sno;
29 dbms_output.put_line(‘Rollnumber:’||sno);
30 dbms_output.put_line(‘Student name:’||sname);
31 dbms_output.put_line(‘ Marks1:’||s1);
32 dbms_output.put_line(‘ Marks2:’||s2);
33 dbms_output.put_line(‘ Marks3:’||s3);
34 dbms_output.put_line(‘ Total:’|| sum1);
35 dbms_output.put_line(‘ Percentage:’||per);
36 dbms_output.put_line(‘ Result:’||res);
37 dbms_output.put_line(‘ Grade:’||grd);
38 end;
39 /

SQL>/
Enter value for sno: 1
old 15: from std where rno=&sno;
new 15: from std where rno=1;

32
Rollnumber : 1
Student name: Nani
Marks1: 60
Marks2: 70
Marks3: 80
Total: 210
Percentage: 70
Result: pass
Grade: first

PL/SQL procedure successfully completed.

OUTPUT:

SQL>select * from std;

RNO NAME C1 C2 C3 TOTAL PERCENTAGE RESULT GRADE


1 Nani 60 70 80 210 70 pass first
2 Anu 71 81 91
3 Lucky 67 77 78
4 Rahul 69 79 87

PROGRAM

20.Write a PL/SQL program to accept to student number and display their


name and marks.

33
 Prompt for student details.

SQL> select * from stud;

RNO NAME C1 C2 C3
1 Nani 60 70 80
2 Anu 71 81 91

2 rows selected.

Pl/ SQL PROGRAM

SQL>declare
sno stud.rno%type:=&sno;
x stud%rowtype;
begin
select * into x from stud where rno=sno;
dbms_output.put_line(‘Sname:’||x.sname);
dbms_output.put_line(‘ M1:’||x.m1);
dbms_output.put_line(‘ M2:’||x.m2);
dbms_output.put_line(‘ M3:’||x.m3);
end;
/
SQL>/
Enter value for sno:1
old 2: sno stud.rno%type:=&sno;
new 2:sno stud.rno%type:=1;

OUTPUT:

sname:Nani
M1: 75
M2: 65
M3: 85

PL/SQL procedure succeccfully completed.

PROGRAM:

34
21.Write a procedure to read rows from 2 tables (say emp, dept) and
store in rows of 3rd table.

>Prompt table emp details.

SQL>select * from emp;

EMPNO ENAME SAL


7369 BOBBY 800
7499 RAJ 1600
7521 SING 1250
7566 LUCKY 2975
7654 SANDEEP 1250

>Prompt table details.

SQL>select * from dept;

DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
40 OPERATIONS

PROCEDURE CODE:
SQL>create procedure edet(e_eno emp.empno%type,
e_ename emp.ename%type,
e_sal emp.sal%type,
d_dno dept.deptno%type,
d_dname dept.dname%type)as
begin
insert into edet(eno,’ename’, sal, dno, ‘dname’)
values(&e_eno,’&e_ename’,e_sal,d_dno,d_dname);
end;
/
PL/SQL procedure successfully completed.

OUTPUT:
 Prompt table edet details.

SQL> select * from edet;

35
EMPNO ENAME SAL DEPTNO DNAME
7369 BOBBY 800 20 RESEARCH
7499 RAJ 1600 30 SALES
7521 SING 1250 30 SALES
7566 LUCKY 2975 20 RESEARCH
7654 SANDEEP 1250 30 SALES

22. TRIGGERS:

The new SQL-99 standard includes support for triggers, which are actions
executed by the DBMS, whenever changes to the database meet conditions
specified in the triggers.

A trigger is a procedure that is automatically invoked by DBMS in response to


specified changes to the database and it’s typically specified by the DBA. The
database that has a set of associated triggers is called an active database.

A trigger description contains 3 parts

>EVENT: A change to database that activates the trigger.


>CONDITION: A query or test that is run when the trigger is activated.
>ACTION: The procedure that is executed when the trigger is activated
and
its condition is true.

A trigger can be thought of as DAEMON that monitors a database and executed


when the database is modified in a way that matches the event specification. A
condition in a trigger can be true (or) false statement (or) query.

A trigger action can examine the answer to the query in the condition part of the
trigger, refer to old and new values of tuples modified by the statement activating
the trigger, executes new queries & makes changes to the database.

PROGRAM:

23.PL/SQL Program to display the employee details of given dept using


cursors.

36
PL/SQL PROGARM:

1 declare
2 dno number:=&dno;
3 cursor c1 is select * from dept where deptno=dno;
4 x emp% rowtype;
5 ch boclean:=false;
6 begin
7 open c1;
8 loop
9 fetch c1 into x;
10 exit when c1%not found;
11 dbms_output.put_line(x.ename||’—‘||x.sal||’—‘||x.hiredate||’—‘||x.job);
12 ch:=true;
13 end loop;
14 close c1;
15 if ch=false then
16 dbms_output.put_line(‘ no employees found in dept’||dno);
17 end if;
18 end;
19 /

OUTPUT:

enter value for dno:20


old 2: dno number:=&dno;
new 2: dno number:=20;

ANU—800—17—DEC—80—CLERK
NANI—2975—02—APR—81—MANAGER
SATYA—3000—19—APR—87—ANALYST

PL/SQL procedure successfully completed.

PROGRAM:

24.PL/SQL Program using stored procedure and stored functions.

PL/SQL PROGARM

37
1 create procedure print2(n char) is
2 begin
3 dbms_output.put_line (n);
4 end;
5 /
6 begin
7 print2 (‘HELLO NANI’);
8 end;
9 /

OUTPUT:

Procedure created.
HELLO NANI
PL/SQL Procedure successfully completed.

PROGARM:

25.PL/SQL Program for Error Handling.

PL/SQL PROGARM

1 declare
2 eno number:=&eno;
3 x emp%rowtype;
4 invalic job exception;
5 begin
6 select * into x from emp where empno=eno;
7 if x.job=’manager’ then raise invalidjob;
8 end if;
9 dbms_output.put_line(x.ename);
10 dbms_output.put_line(x.job);
11 dbms_output.put_line(x.sal);
12 dbms_output.put_line(x.hiredate);
13 exception when no_data found then
14 raise_application_error(-20399,’data not found for given number’);
15 when invalidjob then
16 raise_application_error(-20399,’insufficient privileges..cannot retry’);
17 end;
18 /

OUTPUT:
enter value for eno:7099
old 2: eno number:=&eno;

38
new 2: eno number:=7099;
declare
*

ERROR at line1:
ORA-20399: data not found for given number
ORA-06512: at line 14

PL/SQL successfully not completed.

39