Types of Data
Types of Data
==============
1) Unstructured Data
2) Structured Data
1) Unstructured Data
---------------------
A data which is not in readable format such type of data is called unstructured.
ex:
2) Structured Data
------------------
A data which is in readable format such type of data is called structured data.
ex:
Oracle
========
Oracle
|-------------------------------------------------|
SQL PL/SQL
Client/Server Architecture
==========================
Diagram: oracle1.1
In Client-Server architecture we need to see , how our data will store from frontend to backend.
Frontend
-------------------
The one which is visible to the enduser to perform some operations is called frontend.
ex:
Communication Channel
----------------------
ex:
BackEnd
-------
The one which is not visible to the enduser but it performs operations based on the instructions given by frontend is
called backend.
ex:
Oracle, MySQL, SQL Server , MongoDB, DB2 , Sybase, Teradata, NoSQL and etc.
Management System
=============================
DBMS
========
A database along with software which is used to manage the database is called database management system.
RDBMS
=========
If database is created based on relational theories is called relational database management system.
ex:
Oracle
MySQL
SQL Server
PostgreSQL
Teradata
Sybase
and etc.
DBMS RDBMS
------- -------
It stores the data in the form of files. It stores the data in the form of tables.
It is designed to handle small amount of data. It is designed to handle large amount of data.
It provides support for a single user It provides support for multiple users at a time.
at a time.
SQL
=====
ex:
---------------------------------
ex:
------------------------------------
ex:
---------------------------------
ex:
select
-----------------------------
ex:
---------------------------------
ex:
Table
=======
A table is used to store the data in the form of rows and columns.
ex:
No Name Add
----------------------------------------
----------------------------------------
----------------------------------------
----------------------------------------
Oracle
========
Version : 21c
Website :www.oracle.com/in/oracle
Port No : 1521
password : admin
Download link :
https://drive.google.com/file/d/1tBx4vH14_cF9XClgnOF6L_1kdODbHSM5/view?usp=drive_link
================================================
1)
SQL> connect
username : system
password : admin
SQL> disconnect
2)
SQL> conn
username : system
password : admin
SQL> disc
3)
SQL> disc
create command
===================
syntax:
-----
colN datatype(size));
ex:
describe command
=================
syntax:
desc <table_name>;
ex:
desc student;
desc emp;
desc dept;
insert command
==============
syntax:
-----
ex:
approach2
---------
approach3
---------
commit command
==============
syntax:
commit;
dept table
=========
commit;
emp table
==========
commit;
select command
===============
syntax:
-------
ex:
Projection
----------
ex:
Column Alias
------------
Column alias is temperory.Once the query is executed we will loss the column alias.
ex:
sname as NAME,
sadd as CITY
from student;
Interview Queries
=================
Q) Write a query to display employee id , employee name and employee salary from employee table?
where clause
============
ex:
ex:
Interview Queries
-----------------
Q) Write a query to display employees information those who are working in 10 department?
Q) Write a query to display employees information those who are working as a Manager?
Q) Write a query to display employees information whose salary is greater then 30000?
update command
==============
syntax:
------
ex:
Note:
----
ex:
Delete command
============
syntax:
-------
ex:
Note:
-----
ex:
Logical Operators
==================
1) AND
2) OR
3) NOT
1) AND
---------
ex:
2) OR
-----
3) NOT
-------
ex:
Interview Queries
-----------------
Q) Write a query to display employees information whose salary is greater then equals to 30000 and less then equals
to 50000?
Between operator
=================
Between operator will return the records those who are in the range of values.
In between operator , first we need to write lower limit then higher limit.
ex:
IN operator
===========
It will return the records those who are matching in the list of values.
ex:
============================
Pattern matching operatores are used to select the letters from database table.
1) Percentage(%)
2) Underscore(_)
1) Percentage(%)
----------------
Q) Write a query to display employee information whose employee name starts with 'A' letter?
Q) Write a query to display employee information whose employee name ends with 'n' letter?
Q) Write a query to display employee information whose employee name middle letter as 'l'?
2) Underscore (_)
=================
Q) Write a query to display employee information whose employee name second letter is 'l'?
Q) Write a query to display employee information whose employee name having second last
letter is 'c'?
Q) Write a query to display employee information whose employee name having third letter as 'n'?
DDL commands
============
1) create (tables)
2) alter (columns)
3) drop (tables)
4) truncate (rows/records )
5) rename (tables)
2) alter command
=================
-----------------------
syntax:
------
,...,colN datatype(size));
ex:
---
----------------------------------
We can increase and decrease the size of column only when existing values are fit into new size.
syntax:
------
desc student;
desc student;
desc student;
-----------------------
syntax:
------
ex:
--------------------------
syntax:
-------
ex:
alter table student rename column sadd to city;
3) drop command
=================
syntax:
ex:
4) truncate command
====================
syntax:
-----
ex:
---------- ------------
5) rename command
=================
syntax:
-----
ex:
====================================
Using create and select command we can create duplicate or copy of a table.
ex:
create table stud as select * from emp where esal>=30000 AND esal<=50000;
create table stud as select * from emp where ename like 'A%';
cl scr
======
ex:
cl scr
==================
A dual table is a dummy table which contains one row and one column.
It is used to perform arithmetic operations and to see the current system date.
ex:
Functions
=========
Functions are used to manipulate the data items and gives the result.
1) Group functions
--------------------
ex:
count(*)
--------
ex:
count(expression)
-----------------
ex:
userlist table
==============
==========================================
i) Character functions
i) Character functions
------------------------
upper()
-------
ex:
---------
ex:
initcap()
---------
ex:
lpad()
-------
ex:
rpad()
------
ex:
ltrim()
--------
ex:
rtrim()
-------
trim()
-------
ex:
concat()
--------
ex:
---------------------
abs()
-----
ex:
sqrt()
------
ex:
power(A,B)
----------
ex:
ceil()
------
ex:
floor()
--------
ex:
round()
--------
ex:
trunc()
-------
greatest()
----------
ex:
least()
--------
ex:
=========================
ex:
ex:
---
commit;
--------------------
ADD_MONTHS()
-------------
ex:
MONTHS_BETWEEN()
------------
ex:
--------
ex:
LAST_DAY()
---------
ex:
----------------------
A process of converting from one type to another type is called conversion function.
ex:
TO_CHAR()
1) Number TO_CHAR()
--------------------
ex:
2) Date TO_CHAR()
-----------------
Group by clause
================
It is used to divide the rows into groups so that we can apply group functions.
A column which we used in select clause then same column name we should use in group by clause.
ex:
Having clause
==============
ex:
Q) Write a query to display sum of salary of each department whose sum of salary is
Q) Write a query to display maximum salary of each job whose maximum salary is
================
ex:
Note:
-----
group by deptno
having ssum(esal)>50000
order by deptno;
Integrity Constraints
======================
1) NOT NULL
2) UNIQUE
3) PRIMARY KEY
4) FOREIGN KEY
5) CHECK
i) Table level
1) NOT NULL
-----------
column level
-----------
commit;
Note:
----
NOT NULL constraint can be applied to multiple columns.
ex:
commit;
2) UNIQUE
----------
column level
------------
commit;
table level
------------
commit;
Note:
-----
ex:
3) Primary Key
===============
Primary key does not accept null values and duplicate values.
column level
------------
commit;
table level
------------
commit;
--------------------------------------------------
This relationship is called parent and child relationship or master and detailed relationship.
To establish the relationship , a parent table must have primary key or unique key and child table must have foreign
key.
Foreign key will accept only those values which are present in primary key.
A primary key column name and foreign key column name may or may not match but datatype must match.
Diagram: oracle6.1
parent table
------------
sname varchar2(10),
sadd varchar2(12));
commit;
child table
----------
book_name varchar2(12));
commit;
How to drop the tables
----------------------
In order to drop the tables. First we need to delete child table then parent table.
ex:
5) CHECK
-------------
column level
------------
commit;
ex:
----
drop table student;
sadd varchar2(12));
commit;
ex:
----
sadd varchar2(12));
commit;
table level
-----------
ex:
----
sname varchar2(10) ,
commit;
Assignment
----------
Customer table
custId
custName
custAddress
Item table
item_custId
itemId
itemName
itemPrice
Payment table
pay_custId
paymentId
paymentAmount
paymentMode
TCL commands
=============
1) commit
2) rollback
3) savepoint
1) commit
----------
syntax:
------
commit;
ex:
commit;
2) rollback
-----------
syntax:
------
rollback;
ex:
---
commit;
3) savepoint
-----------
syntax:
savepoint <save_pointe_name>;
ex:
savepoint sp1;
savepoint sp2;
rollback to sp2;
PSEUDO columns
===============
1) ROWNUM
2) ROWID
1) ROWNUM
--------
ex:
2) ROWID
---------
ROWID is permanent.
ex:
Interview Queries
----------------------
or
minus
DCL commands
============
2) revoke
Schema :
-------
Privileges
---------
1) System privilege
-------------------
2) Object privilege
------------------
grant
------
syntax:
-------
syntax:
Hemanth>
create table employee(eid number(3),ename varchar2(10),esal number(10));
commit;
Tejaswini> commit;
Hemanth> disc
Tejaswini> disc
Sequences
===========
syntax:
------
ex:
1) NEXTVAL
---------
ex:
2) CURRVAL
---------
ex:
Synonym
===========
We can use synonym instead of table name for all the commands.
syntax:
-----
ex:
rollback;
Joins
=======
Table alias
-----------
Using table alias length of the query will reduce mean while performance is maintained.
ex:
Definition of joins
------------------
Joins is used to retrieve the data from one or more then one table.
1) Equi join
2) Non-Equi join
3) Self join
4) Cartisian product
5) Inner join
6) Outer join
1) Equi join
-------------
When two tables are joined based on common column then we need to use equi join.
ex:
where(e.deptno=d.deptno); //6
2) Non-Equi join
---------------
When tables are not joined based on equi join operator is called non-equi join.
ex:
3) Self join
-----------
ex:
4) Cartisian product
------------------
When two tables are joined without any condition is called cartisian product.
ex:
5) Inner join
-----------
ex:
ON(e.deptno=d.deptno); //6
ON(e.deptno=d.deptno); //6
6) Outer join
-------------
----------------
SQL
---
where(e.deptno=d.deptno(+));
ANSI
----
select e.eid,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc
ON(e.deptno=d.deptno);
------------------
SQL
---
where(e.deptno(+)=d.deptno);
ANSI
----
select e.eid,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc
ON(e.deptno=d.deptno);
--------------------
ANSI
-----
select e.eid,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc
ON(e.deptno=d.deptno);
What is the difference between RDBMS and MongoDB database?
RDBMS MongoDB
------------- ---------
It can’t stores the data in key and value pair. It stores the data in key and value pair.
Not suitable for hierarchical data storage. Suitable for hierarchical data storage.
It is slower. It is faster.
Assignment
===========
Input:
AABBBCCCCAABB
output:
A2B3C4A2B2
Indexes
==========
We need to create index only to those columns which are widely used in a where clause.
Whenever we create index , two columns will be generated.One contains ROWID and another contains indexed
column. All the records will store in ascending order in indexed column.
index table
--------------------------------------------
ROWID | INDEX-COLUMN
---------------------------------------------
| 9000
| 17000
| 18000
| 19000
| 29000
| 34000
---------------------------------------------
1)simple index
2)complex index
1)simple index
----------------
When index is created only for one column is called simple index.
syntax:
ex:
create index idx1 on emp(eid);
2)complex index
---------------
syntax:
ex:
Here index is used when we call job and comm in where condition.
Views
=====
View is a virtual representation of a data from one or more then one table.
A table which is used to create a view is called base table or above table.
ex:
1) Simple view
2) Complex view
5) Materialized view
1) Simple view
----------------
ex:
rollback;
2) Complex view
---------------
If a view is created using more then one base table is called complex view.
ex:
where(e.deptno=d.deptno);
-----------------------
If a view is created by using one base table and DML operation is not required then we need to use with read only
view.
ex:
-----------------------
If a view is created by using one base table and DML operation is allowed only when condition is true.
ex:
create view v4 as select * from emp where deptno=30 with check option;
5) Materialized view
--------------------
ex:
commit;
EXEC DBMS_SNAPSHOT.REFRESH('v5');
select * from emp; // 6 records
Sub Queries
==========
If we declare a query inside another query such concept is called sub query.
----------------------
If a sub query returns only one row is called single row subquery.
ex:
SQL
-----
Sub Query
--------
select * from emp where ename=(select ename from emp where eid=201);
ex:
---
SQL
----
Sub Query
-------
AND
Q) Write a query to display employee information whose salary is greater then Nelson?
select * from emp where esal > (select esal from emp where ename='Nelson');
Q) Write a query to display second highest salary from employee table?
----------------------
If a 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.
1) ANY
2) ALL
3) IN
ex:
select * from emp where esal > ANY (select esal from emp where deptno=10);
select * from emp where esal < ANY (select esal from emp where deptno=10);
ex:
select * from emp where esal > ALL (select esal from emp where deptno=10);
select * from emp where esal < ALL (select esal from emp where deptno=10);
ex:
select * from emp where esal IN (select esal from emp where deptno=10);
---------------------------
When subquery returns more then one column is called multiple column sub query.
ex:
Merge Command
==============
student10 table
---------------
commit;
student20 table
---------------
commit;
ex:
using student20 s2
ON(s1.sno=s2.sno)
Normalization Denormalization
---------------------- -----------------
It is increases the complexity because of It will reduce complexity because of single table.
multiple tales.
PL/SQL
=======
1) We can achieve programming features like control statements, loops and etc.
2) It reduces network traffic.
3) We can display custom error messages by using the concept of exception handling.
PL/SQL Block
=============
ex:
DECLARE
- // Declaration Section
BEGIN
- // Executale Section
EXCEPTION
- // Exception Section
END;
Declaration Section
--------------------
It is a optional section.
Executable Section
----------------
It is a mandatory section.
Exception Section
----------------
It is a optional section.
ex:
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World');
END;
DECLARE
A number;
B number;
C number;
BEGIN
A:=10;
B:=20;
C:=A+B;
DBMS_OUTPUT.PUT_LINE(C);
END;
ex:
DECLARE
A number:=10;
B number:=20;
C number:=A+B;
BEGIN
END;
ex:
---
DECLARE
A number(3);
B number(3);
C number(6);
BEGIN
A:=&a;
B:=&b;
C:=A+B;
END;
/
ex:
ex:
DECLARE
L_sno number(3);
L_sname varchar2(10);
L_sadd varchar2(12);
BEGIN
L_sno:=&sno;
L_sname:='&sname';
L_sadd:='&sadd';
DBMS_OUTPUT.PUT_LINE('Record Inserted');
END;
ex:
DECLARE
L_sno number(3);
BEGIN
L_sno:=&sno;
END;
ex:
DECLARE
L_sno number(3);
BEGIN
L_sno:=&sno;
DBMS_OUTPUT.PUT_LINE('Record Deleted');
END;
ex:
DECLARE
L_empName varchar2(10);
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empName);
END;
/
Q) Write a Pl/SQL program to display employee name and employee salary whose employee id is 205?
ex:
DECLARE
L_empName varchar2(10);
L_empSal number(10,2);
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);
END;
Q) Write a PL/SQL program to display employee name, employee salary based on employee id ?
ex:
DECLARE
L_empName varchar2(10);
L_empSal number(10,2);
L_empId number(3);
BEGIN
L_empId:=&eid;
DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);
END;
==============================
syntax:
-------
variable_name table_name.col_name%TYPE;
ex:
A emp.eid%TYPE;
Q) Write a PL/SQL program to display employee name, employee salary based on employee id ?
ex:
DECLARE
L_empName emp.ename%TYPE;
L_empSal emp.esal%TYPE;
L_empId emp.eid%TYPE;
BEGIN
L_empId:=&eid;
DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);
END;
=============================
syntax:
-------
variable_name table_name%ROWTYPE;
ex:
Q) Write a PL/SQL program to display employee information whose employee id is 206?
ex:
DECLARE
A emp%ROWTYPE;
BEGIN
END;
Control Statements
===================
1) IF THEN
2) IF THEN ELSE
1) IF THEN
-----------
ex:
DECLARE
A number:=5000;
BEGIN
IF A>2000 THEN
DBMS_OUTPUT.PUT_LINE('It is greatest');
END IF;
END;
ex:
DECLARE
A number:=1000;
BEGIN
IF A>2000 THEN
DBMS_OUTPUT.PUT_LINE('It is greatest');
END IF;
END;
2) IF THEN ELSE
-----------------
ex:
---
DECLARE
A number:=5000;
BEGIN
IF A>2000 THEN
ELSE
END IF;
END;
ex:
---
DECLARE
A number:=1000;
BEGIN
IF A>2000 THEN
ELSE
END IF;
END;
-------------------
ex:
DECLARE
A number:=103;
BEGIN
IF A=100 THEN
ELSE
DBMS_OUTPUT.PUT_LINE('Invalid option');
END IF;
END;
LOOPS
=====
1) Simple loop
2) while loop
3) for loop
1) Simple loop
----------------
ex:
DECLARE
A number:=1;
BEGIN
DBMS_OUTPUT.PUT_LINE('Welcome');
LOOP
DBMS_OUTPUT.PUT_LINE('Hello');
A:=A+1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Thankyou');
END;
2) while loop
-------------
ex:
DECLARE
A number:=1;
BEGIN
DBMS_OUTPUT.PUT_LINE('Welcome');
DBMS_OUTPUT.PUT_LINE('Hello');
A:=A+1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Thankyou');
END;
/
3) for loop
-------------
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('thankyou');
END;
Interview Skills
=================
java
----
class Test
for(int i=1;i<=10;i++)
{
System.out.println(i);
PL/SQL
------
DECLARE
A number;
BEGIN
FOR A IN 1 .. 10 LOOP
DBMS_OUTPUT.PUT_LINE(A);
END LOOP;
END;
ex:
Exceptions
===========
1) Predefined exceptions
2) Userdefined exceptions
1) Predefined exceptions
------------------------
Built-In exceptions are called predefined exceptions.
i) NO_DATA_FOUND Exception
v) DUP_VAL_ON_INDEX Exception
vi) OTHERS
i) NO_DATA_FOUND Exception
--------------------------
This exception will raise when select statement does not return any row.
ex:
DECLARE
L_empName emp.ename%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empName);
EXCEPTION
END;
/
ii) TOO_MANY_ROWS Exception
----------------------------
This exception will raise when select statement returns more then one row.
ex:
---
DECLARE
L_empName emp.ename%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empName);
EXCEPTION
END;
------------------------
This exception will raise when we divide any number with zero.
ex:
--
DECLARE
A number;
BEGIN
A:=10/0;
DBMS_OUTPUT.PUT_LINE(A);
EXCEPTION
END;
/
iv) VALUE_ERROR Exception
------------------------
This exception will raise when there is a mismatch with datatype or size.
ex:
DECLARE
L_empSal emp.esal%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empSal);
EXCEPTION
END;
ex:
----
DECLARE
A number(3);
BEGIN
A:=1234;
DBMS_OUTPUT.PUT_LINE(A);
EXCEPTION
END;
v) DUP_VAL_ON_INDEX Exception
--------------------------
This exception will raise when we insert duplicate values on primary key.
ex:
BEGIN
DBMS_OUTPUT.PUT_LINE('Record Inserted');
EXCEPTION
END;
vi) OTHERS
----------
ex:
DECLARE
L_empName emp.ename%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empName);
EXCEPTION
END;
2) Userdefined exceptions
-------------------------
Exceptions which are created by the user based on the application requirement are called
userdefined exceptions.
step1:
-------
step2:
-----
step3:
------
ex:
---
DECLARE
MY_EX1 Exception;
SALARY number:=5000;
BEGIN
IF SALARY>2000 THEN
RAISE MY_EX1;
END IF;
DBMS_OUTPUT.PUT_LINE(SALARY);
EXCEPTION
END;
Cursors
========
1) Implicit cursor
2) Explicit cursor
1) Implicit cursor
------------------
All the activities related to cursor like opening the cursor, processing the cursor and closing the cursor which is done
automatically is called implicit cursor.
i) SQL%ISOPEN
-----------
ii) SQL%FOUND
--------------
It is a boolean attribute which returns true if SQL command is success and returns
iii) SQL%NOTFOUND
---------------
It is inverse of SQL%FOUND.
It is a boolean attribute which returns false if SQL command is success and returns
iv) SQL%ROWCOUNT
-----------------
-------------
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
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Record Updated');
ELSE
END IF;
END;
iii) SQL%NOTFOUND
------------
BEGIN
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
END;
2) Explicit cursor
-----------------
All the activities related to cursor like opening the cursor, processing the cursor and closing the cursor which is done
by user is called explicit cursor.
We need to explicit cursor when select statement returns more then one row.
i) %ISOPEN
---------
It will return true if cursor is opened and returns false if cursor is closed.
ii) %FOUND
---------
It will return true if SQL command is success and returns false if SQL command failed.
iii) %NOTFOUND
-------------
It is inverse of %FOUND.
It will return false if SQL command is success and returns true if SQL command failed.
iv) %ROWCOUNT
------------
ex:
DECLARE
L_empName emp.ename%TYPE;
BEGIN
OPEN C1;
LOOP
DBMS_OUTPUT.PUT_LINE(L_empName);
END LOOP;
CLOSE C1;
END;
Q) Write a PL/SQL program to select employee names,employee salarys from employee table?
ex:
DECLARE
L_empName emp.ename%TYPE;
L_empSal emp.esal%TYPE;
BEGIN
OPEN C1;
LOOP
DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);
END LOOP;
CLOSE C1;
END;
ex:
DECLARE
A emp%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 into A;
END LOOP;
CLOSE C1;
END;
/
PL/SQL procedures
==================
It is a named PL/SQL block which is used to compiled and permanently stored in a database for repeated execution.
syntax:
-----
is
begin
end;
is
begin
DBMS_OUTPUT.PUT_LINE('Hello World');
END;
ex:
exec p1;
ex:
===========
1) Predefined exceptions
2) Userdefined exceptions
1) Predefined exceptions
------------------------
i) NO_DATA_FOUND Exception
v) DUP_VAL_ON_INDEX Exception
vi) OTHERS
i) NO_DATA_FOUND Exception
--------------------------
This exception will raise when select statement does not return any row.
ex:
DECLARE
L_empName emp.ename%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empName);
EXCEPTION
END;
----------------------------
This exception will raise when select statement returns more then one row.
ex:
---
DECLARE
L_empName emp.ename%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empName);
EXCEPTION
END;
------------------------
This exception will raise when we divide any number with zero.
ex:
--
DECLARE
A number;
BEGIN
A:=10/0;
DBMS_OUTPUT.PUT_LINE(A);
EXCEPTION
END;
------------------------
This exception will raise when there is a mismatch with datatype or size.
ex:
DECLARE
L_empSal emp.esal%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empSal);
EXCEPTION
END;
ex:
----
DECLARE
A number(3);
BEGIN
A:=1234;
DBMS_OUTPUT.PUT_LINE(A);
EXCEPTION
END;
v) DUP_VAL_ON_INDEX Exception
--------------------------
This exception will raise when we insert duplicate values on primary key.
ex:
BEGIN
DBMS_OUTPUT.PUT_LINE('Record Inserted');
EXCEPTION
END;
vi) OTHERS
----------
ex:
DECLARE
L_empName emp.ename%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE(L_empName);
EXCEPTION
END;
2) Userdefined exceptions
-------------------------
Exceptions which are created by the user based on the application requirement are called
userdefined exceptions.
step1:
-------
step2:
-----
step3:
------
ex:
---
DECLARE
MY_EX1 Exception;
SALARY number:=5000;
BEGIN
IF SALARY>2000 THEN
RAISE MY_EX1;
END IF;
DBMS_OUTPUT.PUT_LINE(SALARY);
EXCEPTION
END;
Cursors
========
1) Implicit cursor
2) Explicit cursor
1) Implicit cursor
------------------
All the activities related to cursor like opening the cursor, processing the cursor and closing the cursor which is done
automatically is called implicit cursor.
i) SQL%ISOPEN
-----------
ii) SQL%FOUND
--------------
It is a boolean attribute which returns true if SQL command is success and returns
iii) SQL%NOTFOUND
---------------
It is inverse of SQL%FOUND.
It is a boolean attribute which returns false if SQL command is success and returns
iv) SQL%ROWCOUNT
-----------------
i) 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
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Record Updated');
ELSE
END IF;
END;
iii) SQL%NOTFOUND
------------
BEGIN
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('Record Updated');
ELSE
END IF;
END;
iv) SQL%ROWCOUNT
------------------
BEGIN
END;
2) Explicit cursor
-----------------
All the activities related to cursor like opening the cursor, processing the cursor and closing the cursor which is done
by user is called explicit cursor.
We need to explicit cursor when select statement returns more then one row.
We have four types of explicit cursor attributes.
i) %ISOPEN
---------
It will return true if cursor is opened and returns false if cursor is closed.
ii) %FOUND
---------
It will return true if SQL command is success and returns false if SQL command failed.
iii) %NOTFOUND
-------------
It is inverse of %FOUND.
It will return false if SQL command is success and returns true if SQL command failed.
iv) %ROWCOUNT
------------
ex:
DECLARE
L_empName emp.ename%TYPE;
BEGIN
OPEN C1;
LOOP
DBMS_OUTPUT.PUT_LINE(L_empName);
END LOOP;
CLOSE C1;
END;
Q) Write a PL/SQL program to select employee names,employee salarys from employee table?
ex:
DECLARE
L_empName emp.ename%TYPE;
L_empSal emp.esal%TYPE;
BEGIN
OPEN C1;
LOOP
DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);
END LOOP;
CLOSE C1;
END;
ex:
DECLARE
BEGIN
OPEN C1;
LOOP
FETCH C1 into A;
END LOOP;
CLOSE C1;
END;
PL/SQL procedures
==================
It is a named PL/SQL block which is used to compiled and permanently stored in a database for repeated execution.
syntax:
-----
is
begin
end;
is
begin
DBMS_OUTPUT.PUT_LINE('Hello World');
END;
ex:
exec p1;
ex:
1) IN Parameter
2) OUT Parameter
3) IN OUT Parameter
1) IN Parameter
----------------
is
C number;
begin
C:=A+B;
END;
ex:
exec sum(10,20);
is
BEGIN
DBMS_OUTPUT.PUT_LINE('Record Deleted');
END;
ex:
exec delete_record(103);
2) OUT Parameter
-----------------
begin
C:=A+B;
END;
--------------------------------------------
step1:
----
ex:
variable N number;
step2:
-----
ex:
exec ret_sum(10,20,:N);
step3:
-----
ex:
print N;
3) IN OUT parameter
------------------
BEGIN
A:=A*A*A;
END;
---------------------------------------------
step1:
-----
ex:
variable N number;
step2:
-----
ex:
BEGIN
:N:=5;
END;
step3:
------
ex:
exec ret_cube(:N);
step4:
------
ex:
print N;
Q) Write a query to see the list of procedures present in database?
Functions
===========
Function is a named PL/SQL block which must and should returns a value.
syntax:
------
return datatype
is
begin
return <value>;
END;
/
Q) Write a function to perform sum of two numbers and return sum?
return number
is
C number;
begin
C:=A+B;
return C;
END;
ex:
Q) Write a function to accept one salary and find out 10% of TDS?
return number
is
TAX number;
begin
TAX:=salary*10/100;
return TAX;
END;
ex:
procedure function
--------------- --------------
A procedure may or may not returns a value. A function always returns a value.
Can't by invoke by using select command. Can by invoke by using select command.
Packages
=========
PL/SQL procedures and functions are called logical related sub programs.
1) Package specification
-----------------
2) package body
---------------
ex:1
-----
package specification
--------------------
is
end pkg1;
package body
------------
is
C number;
begin
C:=A+B;
DBMS_OUTPUT.PUT_LINE(C);
END;
end pkg1;
ex:
exec pkg1.sum(20,30);
ex:2
----
package specification
----------------------
is
return number;
end pkg2;
package body
-------------
is
is
C number;
begin
C:=A+B;
return C;
END;
end pkg2;
ex:
Triggers
=========
syntax:
------
is
begin
END;
ex:
---
begin
END;
Note:
-----
ex:
begin
if inserting then
DBMS_OUTPUT.PUT_LINE('Yahoo! inserted');
DBMS_OUTPUT.PUT_LINE('Yahoo! updated');
else
DBMS_OUTPUT.PUT_LINE('Yahoo! deleted');
end if;
end;
Statement level trigger will execute only for one time irrespective of number of records
ex:
begin
DBMS_OUTPUT.PUT_LINE('Deleted');
END;
-------------------
Row level trigger will execute irrespective of number of records effected in a database table.
ex:
create or replace trigger trg4 after delete on student for each row
begin
DBMS_OUTPUT.PUT_LINE('Deleted');
END;