You are on page 1of 107

Class-1

Types of data
We have two types of data.
1)Unstructured Data
2)Structured Data

1)Unstructured Data
 Data which is not in readable format is called unstructured data.
 In general, meaning less data is called unstructured data.

ex:
302 willorro Lakemba SYD NSW

2)Structured Data
 Data which is in readable format is called structured data.
 In general, meaning full data is called structured data.

ex:
unit street Locality City State
302 willorro Lakemba SYD NSW
Client-Server Architecture
In this architecture we need to see how our frontend data will store in backend.
Diagram: oracle1.1
FrontEnd
The one which is visible to the enduser to perform some operations is called
frontend.
ex:
Java, Python, .Net, Perl, D2K and etc.
Communication Channel
It acts like a bridge between frontend and backend.
ex:
JDBC - Java Database Connectivity
ODBC - Open Database Connectivity
PDBC - Python Database Connectivity

BackEnd
The one which is not visible to the enduser but it performs some operations
based on the instructions given by frontend is called backend.

ex:
Oracle, MySQL, NoSQL, H2 , Sybase, Teradata , PostgreSQL and etc.
Management System
 It is a software which is used to manage the database.
 Management system will perform following acitivities very easily.
1)Adding the new data
2)Updating the existing data
3)Deleting the unnecessary data
4)Selecting a required data

DBMS
A database along with software which is used to manage the database is called
database management system.
RDBMS
Any database which is developed based on relational theories is called relational
database management system.
ex:
Oracle
MySQL
NoSQL
SQL Server
and etc.

Q) What is Oracle ?
 Oracle is one of the database which is used to store structured data.
 Oracle is a product of Oracle Corporation.
 Oracle is classified into two types.

Oracle
|----------------------------------------------------------|
SQL PL/SQL
(Structured Query Language) (Procedural/ Structured Query Language)
SQL
 SQL stands for Structured Query Language which is pronounce as
SEQUEL.
 It is used to communicate with Oracle database only.
 It is a case insensitive language.
 It is a command based language.
 Every command must starts with verb.
ex:
insert, update, delete, merge and etc.
 Every command must ends with semicolon only.
 It is a language developed by Mr.Codd(By IBM) in 1972.

Sub languages of SQL


We have five sub languages of SQL.
1)DDL - (Data Definition Language)
2)DML - (Data Manipulation Language)
3)DRL - (Data retrieve Language)
4)DCL - (Data Control Language)
5)TCL - (Transaction Control Language)

1)DDL - (Data Definition Language)


This language is used to maintain the data base objects.
It is a collection of five commands.
ex:
create, alter, drop, truncate and rename.

2)DML - (Data Manipulation Language)


This language is used to manipulate the data present in database.
It is a collection of four commends.
ex:
insert, update, delete and merge.

3)DRL - (Data retrieve Language)


It is used to retrieve the data present in database.
It is a collection of one command.
ex:
select

4)DCL - (Data Control Language)


This language is used to control the access of data to the user.
It is a collection of two commands.
ex:
grant and revoke
5)TCL - (Transaction Control Language)
This language is used to maintain the transaction of database.
It is a collection of three commands.
ex:
commit, rollback and savepoint.

What is Table
 Table is an object which is used to store the data.
 In general, table is a collection of rows and columns.
 SQL is a case insensitive language but data which is present in a table is a
case sensitive.

ex:
S No. S Name S ADD
101 Alan USA
102 Jose UK
103 Mark UAE

Oracle Database Installation


Database : Oracle

version : 10g / 11g

Vendor : Oracle Corporation

website : www.oracle.com

Open source : Open source


download link :

https://drive.google.com/file/d/0B9rC21sL6v0td1NDZXpkUy1oMm8/view?usp
=sharing&resourcekey=0-aKooR3NmAh_eLo_qGw_inA
username : system (default)
password: admin
confirm password: admin
Establish the connection with database software
To perform or execute any query in a database we need to use establish the
connection with database software.
Once the work with database is completed we need to disconnect with database
software.
ex:1
SQL> connect
username: system
password: admin
SQL> disconnect

ex:2
SQL> conn
username: system
password: admin
SQL> disc
ex:3
SQL> conn system/admin
SQL> disc
create command
It is used to create a table in database.

syntax:
create table <table_name> (col1 datatype(size), col2 datatype(size),...,
colN datatype(size));

ex:
create table student(sno number(3),
sname varchar2(10),
sadd varchar2(12));

create table dept(deptno number(3),


dname varchar2(10),
dloc varchar2(8));

create table emp(eno number(3),


ename varchar2(10),
esal number(10,2),
deptno number(3),
job varchar2(10),
comm number(6));

describe command
It is used to see the structure of a table.

syntax:
desc <table_name>;
ex:
desc emp;
desc student;
desc dept;

Class-2
insert command
It is used to insert a row in a database table.
syntax:
insert into <table_name> values(val1,val2,.....,valN);
ex:
insert into student values(101,raja,hyd); // invalid
insert into student values(101,'raja','hyd'); // valid
insert into student values('ravi',102,'pune'); // invalid
insert into student values(102,'ravi'); // invalid
null
null is keyword which represent undefined or unavailable.

ex:
insert into student values(102,'ravi',null); // valid

approach2
insert into student(sno,sname,sadd) values(103,'ramana','delhi');
insert into student(sno,sname) values(104,'raja');

approach3
We can insert dynamic inputs by using '&' symbol.
ex:
insert into student values(&sno,'&sname','&sadd');
commit command
It is used to make the changes permanent to database.
syntax:
commit;
select command
It is used to select /retrieve the records from database table.
syntax:
select * from <table_name>;
Here '*' means all rows and columns.
ex:
select * from student;
select * from emp;
select * from dept;
emp table
create table emp(eno number(3),ename varchar2(10),esal number(10,2),deptno
number(3),
job varchar2(10), comm number(5));
insert into emp values(201,'Alan',8000,10,'Clerk',null);
insert into emp values(202,'Jose',12000,10,'Clerk',100);
insert into emp values(203,'Nancy',27000,20,'HR',200);
insert into emp values(204,'Lucy',36000,20,'HR',500);
insert into emp values(205,'Mark',45000,30,'Manager',500);
insert into emp values(206,'James',28000,30,'Manager',900);

commit;
dept table
create table dept(deptno number(3),dname varchar2(10),dloc varchar2(12));
insert into dept values(10,'ECE','HYD');
insert into dept values(20,'EEE','DELHI');
insert into dept values(30,'CSE','VIZAG');
insert into dept values(40,'MEC','PUNE');
commit;
Projection:
Selecting specific columns from the database table is called projection.
ex:
select sno from student;
select sno,sname from student;
select sno,sname,sadd from student;
column alias
A userdefine heading given to a column is called column alias.
Column alias we can apply to any column.
Scope of column alias is with respect to same column. It means when query is
executed we will loss the column alias.
ex:
select sno,sname,sadd from student;
select sno as rollno,
sname as firstname,
sadd as city from student;
Interview queries
Q) Write a query to display all the tables present in database?

select * from tab;

Q) Write a query to see the logical database name(schema name)?

select * from global_name;

Q) Write a query to see the list of users present in database?

select * from all_users;

Q) write a query to display all the employees information from emp table?

select * from emp;

Q) write a query to display employee no,employee name and salary from


emp table?
select eno,ename,esal from emp;

Q) Write a query to display employee number, employee name , employee


salary and annual salary from emp table?

select eno,ename,esal,esal*12 from emp;

Q) Write a query to display employee number, employee name , employee


salary and annual salary as ANNUAL_SAL from emp table?

select eno,ename,esal,esal*12 as ANNUAL_SAL from emp;

Where clause
To select specific records from database table then we need to use where clause.

syntax:
select * from <table_name> where condition;

ex:
select * from student where sno=101;

select * from student where sname='rakesh'; // no rows selected

select * from student where sname='Rakesh';

select * from student where sadd='hyd';


Interview queries
Q) Write a query to display employees information those who are working
in 10 dept?
select * from emp where deptno=10;

Q) Write a query to display employees information those who are working


as a Manager?

select * from emp where job='Manager';

Q) Write a query to display employee information whose salary is greater


then 25000?
select * from emp where esal>25000;

Q) Write a query to display employee information whose commission is


null?
select * from emp where comm=null; // no rows selected.
select * from emp where comm is null;
update command
It is used to update the records in database table.

syntax:
update <table_name> set <col_name>=value where condition;

ex:
update student set sname='gogo' where sno=101;

update student set sadd='hyd' where sno=102;


update student set sname='jojo',sadd='delhi' where sno=103;

Note:
If we won't use where clause then all rows will be updated.
ex:
update student set sname='raja';

update student set sno=101;

update student set sadd='hyd';

Delete command
===============
It is used to delete the records from database table.

syntax:
delete from <table_name> where condition;
ex:
delete from student where sno=105;
delete from student where sname='raja';
delete from student where sadd='hyd';

Note:
If we won't use where clause then all rows will be deleted.
ex:
delete from emp;
delete from dept;
delete from student;
Class-3
Logical Operators
If we want to declare more then one condition in our query then we need to use
logical operators.
We have three logical operators.
1)AND
2)OR
3)NOT

1)AND
It will return the records if all conditions are true.
All conditions must belongs to same row only.
ex:
select * from emp where eno=201 and ename='Alan';
select * from emp where eno=202 and ename='Alan'; // NO ROWS
SELECTED
select * from emp where eno=202 and ename='Linda'; // no rows selected
select * from emp where esal>8000 and esal<30000;
2)OR
It will return the records atleast one condition is true.
Here conditions can be from any row.
ex:
select * from emp where eno=201 OR ename='Alan';
select * from emp where eno=202 OR ename='Alan';

select * from emp where eno=202 OR ename='Linda';


select * from emp where eno=201 OR eno=202 OR eno=203;

3)NOT
It will display the records except the condition.
A '<>' symbol denoted as not operator.
ex:
select * from emp where NOT eno=201;

select * from emp where eno<>201;

Q) write a query to display all the employees information those who are not
working in 10 department?

select * from emp where NOT deptno=10;


or
select * from emp where deptno<>10;

Duplicate table or copy of a table


We can create a duplicate table or copy of a table by using create and select
command.
ex:
create table stud as select * from emp;
create table stud as select eno,ename,esal from emp;
create table stud as select * from emp where eno=201;
create table stud as select * from emp where esal>= 5000 and
esal<=20000;
create table stud as select * from emp where comm is null;
create table stud as select * from emp where deptno<>10;

cl scr
IT is used to clear the output screen of sql command prompt.
syntax:
cl scr

Between operator
It will return the records those who are in the range of values.
Between operator will take the support of AND operator.
In between operator we need to write first lower limit then higher limit.
ex:
select * from emp where eno between 201 AND 204;
select * from emp where deptno between 10 and 30;
select * from emp where esal between 5000 and 20000;

In operator
In operator is a replacement of OR operator.
It will return the records those who are matching in the list of values.
ex:
select * from emp where eno IN(201,202,203);
select * from emp where ename IN('Alan','Linda','Jose');
select * from emp where deptno IN(10,20,30);

Pattern matching operators


Pattern matching operators are used to select the letters from database table.
Pattern matching operator take the support of "like" operator.
We have two types of pattern matching operators.
1)Percentage (%)
2)Underscore(_)

1)Percentage (%)
Q) Write a query to display employee information whose employee name
starts with 'A' letter?

select * from emp where ename like 'A%';

Q) Write a query to display employee information whose employee name


ends with 'y' letter?

select * from emp where ename like '%y';

Q) Write a query to display employee information whose employee name


middle letter is 'n'?
select * from emp where ename like '%n%';

2) Underscore(_)
Q) Write a query to display employee information whose employee name
having second letter is 'l'?

select * from emp where ename like '_l%';

Q) Write a query to display employee information whose employee name


having third letter is 'n'?
select * from emp where ename like '__n%';

Q) Write a query to display employee information whose employee name


having second last letter as 'c'?

select * from emp where ename like '%c_';

DDL commands
create - (tables)
alter - (columns)
drop - (tables)
truncate - (rows/records)
rename - (tables)

alter command
Using alter command we can perform following activities.
1)Adding a new column
2)Dropping a existing column
3)Modifying a column
4)Renaming a column

1)Adding a new column


Using alter command we can add a new column.
syntax:
alter table <table_name> ADD (col1 datatype(size),col2 datatype(size),...,colN
datatype(size));
ex:
alter table student add (state varchar2(10));
alter table student add (pincode number(8));
alter table student add (state varchar2(10),pincode number(8));

update student set state='telangana' where sno=101;

2)Dropping a existing column


Using alter command we can drop the existing column.
syntax:
alter table <table_name> DROP (col1,col2,....,colN);
ex:
alter table student DROP (state);
alter table student DROP (pincode);
alter table student DROP (state,pincode);
3)Modifying a column
Using alter command we can modify a column.
We can increase or decrease the size of a column only when existing values are
fit into new size.
We can change the datatype of a column only when column is empty.
ex:
desc student;

alter table student modify (sadd varchar2(15));

desc student;

alter table student modify (sadd number(4));


4)Renaming a column
Using alter command we can rename the column name.

syntax:
alter table <table_name> rename column <old_name> to <new_name>;
ex:
alter table student rename column sadd to city;
alter table emp rename column esal to dailywages;
alter table emp rename column job to designation;
drop command
It is used to drop the table from database.
syntax:
drop table <table_name>
ex:
drop table emp;
drop table student;
drop table dept;

truncate command
It is used to delete the records permenently from database table.

syntax:
truncate table <table_name>

ex:
truncate table emp;
truncate table dept;
truncate table student;
Q) What is the difference between delete and truncate command?
delete truncate
It will delete the records temperorly. It will delete the records
permanently.
We can rollback the data. We can't rollback the data.
Where clause can be used. Where clause can't be used.
It is a DML command. It is a DDL command.

rename command
It is used to rename the table name.
syntax:
rename <old_name> to <new_name>;
ex:
rename emp to employee;
rename student to students;
rename dept to department;

Class-4
Functions
Functions are used to manipulate the data items and gives the result.

We have two types of functions in SQL.

1)Group Functions / Multiple Rows Functions

2)Scalar Functions / Single Row Functions


1)Group Functions
Group functions are applicable for multiple rows.

We have following list of group functions.


ex:
sum(), avg(), max(), min(), count(*) and count(exp).

Q) Write a query to display sum of all the employee salary?

select sum(esal) from emp;

Q)Write a query to display average salary of each employee from emp


table?

select avg(esal) from emp;

Q) Write a query to display highest salary from emp table?

select max(esal) from emp;

Q) Write a query to display least salary from emp table?

select min(esal) from emp;

Q) Difference between count(*) and count(exp)?


count(*)
It will return number of records present in a table.
It will include null records.
ex:
select count(*) from emp;

count(exp)
It will return number of values present in a database table column.
It will not include null values.
ex:
select count(eno) from emp; // 6
select count(comm) from emp; // 5

userlist table

create table userlist(uname varchar2(10), pwd varchar2(10));


insert into userlist values('raja','rani');
insert into userlist values('king','kingdom');
commit;

Q) Write a query to validate username and password is correct or not?

select count(*) from userlist where uname='raja' and pwd='rani'; //1

or
select count(*) from userlist where uname='raja' and pwd='rani1'; // 0

Dual table
Dual table is a dummy table which is used to perform arithmetic operations and
to see the
current system date.

Dual table contains one row and one column.

ex:
select 10+20 from dual;
select 10*20 from dual;
select 10-20 from dual;

select sysdate from dual;


select current_date from dual;

2)Scalar Functions
Scalar functions are applicable for single row.
Scaler functions are divided into four types.
i)Character Functions
ii)Number Functions
iii)Date Functions
iv)Conversion Functions
i)Character Functions
UPPER()
It will convert lower case to upper case.
ex:
select upper('oracle training') from dual;
select upper('oracle training') as UPPER from dual;

LOWER()
It will convert upper case to lower case.
ex:
select lower('ORACLE TRAINING') from dual;
select lower('ORACLE TRAINING') as LOWER from dual;

INITCAP()

It will display the text in init cap.


ex:
select initcap('ORACLE TRAINING') from dual;
select initcap('ORACLE TRAINING') as INITCAP from dual;

LPAD()
It will pad the characters towards left side.
ex:
select LPAD('oracle',10,'z') from dual;//zzzzoracle
select LPAD('oracle',10,'z') as LPAD from dual;

RPAD()
It will pad the characters towards right side.
ex:
select RPAD('oracle',10,'z') from dual;//oraclezzzz
select RPAD('oracle',10,'z') as RPAD from dual;

LTRIM()
It will trim the character from left side.
ex:
select LTRIM('zzoraclezz','z') from dual;//oraclezz
select LTRIM('zzoraclezz','z') as LTRIM from dual;

RTRIM()
It will trim the character from right side.
ex:
select RTRIM('zzoraclezz','z') from dual;//zzoracle
select RTRIM('zzoraclezz','z') as RTRIM from dual;

TRIM()
It will trim the characters from both the sides.
ex:
select TRIM('z' from 'zzoraclezz') from dual;//oracle
select TRIM('z' from 'zzoraclezz') as TRIM from dual;

SUBSTR()
It will return sub string.
ex:
select substr('oracle',2,3) from dual;//rac
select substr('training',1,5) from dual;//train

CONCAT()
It will concatinate two strings.
ex:
select concat('mega','star') from dual;//megastar

select concat(concat('mega','star'),'chiru') from dual;


ii) Number Functions
ABS()
It will return absoluate value.
ex:
select abs(-5) from dual;//5
select abs(-10.45) from dual;//10.45

SQRT()
It will return exact square root value.
ex:
select sqrt(25) from dual; // 5
select sqrt(81) from dual; //9
select sqrt(26) from dual;//5.09

POWER(A,B)
It will return power value.
ex:
select power(2,3) from dual;//8
select power(5,3) from dual;//125

CEIL()
It will return ceil value.
ex:
select ceil(10.6) from dual;//11
select ceil(6.1) from dual;//7

FLOOR()
It will return floor value.
ex:
select floor(10.7) from dual;//10
select floor(4.2) from dual;//4

TRUNC()
It will remove decimal values.
ex:
select trunc(10.45) from dual;//10
select trunc(98.12) from dual;//98

ROUND()
It will return nearest value.
ex:
select round(10.5) from dual;//11
select round(10.4) from dual;//10
GREATEST()
It will return greatest value.
ex:
select greatest(10,2,67) from dual;//67
LEAST()
It will return lowest value.
ex:
select least(10,2,67) from dual;//2

iii)Date Functions
drop table emp1;

create table emp1(eid number(3),ename varchar2(10),edoj date);

insert into emp1 values(101,'Alan','01-JAN-21');

insert into emp1 values(102,'Jose',sysdate);

insert into emp1 values(103,'Linda',current_date);

commit;

ADD_MONTHS()
It will add months in a given date.
ex:
select ADD_MONTHS(sysdate,4) from dual;
select ADD_MONTHS('01-JAN-22',3) from dual;
MONTHS_BETWEEN()
It will return number of months between two dates.
ex:
select MONTHS_BETWEEN('01-JAN-22','01-MAY-22') from
dual;

NEXT_DAY()
It will return next date of a given day in a week.
ex:
select NEXT_DAY(sysdate,'SUNDAY') from dual;
select NEXT_DAY(sysdate,'FRIDAY') from dual;

LAST_DAY()

It will return last date of a month.


ex:
select LAST_DAY(sysdate) from dual;
select LAST_DAY('04-FEB-22') from dual;
Class-5
iv)Conversion function
Conversion function is used convert from one datatype to another datatype.

ex:
TO_CHAR()

We have two pseudo for TO_CHAR().


1) number to_char()

It will accept '9' in digits and '$' symbol


ex:
select eno,ename,esal from emp;
select eno,ename,TO_CHAR(esal,'9,999') from emp;
select eno,ename,TO_CHAR(esal,'99,999') from emp;
select eno,ename,TO_CHAR(esal,'$99,999') from emp;

2)date to_char()
ex:
select sysdate from dual;
select TO_CHAR(sysdate,'dd-MM-yyyy') from dual;
select TO_CHAR(sysdate,'dd-MM-yyyy') as DOJ from dual;
select TO_CHAR(sysdate,'yyyy-MM-dd') as DOJ from dual;
select TO_CHAR(sysdate,'DAY') from dual;//Tuesday
select TO_CHAR(sysdate,'DY') from dual;//tue
select TO_CHAR(sysdate,'Month') from dual;//september
select TO_CHAR(sysdate,'Mon') from dual;//sep
select TO_CHAR(sysdate,'year') from dual;//twenty twenty two
select TO_CHAR(sysdate,'yyyy') from dual;//2022
select TO_CHAR(sysdate,'hh:mi:ss') from dual;
select TO_CHAR(sysdate,'dd-MM-yyyy hh:mi:ss') from dual;

Group by clause
It is used divide the rows into groups so that we can apply group functions.
A column which we used in select clause then same column we need to use in
group by clause.
Q) Write a query to display sum of salary of each department?

select sum(esal),deptno from emp group by deptno;

Q) Write a query to display highest salary of each department?

select max(esal),deptno from emp group by deptno;

Q) Write a query to display average salary of each job?

select avg(esal),job from emp group by job;

Having clause
It is used to filter the rows from group by clause.
Having clause we need to place after group by clause.

Q) Write a query to display sum of salary of each department where sum of


salary is greater then 30000?

select sum(esal),deptno from emp group by deptno having


sum(esal)>30000;

Order by clause
It is used to arrange the rows in a database table.
Bydefault it will arrange the records in ascending order.

ex:
select * from emp order by eno;
select * from emp order by ename;
select * from emp order by deptno desc;

Integrity constraints
Constraints are the rules which are applied on a table.
Using constraints we can achieve accuracy and quality of data.

We have following list of constraints .

1)NOT NULL
2)UNIQUE
3)PRIMARY KEY
4)FOREIGN KEY
5)CHECK

Constraints are created in two levels.


\i)column level
ii)table level

1)NOT NULL
NOT NULL constraint does not accept null values.
It will accept duplicate values.
NOT NULL constraint can be created only at column level.

ex:

column level
------------
drop table student;

create table student(sno number(3) NOT NULL ,


sname varchar2(10),
sadd varchar2(12));

insert into student values(101,'raja','hyd');


insert into student values(101,'ravi','delhi');

insert into student values(null,'raja','hyd'); //invalid


commit;

Note:
------
We can declare NOT NULL for multiple columns.

2)UNIQUE
UNIQUE constraint does not accept duplicates.
But it will accept null values.
UNIQUE constraint can be created at column level and table level.
column level
drop table student;

create table student(sno number(3) UNIQUE,


sname varchar2(10),
sadd varchar2(12));

insert into student values(101,'raja','hyd');


insert into student values(101,'ravi','delhi'); //invalid
insert into student values(null,'raja','hyd');
commit;

table level
drop table student;

create table student(sno number(3),


sname varchar2(10),
sadd varchar2(12), UNIQUE(sno));

insert into student values(101,'raja','hyd');


insert into student values(101,'ravi','delhi'); //invalid
insert into student values(null,'raja','hyd');
commit;

Note:
------
We can declare UNIQUE for multiple columns.

3)PRIMARY KEY
 Primary key is a combination of not null and unique constraint.
 Primary key does not accept duplicates and null values.
 Primary key can be created at column level and table level.

ex:

column level
drop table student;
create table student(sno number(3) PRIMARY KEY,
sname varchar2(10),
sadd varchar2(12));

insert into student values(101,'raja','hyd');


insert into student values(101,'ravi','delhi'); //invalid
insert into student values(null,'ramana','vizag'); //invalid
commit;

Table level
drop table student;

create table student(sno number(3) ,


sname varchar2(10),
sadd varchar2(12),PRIMARY KEY(sno));
insert into student values(101,'raja','hyd');
insert into student values(101,'ravi','delhi'); //invalid
insert into student values(null,'ramana','vizag'); //invalid
commit;

4)Foreign key
 Foreign key is used to establish the relationship between two tables.
 This relationship is called parent and child relationship or master and
detailed relationship.
 To create a relationship a parent table must have primary key or unique
key and
 child table must have foreign key.
 A foreign key name , may or may not match with primary key but
datatype must match.
 Foreign key will accept only those values which are present in primary
key.

ex:
college table
create table college(sno number(3) primary key,
sname varchar2(10),
sadd varchar2(12));

insert into college values(101,'raja','hyd');


insert into college values(102,'ravi','delhi');
insert into college values(103,'ramana','vizag');
commit;

library table
create table library(roll_no number(3) REFERENCES college(sno),
book_name varchar2(15));
insert into library values(101,'java');
insert into library values(102,'oracle');
insert into library values(103,'react');
insert into library values(103,'springboot');
insert into library values(null,'microservices');
commit;

5)Check constraint
It is used to describe domain of a column.
Here domain means what type of values a column must accept.
check constraint can be created at column level and table level.

column level
ex:
drop table student;

create table student(sno number(3) ,


sname varchar2(10) check(sname=upper(sname)),
sadd varchar2(12));

insert into student values(101,'raja','hyd');


insert into student values(102,'RAVI','delhi'); //valid
insert into student values(103,'RaMaNa','vizag');
commit;
ex:
drop table student;

create table student(sno number(3) ,


sname varchar2(10) check(sname=lower(sname)),
sadd varchar2(12));

insert into student values(101,'raja','hyd'); //valid


insert into student values(102,'RAVI','delhi');
insert into student values(103,'RaMaNa','vizag');
commit;

ex:
drop table student;

create table student(sno number(3) ,


sname varchar2(10),
smarks number(3) check(smarks between 0 and 100));

insert into student values(101,'raja',78);


insert into student values(102,'RAVI',100);
insert into student values(103,'RaMaNa',109);
commit;

ex:
drop table student;
create table student(sno number(3) ,
sname varchar2(10),
smarks number(3) check(smarks<=100));

insert into student values(101,'raja',78);


insert into student values(102,'RAVI',100);
insert into student values(103,'RaMaNa',109);
commit;

table level
ex:
drop table student;

create table student(sno number(3) ,


sname varchar2(10),
smarks number(3), check(sname=upper(sname)));

insert into student values(101,'raja',78); //invalid


insert into student values(102,'RAVI',100);
insert into student values(103,'RaMaNa',109);//invalid
commit;

Class-6
TCL commands
1)commit
It is used to make the changes permanent to database.
ex:
drop table student;
create table student(sno number(3),sname varchar2(10),sadd
varchar2(12));

insert into student values(101,'raja','hyd');


insert into student values(102,'ravi','delhi');

commit;

select * from student; //2 records

rollback
It is used to undo the changes which are not permanent.
ex:
drop table student;
create table student(sno number(3),sname varchar2(10),sadd
varchar2(12));

insert into student values(101,'raja','hyd');


insert into student values(102,'ravi','delhi');

commit;

insert into student values(103,'raj','vizag');


insert into student values(104,'ramana','pune');
select * from student; //4 records

rollback;

select * from student; // 2 records

savepoint

Instead of complete rollback we can rollback upto save point.


ex:
drop table student;
create table student(sno number(3),sname varchar2(10),sadd
varchar2(12));

insert into student values(101,'raja','hyd');


insert into student values(102,'ravi','delhi');

savepoint sp1;

insert into student values(103,'raj','vizag');


insert into student values(104,'ramana','pune');

savepoint sp2;

insert into student values(105,'alan','texas');


insert into student values(106,'jose','florida');

select * from student; // 6 records


rollback to sp2;

select * from student; // 4 records

PSEUDO columns
A pseudo column means a column which is not real.
We have two pseudo columns.

1)RONUM
ROWNUM always starts with 1 and increment by 1.
ROWNUM values are temperory and It will be created when we execute the
command.

ex:
select eno,ename,esal from emp;
select rownum,eno,ename,esal from emp;

2)ROWID
ROWID is a hexadecimal value and it is permanent.
ROWID is a address where our records will store in a database table.
ex:
select rowid,rownum,eno,ename,esal from emp;

Q) Write a query to display a first three records from emp table?


select * from emp where rownum<=3;

Q) Write a query to display fourth record from emp table?

select * from emp where rownum<=4


minus
select * from emp where rownum<=3;

DCL commands
grant
revoke

schema
Schema is a memory location which is used to run sql commands.

Privileges
Permissions given to a user is called privileges.
Rights given to a user is called privileges.
We have two types two privileges.

1)System privilege
Permission given by DBA to user is called system privilege.

2)Object privilege
Permission given by one user to another user is called object
privilge.
grant
Granting the permission to the user.
ex:
grant <privilge1>,<privilege2> to <user_name>;

revoke
revoking the permission from the user.
ex:
revoke <privilge1>,<privilege2> from <user_name>;

DBA> create user monika identified by monika;


DBA> create user srinu identified by srinu;

monika> conn monika/monika //logon denied

srinu> conn srinu/srinu //logon denied

DBA> grant connect,resource to monika,srinu;

srinu>
create table employee(eid number(3),ename varchar2(10),esal number(10));
insert into employee values(201,'Alan',1000);
insert into employee values(202,'Jose',2000);
insert into employee values(203,'Nancy',1000);
commit;

monika> select * from employee; // table or view does not exist

srinu> grant select on employee to monika;

monika> select * from srinu.employee;

monika> delete from srinu.employee; //insufficient privilege

srinu> grant delete on employee to monika;

monika> delete from srinu.employee;


commit;

srinu> disc;

monika> disc;

srinu> revoke select,delete on employee from monika;

DBA> revoke connect,resource from monika,srinu;

Q) Write a query to see all the users present in database?


ex:
select * from all_users;
Q) Write a query to drop the user from database?

drop user monika;


drop user srinu cascade;

Synonyms
Synonym is a alternate name which is given to an object(table).

We can use synonym name instead of table name for every command.

We can declare synonym name as follow.

syntax:
create synonym <synonym_name> for <table_name>;
ex:
create synonym s1 for student;

select * from s1;

delete from s1;

Q) Write a query to see all the list of synonyms present in database?


select synonym_name from user_synonyms;
Q) Write a query to drop the synonym from database?
drop synonym s1;
Class-7
Joins
select * from emp,dept; // 6 * 4 = 24 records
select eno,ename,esal,dname,dloc from emp ,dept;
select eno,ename,esal,deptno,dname,dloc from emp ,dept; //column
ambiguously defined
If two tables contain common column then we need to use that column by using
table name.
ex:
select emp.eno,emp.ename,emp.esal,dept.deptno,dept.dname,dept.dloc
from emp ,dept; // 6 * 4 = 24 records

table alias
A userdefine heading given to a table is called table alias.
Using table alias length of the query will reduce meanwhile performance is
maintained.
Table alias is temperory.
Once the query is executed we will loss the table alias.
Table alias we can take in select clause as well as in where clause.

ex:
select e.eno,e.ename,e.esal,d.deptno,d.dname,d.dloc from emp e,dept d;
//6*4=24 records

Definition of joins
Joins is used to retrieve the data from one or more then one table.
We have following types of joins.

1)Equi Join
2)Non-Equi Join
3)Cartisian product
4)Self join
5)Inner Join
6)Outer Join

1)Equi Join
When two tables are joined based on common column is called equi-join.

ex:
select e.eno,e.ename,e.esal,d.dname,d.dloc from emp e,dept d
where(e.deptno=d.deptno);// 6 records

2)Non-Equi join
When tables are joined without joined condition is called non-equi join.
ex:

select e.eno,e.ename,e.esal,d.dname,d.dloc from emp e,dept d


where esal between 10000 and 30000;//3*4 = 12 records

3)Cartisian product
Cartisian product will give all possible combinations.It does not have any where
condition.
ex:
select e.eno,e.ename,e.esal,d.dname,d.dloc from emp e,dept d; // 6*4=24
recrods

4)Self join
A table which is joined to itself is called self join.
In self join we need to create two table alias for same table.

ex:
select e1.eno,e1.ename,e1.esal,e2.job,e2.comm from emp e1,emp e2
where(e1.deptno=e2.deptno);// 6+6=12 records

5)Inner Join
It is similar to equi join.
It will return only matching records.
Inner join given by ANSI people.
ANSI stands for American National Standards Institute.
ex:
ANSI
select e.eno,e.ename,e.esal,d.dname,d.dloc from emp e INNER JOIN dept
d
ON(e.deptno=d.deptno); // 6 records

select e.eno,e.ename,e.esal,d.dname,d.dloc from emp e JOIN dept d


ON(e.deptno=d.deptno); //6 records
6)Outer join
It is a extension of outer join.
It will return matching as well as not matching records.

A '+' is denoted as outer join operator.

We have following types of outer joins.

1)Left outer join


SQL

select e.eno,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc from


emp e,dept d
where (e.deptno=d.deptno(+));
ANSI

select e.eno,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc from


emp e
Left outer join dept d
on(e.deptno=d.deptno);

2)Right outer join


SQL
select e.eno,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc from
emp e,dept d
where (e.deptno(+)=d.deptno);
ANSI
select e.eno,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc from
emp e
right outer join dept d
on(e.deptno=d.deptno);

3)Full outer join


ANSI
select e.eno,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc from
emp e
full outer join dept d
on(e.deptno=d.deptno);

Interview question

Diagram : oracle7.1

Q) Write a query to display student number, student name ,book name and
semister from
given three tables?
select c.sno,c.sname,l.book_name,a.semister from college c inner join
library l
ON(c.sno=l.rollno) inner join adminstration a
ON(c.sno=a.sid);

Java Interview question


class Test
{
public static void main(String[] args)
{
//rows
for(int i=5;i>=1;i--)
{
if(i%2!=0)
{
for(int j=1;j<=i;j++)
{
System.out.print(i+" ");
}
}
//new line
System.out.println("");
}
}
}
Class-8
Sequences
Sequence is an object which is used to generate numbers.
syntax:
create sequence <sequence_name> start with value increment by value;

ex:
create sequence sq1 start with 101 increment by 1;

create sequence sq2 start with 10 increment by 10;

create sequence sq3 start with 1 increment by 1;

create sequence sq3 start with 1 increment by 1 MINVALUE 10;

create sequence sq3 start with 1 increment by 1 MINVALUE 10


MAXVALUE 100;

Sequence contains two pseudo's.

1)NEXTVAL
2)CURRVAL

1)NEXTVAL
It is used to generate the next number in a sequence.
ex:

create sequence sq1 start with 101 increment by 1;

drop table student;


create table student(sno number(3),sname varchar2(10),sadd
varchar2(12));

insert into student values(sq1.NEXTVAL,'raja','hyd');

insert into student values(sq1.NEXTVAL,'ravi','delhi');

insert into student values(sq1.NEXTVAL,'ramana','vizag');

commit;

2)CURRVAL
It will return the last number which is generated by sequence.
ex:
select sq1.currval from dual;

Q) Write a query to display all sequences present in database?

select sequence_name from user_sequences;

Q) Write a query to drop the sequence?

drop sequence sq1;


drop sequence sq2;
drop sequence sq3;
drop sequence sq4;
Indexes
Indexes is an object which is used to improve the performance of select
statement.

Index in a database is same as index in a book.

Index will be created only to those columns which are widely used in where
clause/condition.

Whenever we create a index , two columns will generated .One is a ROWID


and another is a
indexed column.Bydefault all the records will store in ascending order inside
index column.

index table
-----------------------------------------------------------
ROWID | INDEX COLUMN
--------------------------------------------------------------
| 5000
| 12000
| 20000
| 34000

We have two types of indexs.

1)simple index
When index is created only for one column is called simple index.
syntax:
create index <index_name> on <table_name>(<col_name>);
ex:
create index idx1 on emp(eno);

Here index will occur when we use 'eno' in a where clause.


ex:
select * from emp where eno=206;

2)complex index
When index is created for multiple columns is called complex index.

syntax:
create index <index_name> on <table_name>(col1,col2,..,colN);

ex:
create index idx2 on emp(esal,deptno);

Here index will occur when we use esal and deptno used in where clause.

ex:
select * from emp where esal=12000 and deptno=10;

Indexes are categories in to two types.


1)Unique index
Unique index will be created only to those columns which do not have any
duplicates.
Unique index will be created when table have primary key or unique key.

ex:
create unique index idx3 on emp(eno);

2)Non-unique index
Bydefault every index is a non-unique index.

Non-unique index contains duplicate values.

ex:
create index idx4 on emp(deptno);

Q) Write a query to display all the indexes present in database?

select index_name from user_indexes;

Q) Write a query to drop the index from database?

drop index idx1;


drop index idx2;
drop index idx3;
drop index idx4;

Views
A view is a logical representation of a data from one or more then one table.

syntax:
create view <view_name> as select stmt;

ex:
create view v1 as select * from emp;

A table which is used to create a view is called base table or above table.
View does not consumes the memory.
View does not have any data.
When we write select command , view will get the data from base table or
above table.
Views are divided into different types.

1)Simple View

When view is created by using one base table is called simple view.
DML operations are allowed in simple view.
ex:
create view v1 as select * from emp;
create view v1 as select * from emp where deptno=10;
create view v1 as select eno,ename,esal from emp;
create view v1 as select * from emp where eno IN(201,202,203);
create view v1 as select * from emp where ename like 'A%';
create view v1 as select * from emp where comm is null;
create view v1 as select * from emp where esal between 20000 and
40000;

delete from v1; // all records deleted

select * from v1;


select * from emp;
2)Complex view
When view is created by using more then one base table or above table is
called
complex view.

In complex view DML operations are not allowed.


ex:
create view v2 as select e.eno,e.ename,e.esal,d.dname,d.dloc
from emp e,dept d
where (e.deptno=d.deptno);

select * from v2;

delete from v2; //error

3)with read only view


If we want to create a view by using one base table and DML operations
are not
allowed then we need to use read only view.
ex:
create view v3 as select * from emp with read only;

select * from v3;

delete from v3; // error

4)with check option view


If we want to create a view by using one base table and DML operations
are
allowed when condition is satisfied then we need to use with check option
view.
ex:
create view v4 as select * from emp where deptno=30 with check
option;

select * from v4;

delete from v4 where deptno=30; //valid

5)Materialized view
To create a materialized view a base table must have primary key.
ex:
alter table emp ADD primary key(eno);

create materialized view v5 as select * from emp;


delete from emp; // all records deleted

select * from v5; // all records displaying

Here we need to refresh materialized view.

ex:
exec DBMS_SNAPSHOT.REFRESH('v5');
select * from v5; // no rows selected
Class-9
Sub Queries
Sub query is used to select the records based on unknown values.

We have different types of sub queries.

1)Single Row sub query


2)Multiple Row sub query
3)Multiple column sub query

1)Single Row sub query


When sub query returns only one row is called single row sub query.

sql query

select * from emp where eno=201;


sub query
select * from emp where eno=(select eno from emp where ename='Alan');

Here sub query will execute first then parent query.


Sub query can be nested upto 32 levels.

two level sub query


select * from emp where
eno=(select eno from emp where ename='Alan')
and
ename=(select ename from emp where esal=8000);

Q) Write a query to display second highest salary from emp table?

select max(esal) from emp where esal<(select max(esal) fromm emp);

2)Multiple Row sub query


When sub query returns more then one row is called multiple row sub query.
To perform multiple row sub query we need to use multiple row operators.
We have three multiple row operators.
1)ANY
2)ALL
3)IN
1)ANY
select * from emp where esal > ANY (select esal from emp where
deptno=10);//least one

select * from emp where esal < ANY (select esal from emp where
deptno=10);//highest

2)ALL
select * from emp where esal > ALL (select esal from emp where
deptno=10);//least one

3)IN

select * from emp where esal IN (select esal from emp where deptno=10);

3)Multiple column sub query


If sub query returns more then one column is called multiple column sub query.

ex:

select * from emp where(eno,ename,esal) IN(select eno,ename,esal from emp


where eno=201);

select eno,ename,esal from emp where(eno,ename,esal) IN(select


eno,ename,esal from emp where eno=201);
PL/SQL
It is a extension of SQL and it will give following features.

1)We can achieve programming features like control statements, loops and etc.
2)It will reduce network traffic.
3)We can display custom messages by using the concept of exception handling.
4)We can perform related operations by the concept of triggers.
5)We can save the source code permanent to database for repeated execution.

PL/SQL block
PL/SQL program is also known as PL/SQL block.

syntax:
DECLARE
-
- // declaration section
-
BEGIN
-
- // executable section
-
EXCEPTION
-
- // exception section
-
END;
/
Declaration section
It is used to declare variables , cursors, exceptions and etc.
It is optional section.

Executable section
It contains lines of code which is used to complete a table.
Actual logic we will write inside executable section.
It is mandatory section.
Exception section

It contains lines of code which is executed when exception is occured.


It is optional section.

To see the output in PL/SQL we need to use below command.


ex:
SQL> set serveroutput on

Q) Write a PL/SQL program to display Hello World?

BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World');
END;
/
Here DBMS_OUTPUT is a package name.
PUT_LINE is a procedure name.

Q) Write a pl/sql program to perform sum of two numbers?

DECLARE
A number;
B number;
C number;
BEGIN
A:=10;
B:=20;
C:=A+B;
DBMS_OUTPUT.PUT_LINE(C);
END;
/

Declaration and intialization using single line


DECLARE
A number:=10;
B number:=20;
C number:=A+B;
BEGIN
DBMS_OUTPUT.PUT_LINE('sum of two numbers is ='||C);
END;
/

Using '&' symbol we can read dynamic inputs.

ex:

DECLARE
A number(3);
B number(3);
C number(6);
BEGIN
A:=&a;
B:=&b;
C:=A+B;
DBMS_OUTPUT.PUT_LINE('sum of two numbers is ='||C);
END;
/

Class-10
To see the output in PL/SQL we need to use below command.
ex:
SQL> set serveroutput on

In PL/SQL we can perform DML and DRL operations.

Q) Write a PL/SQL program to insert a record into student table?


DECLARE
L_sno number(3);
L_sname varchar2(10);
L_sadd varchar2(12);
BEGIN
L_sno:=&sno;
L_sname:='&sname';
L_sadd:='&sadd';
insert into student values(L_sno,L_sname,L_sadd);
DBMS_OUTPUT.PUT_LINE('Record inserted');
END;
/

Q) Write a PL/SQL program to update student name based on student no?


DECLARE
L_sno number(3);
BEGIN
L_sno:=&sno;
update student set sname='ramulu' where sno=L_sno;
DBMS_OUTPUT.PUT_LINE('Thank you for updating');
END;
/

Q) Write a PL/SQL program to delete student record based on student no?

DECLARE
L_sno number(3);
BEGIN
L_sno:=&sno;
delete from student where sno=L_sno;
DBMS_OUTPUT.PUT_LINE('Thank you for deleting');
END;
/

To write select command in PL/SQL we need to use into clause.

Q) Write a PL/SQL program to display employee name whose employee


number is 201?

DECLARE
L_ename varchar2(10);
BEGIN
select ename into L_ename from emp where eno=201;
DBMS_OUTPUT.PUT_LINE(L_ename);
END;
/

Q) Write a PL/SQL program to display employee name and employee salary


from emp table whose employee number is 204?

DECLARE
L_ename varchar2(10);
L_esal number(10,2);
BEGIN
select ename,esal into L_ename,L_esal from emp where eno=204;
DBMS_OUTPUT.PUT_LINE(L_ename||' '||L_esal);
END;
/

Percentage(%) TYPE attribute


It is used to declare a local variable which holds complete column of a table.

syntax:
varaible_name table_name.col_name%TYPE;

ex:
A emp.eno%TYPE;

Q) Write a PL/SQL program to display employee name, employee salary ,


employee job from
emp table whose employee number is 202?

DECLARE
L_ename emp.ename%TYPE;
L_esal emp.esal%TYPE;
L_ejob emp.job%TYPE;
BEGIN
select ename,esal,job into L_ename,L_esal,L_ejob from emp where eno=202;
DBMS_OUTPUT.PUT_LINE(L_ename||' '||L_esal||' '||L_ejob);
END;
/
Percentage(%) ROWTYPE attribute
It is used to declare a local variable which holds completed row of a table.

syntax:
variable_name table_name%ROWTYPE;
ex:
A emp%ROWTYPE;

We can't display rowtype variable directly.

To display the data from rowtype variable we need to use


variable_name.column_name.

Q) Write a PL/SQL program to display employee information whose employee


no is 206?
DECLARE
A emp%ROWTYPE;
BEGIN
select * into A from emp where eno=206;
DBMS_OUTPUT.PUT_LINE(A.eno||' '||A.ename||' '||A.esal||' '||A.deptno||'
'||A.job);
END;
/
Control Statements
IF THEN

It will evaluate the code if condition is true.

ex:

DECLARE
A number:=100;
BEGIN

IF A>5 THEN
DBMS_OUTPUT.PUT_LINE('TRUE');
END IF;

END;
/

ex:

DECLARE
A number:=100;
BEGIN

IF A>500 THEN
DBMS_OUTPUT.PUT_LINE('TRUE');
END IF;

END;
/

IF THEN ELSE
It will evaluate the code either our condition is true or false.

ex:
DECLARE
A number:=5;
BEGIN

IF A>2 THEN
DBMS_OUTPUT.PUT_LINE('TRUE');
ELSE
DBMS_OUTPUT.PUT_LINE('FALSE');
END IF;

END;
/

ex:
DECLARE
A number:=5;
BEGIN

IF A>20 THEN
DBMS_OUTPUT.PUT_LINE('TRUE');
ELSE
DBMS_OUTPUT.PUT_LINE('FALSE');
END IF;

END;
/

IF THEN ELSIF THEN ELSE


It will evaluate the code based on multiple conditions.

ex:
DECLARE
A number:=103;
BEGIN

IF A=100 THEN
DBMS_OUTPUT.PUT_LINE('It is police number');
ELSIF A=103 THEN
DBMS_OUTPUT.PUT_LINE('It is enquiry number');
ELSIF A=108 THEN
DBMS_OUTPUT.PUT_LINE('It is emergency number');
ELSE
DBMS_OUTPUT.PUT_LINE('Invalid option');
END IF;

END;
/

LOOPS
We have three types of loops.
1)Simple loop
2)While loop
3)for loop

1)Simple loop
It will evaluate the code untill our condition is true.

ex:
DECLARE
A number:=1;
BEGIN

DBMS_OUTPUT.PUT_LINE('Welcome');

LOOP
DBMS_OUTPUT.PUT_LINE('Hello');
EXIT WHEN A=4;
A:=A+1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Thank You');
END;
/

2)while loop
It will evaluate the code untill our condition is true.

ex:

DECLARE
A number:=1;
BEGIN

DBMS_OUTPUT.PUT_LINE('Welcome');

WHILE A<=4 LOOP


DBMS_OUTPUT.PUT_LINE('Hello');
A:=A+1;
END LOOP;

DBMS_OUTPUT.PUT_LINE('Thank you');
END;
/

3)FOR LOOP
It will evaluate the code untill our condition is true.
ex:
DECLARE
A number;
BEGIN
DBMS_OUTPUT.PUT_LINE('Welcome');

FOR A IN 1 .. 4 LOOP
DBMS_OUTPUT.PUT_LINE('Hello');
END LOOP;

DBMS_OUTPUT.PUT_LINE('Thank you');
END;
/
Exceptions
Runtime errors are called exceptions.

Exception always occured at runtime so they are also known as runtime events.

In PL/SQL we have two types of exceptions.

1)Predefine exceptions
2)Userdefine exceptions

1)Predefine exceptions
Built-In exceptions are called predefine exceptions.
Predefine exceptions contain exception name and exception number.

We have following list of predefine exceptions in java.

1)NO_DATA_FOUND EXCEPTION
2)TOO_MANY_ROWS EXCEPTION
3)VALUE_ERROR EXCEPTION
4)ZERO_DIVIDE EXCEPTION
5)DUP_VAL_ON_INDEX EXCEPTION
6)OTHERS

1)NO_DATA_FOUND EXCEPTION
This exception will occur when select statement does not return any row.

DECLARE
L_ename emp.ename%TYPE;
BEGIN
select ename into L_ename from emp where eno=209;
DBMS_OUTPUT.PUT_LINE(L_ename);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('please check the employee id ');
END;
/

2)TOO_MANY_ROWS EXCEPTION
This exception will occur when select statement returns more then one row.
ex:

DECLARE
L_ename emp.ename%TYPE;
BEGIN
select ename into L_ename from emp ;
DBMS_OUTPUT.PUT_LINE(L_ename);
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('select statement returns more then one row ');
END;
/

3)VALUE_ERROR
This exception will occur when there is a mismatch with datatype and size.
ex:

DECLARE
L_esal emp.esal%TYPE;
BEGIN
select ename into L_esal from emp where eno=202;
DBMS_OUTPUT.PUT_LINE(L_esal);
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('please check the column ');
END;
/

4)ZERO_DIVIDE
This exception will occur when we are trying to divide any number with zero.

ex:
DECLARE
A number;
BEGIN
A:=100/0;
DBMS_OUTPUT.PUT_LINE(A);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Please dont divide by zero');
END;
/

5)DUP_VAL_ON_INDEX
This exception will occur when we are trying to insert duplicate value in a
column.

ex:
alter table emp add primary key(eno);

BEGIN
insert into emp values(204,'Ana',19000,40,'Salesman',100);
DBMS_OUTPUT.PUT_LINE('Thank you for inserting');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Duplicates not allowed');
END;
/

6)OTHERS
It is a universal angular exception which handles all types of exceptions.

ex:

DECLARE
L_ename emp.ename%TYPE;
BEGIN
select ename into L_ename from emp where eno=209;
DBMS_OUTPUT.PUT_LINE(L_ename);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('please check the employee id ');
END;
/
Class-11
To see the output in PL/SQL we need to use below command.
ex:
SQL> set serveroutput on
Userdefine exceptions
Exceptions which are created by the user based on the requirement is called
userdefine exceptions.

steps to develop user define exceptions


step1:
Declare the Exception

step2:
Raise the exception

step3:
Handle the exception

ex:
DECLARE
L_esal number:=5000;
MY_EX1 Exception;

BEGIN
IF L_esal>2000 THEN
RAISE MY_EX1;
END IF;
DBMS_OUTPUT.PUT_LINE(L_esal);

EXCEPTION
WHEN MY_EX1 THEN
DBMS_OUTPUT.PUT_LINE('Salary is too high');
END;
/

Cursors
Cursor is a memory location which is used to run SQL commands.

We have two types of cursors.

1)Implicit cursor
2)Explicit cursor

1)Implicit cursor
All the activities related to cursor like opening the cursor , processing the cursor
closing the cursor which is done automatically is called implicit cursor.

We have four types of cursors attributes.


i)SQL%ISOPEN
ii)SQL%FOUND
iii)SQL%NOTFOUND
iv)SQL%ROWCOUNT

i)SQL%ISOPEN
It is a boolean attribute which always returns false.
ii)SQL%FOUND
IT is a boolean attribute which returns true if SQL command is success
and returns
false is SQL command is failed.

iii)SQL%NOTFOUND
It is completely reverse of SQL%FOUND.

IT is a boolean attribute which returns false if SQL command is success


and returns
true is SQL command is failed.

iv)SQL%ROWCOUNT
It will return number of records effected in a table.

SQL%ISOPEN
BEGIN
IF SQL%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('cursor is opened');
ELSE
DBMS_OUTPUT.PUT_LINE('cursor is closed');
END IF;
END;
/

ii)SQL%FOUND
BEGIN
update student set sname='Alan' where sname='ramana';
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Record updated');
ELSE
DBMS_OUTPUT.PUT_LINE('Record Not updated');
END IF;
END;
/

iii)SQL%NOTFOUND
BEGIN
update student set sname='kelvin' where sname='jojo';
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('Record updated');
ELSE
DBMS_OUTPUT.PUT_LINE('Record Not updated');
END IF;
END;
/

iv)SQL%ROWCOUNT
BEGIN
update student set sname='raj';
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||' records updated');
END;
/

2)Explicit cursor
All the activities relatead to cursor like opening the cursor , processing the
cursor
and closing cursor which is done by a user is called explicit cursor.

We need to use explicit cursor when select statement returns more then one row.

steps to develop explicit cursor


step1:
Declare a cursor
ex:
CURSOR CURSOR_NAME is select stmt;
step2:
OPEN The cursor
ex:
OPEN CURSOR_NAME

step3:
Fetch the data from cursor to local variables
ex:
FETCH CURSOR_NAME INTO VAR1,VAR2,..,VARN;
step4:
Close the cursor
ex:
CLOSE CURSOR_NAME;
Q) Write a PL/SQL program to select employee names from emp table?
DECLARE
L_Ename emp.ename%TYPE;
CURSOR C1 is select ename from emp;
BEGIN
OPEN C1;
LOOP
FETCH C1 into L_Ename;
DBMS_OUTPUT.PUT_LINE(L_Ename);
EXIT WHEN C1%NOTFOUND;
END LOOP;
CLOSE C1;
END;
/
Q) Write a PL/SQL program to display employee number , employee name and
employee salary
from emp table?

DECLARE
L_Eno emp.eno%TYPE;
L_Ename emp.ename%TYPE;
L_Esal emp.esal%TYPE;
CURSOR C2 is select eno,ename,esal from emp;
BEGIN
OPEN C2;
LOOP
FETCH C2 into L_Eno,L_Ename,L_Esal ;
DBMS_OUTPUT.PUT_LINE(L_Eno||' '||L_Ename||' '||L_Esal );
EXIT WHEN C2%NOTFOUND;
END LOOP;
CLOSE C2;
END;
/

Procedures
In PL/SQL procedures are also known as stored procedures.

A procedure is named PL/SQL block which is compiled and execute


permanently in a
database for repeated execution.

syntax:
create or replace procedure <procedure_name>
is
begin
-
- -- code to be execute
-
end;
/

Q) Write a procedure to display Hello World?

create or replace procedure p1


is
begin
DBMS_OUTPUT.PUT_LINE('Hello World');
END;
/

To call the procedure we need to use below command.


ex:
SQL>exec p1;

Every procedure may have three parameters.

1)IN parameter
2)OUT parameter
3)IN OUT parameter

1)IN parameter
It is used to accept the values from the user.

Q) write a PL/SQL program to accept two numbers and display sum?

create or replace procedure sum(A IN number, B IN number)


is
C number;
begin
C:=A+B;
DBMS_OUTPUT.PUT_LINE('Sum of two numbers is ='||C);
END;
/
To execute above procedure we need to use below command.
ex:
SQL> exec sum(10,20);

2)OUT parameter
It is used to return the value to the user.

Q) Write a procedure to accept two numbers and return sum?

create or replace procedure ret_sum(A IN number,B IN number,C OUT


number)
is
begin
C:=A+B;
END;
/

steps to call the procedure having out parameter


step1:
Declare a bind variable
ex:
variable N number;

step2:
Execute the procedure.
ex:
exec ret_sum(10,20,:N);

step3:
print the bind variable.
ex:
print N;

3)IN OUT parameter


It is used to accept the value from the user and it is used to return the value to
the
user.

ex:
create or replace procedure ret_square(A IN OUT number)
is
begin
A:=A*A;
END;
/
Steps to call a procedure having IN OUT parameter
step1:
declare a bind variable
ex:
variable N number;
step2:
intialize the bind variable
ex:
begin
:N:=5;
END;
/
step3:
execute the procedure
ex:
exec ret_square(:N);
step4:
print the bind variable
ex:
print N;

Functions
Function is a named PL/SQL block which must and should returns a value.

syntax:
create or replace function function_name
return datatype
is
begin
-
-
-
return datatype;
end;
/

Q) Write a PL/SQL function to accept two numbers and return sum?

create or replace function f1(A number,B number)


return number
is
C number;
begin
C:=A+B;
return C;
END;
/

Functions can be invoked by using select statement.


ex:
select f1(10,20) from dual;

Q) Differences between procedures and functions?

Procedures Functions
A procedure may or maynot A function always returns a value.
returns a value.
DML operations are allowed. DML operations are not allowed.
Can't be invoked by using select statement. Can be invoked by using select
statement.
Class-12

To see the output in PL/SQL we need to use below command.


ex:
SQL> set serveroutput on

Packages
A package is a collection of logical related sub programs.

PL/SQL procedures and functions are called sub programs.

In general, package is a collection of procedures and functions.

A package creation involved in two steps.

1)Package specification

Package specification means declaration of logical related sub programs.

2)Package body
Package body contains definition of logical related sub programs.

ex:1

Package specification
create or replace package pkg1
is
procedure p1;
end pkg1;
/

package body
create or replace package body pkg1
is
procedure p1
is
begin
DBMS_OUTPUT.PUT_LINE('This is procedure');
END;
END pkg1;
/

To execute above procedure we need to use below command.


ex:
exec pkg1.p1;

ex:2
package specification
create or replace package pkg2
is
function sum(A number,B number)
return number;
end pkg2;
/

package body
create or replace package body pkg2
is
function sum(A number,B number)
return number
is
C number;
begin
C:=A+B;
return C;
END;
end pkg2;
/

To execute above function we need to use below command.


ex:
select pkg2.sum(10,20) from dual;

Note:
If we get any error in PL/SQL we need to use below command.
ex:
SQL>show error;
ex:3
package specification
create or replace package pkg3
is
procedure getRecords(L_eno IN number);
function square(A number)
return number;
end pkg3;
/

package body
create or replace package body pkg3
is

procedure getRecords(L_eno IN number)


is
L_ename emp.ename%TYPE;
begin
select ename into L_ename from emp where eno=L_eno;
DBMS_OUTPUT.PUT_LINE(L_ename);
END;

function square(A number)


return number
is
square number;
begin
square:=A*A;
return square;
END;

END pkg3;
/

To execute above procedure and function we need to use below commands.


ex:
exec pkg3.getRecords(201);

or

select pkg3.square(5) from dual;

Interview queries
Q) Write a query to see the list of procedures present in Database?

select object_name from user_objects where


object_type='PROCEDURE';

Q) Write a query to see the source code of a procedure?

select text from user_source where name='P1';


Q) Write a query to drop the procedure from database?

drop procedure p1;

Q) Write a query to see the list of functions present in Database?

select object_name from user_objects where object_type='FUNCTION';

Q) Write a query to see the source code of a function?

select text from user_source where name='F1';

Q) Write a query to drop the function from database?

drop function f1;

Q) Write a query to see the list of packages present in Database?

select object_name from user_objects where object_type='PACKAGE';

Q) Write a query to see the source code of a package?


select text from user_source where name='PKG1';

Q) Write a query to drop the package from database?


drop package pkg1;
drop package pkg2;
drop package pkg3;

Triggers
Trigger is a PL/SQL block which is executed based on event.

Trigger events are insert,update and delete.

Trigger timings are before , after and insteadof.

syntax:
create or replace trigger <trigger_name><timming><event> on
<object_name>
begin
-
- //code to execute
-
end;
/
ex:
create or replace trigger trg1 after insert on student
begin
DBMS_OUTPUT.PUT_LINE('Thank you for inserting');
END;
/
select * from student;

insert into student values(104,'lucy','USA');

We can create multiple triggers on a table.

ex:2
create or replace trigger trg2 before insert OR update OR delete on student
begin

IF inserting then
DBMS_OUTPUT.PUT_LINE('Record Inserted');
ELSIF updating then
DBMS_OUTPUT.PUT_LINE('Record updated');
ELSE
DBMS_OUTPUT.PUT_LINE('Record deleted');
END IF;

END;
/

select * from student;

insert into student values(104,'Lucy','USA');


update student set sname='jojo' where sno=103;
delete from student where sno=104;
We have two types triggers.

1)Statement level trigger


Statement level trigger will execute only for one time irrespective of number of
records effected in a table.

Bydefault every trigger is a statement level trigger.

ex:
create or replace trigger trg3 after delete on emp
begin
DBMS_OUTPUT.PUT_LINE('Thank you for deleting');
END;
/

2)Row level trigger


ROW level trigger will execute based on number of records effected in a
database table.

To create a row level trigger we need to use for each row clause.
ex:
create or replace trigger trg3 after delete on emp FOR EACH ROW
begin
DBMS_OUTPUT.PUT_LINE('Thank you for deleting');
END;
/
select * from emp;
delete from emp;

interview queries
Q) Write a query to see the list of triggers present in database?

select object_name from user_objects where object_type='TRIGGER';

Q) Write a query to see the source code of a trigger?

select text from user_source where name='TRG2';

Q) Write a query to drop a trigger from database?


drop trigger trg1;

You might also like