Oracle SQL
Oracle SQL
Ex:
SNO SNAME MARKS
101 MALLI 99
102 SREE 98
103 KRISH 97
104 VISH 96
A database along with the software which helps to manage. The database is called
database management system (DBMS).
A DBMS which is based on relational theory is called as relational database
management system.
Examples of RDBMS:
1. ORACLE
2. SQL SERVER
3. DB2
4. MYSQL
5. SYBASE
6. TERA DATA
7. MS ACCESS
SQL:
Structured query language pronounced as (SEQUEL). This language is used to
communicate to oracle database.
Features of SQL:
1. It is a command based language.
2. It is not case sensitive.
3. Every command should end with ‘;’.
4. Every command starts with “verb”.
Page 1 of 108
5. It is similar to English. This language is developed in the year 1972. Mr.CODD, by
IBM developed by “IBM”.
*DML: This language is used to manipulate the data you have stored. It is collection of
four commands.
INSERT, UPDATE, DELETE, MERGE
*DRL: This language is used to retrieve the data from the database. It is collection of
only one command.
SELECT
*DCL: This language is used to control the axis of the data to the users it is collection of
two commands.
GRANT, REVOKE
TABLE: Table is an object which is used to store some data. In general it is collection of
Rows and Columns.
Page 2 of 108
Ex:
Create table student (SNO number (3), SNAME varchar2(20), MARKS number(3));
SQL*PLUS: It is a client environment where the developer will write the queries and
submit the queries is execution.
*INSERT COMMENT:
Syntax:
INSERT INTO<TABLE_NAME>VALUES(VAL1,VAL2,VAL3,…………VALn);
EX:
Insert into student values(101,Arun,60);
Error: Arun
Correct: ‘Arun’
Insert into student values(101,’Arun’,60);
*SELECT: This commend is used to return the data from the table.
Page 3 of 108
Syntax1: SELECT * FROM <TABLE_NAME>;
Ex: select * from student; // * represent ALL
Note: where we use * all the information (ALL the columns and the rows are display).
*Columns ALIAS: Column ALIAS user defined column heading given to the required
column.
Ex:
Select EMPNO,ENAME,SAL,SAL*12 ANNUAL_SAL,DEPTNO from EMP;
Select EMPNO ROLL_NO,ENAME,SAL from EMP;
Note:
1. Column Alias can be provides for any column.
2. Column Aliases are temporary.
3. The scope of column Alias is to respect to the same query.
*DATA TYPES:
1. CHAR: The data type is used to store alpha numeric values.
It can be also store special symbols like -,:,/,* and etc.
This data type of fixed size. The Maximum size is 255 bytes.
Note: Memory is not used efficiently.
2.VARCHAR2: This data type it can store alphanumeric values special symbols like -,:,_
and etc. This data type is of variable size. Maximum size 4000 bytes.
Note: Memory is efficiently used.
3.NUMBER(P,S): p-precision/s-scale
This data type used to store numeric values maximum size 38 digits.
4.DATE: This data type is used to store date values it will not have size.
Range 01-JAN-4712 BC TO 31-DEC-9999 AD
Default Date format is DD-MM-YY.
Ex:
Create table student1(SNO number(2),
SNAME varchar2(20),
MARKS number(3),
Page 5 of 108
DOJ Date);
6.RAW: used to store Images,logos,digital signatures etc. Maximum size 255 bytes.
9.BLO:(binary large object) used to store binary data. Maximum size 4 GB.
10.BFILE:(binary file)
*Describe command: This command is used to see the structure of the table.
Ex:
DESCRIBE Student //(not use ;)
NAME NULL TYPE
SNO NUMBER(2)
SNAME VARCHAR2(20)
MARKS NUMBER(3)
NOTE:
It is SQL*PLUS command
Short form is DESC
EXIT
CONN ALL ARE SQL*PLUS
CL SCR COMMANDS
DESC
Page 6 of 108
*where clause: class is used to select specific rows basing on a condition.
Ex:
Select * from emp where sal>2000;
SAL
2975
2875
3000
Select * from emp where deptno = 10;
Select * from student where sno < = 103;
Select eno,ename,sal,deptno from emp where dept = 20;
Note: Data which is stored the inside the table is case sensitive.
Ex:
Select * from emp where job = ‘clerk’;
Select * from student where comm is NULL;
Note: is NULL is operator which is use to retrieve the rows based on NULL values.
Ex:
Select * from student where marks is NULL;
Select * from student where sname is NULL;
*DELETE: This command is used to remove the complete row from the table.
SYSTAX: Delete from <table_name> where <condition>;
*write a
Ex:
query delete command?
Delete from student where sno = 101;
Update student set sname = null, marks = null where sno = 101;
Note: when where clause is not use all the rows delete.
Ex:
Delete from student1;
Select * from emp where SAL >2000 AND JOB = ‘MANAGER’ AND deptno = 30;
Select * from emp where DEPTNO = 10 OR DEPTNO = 20;
Select * from emp where SAL >2000 AND SAL < 4000;
BETWEEN: between operator is used to display the rows which is following in the
range of values.
*IN OPERATOR:
1. IN operator will be return the rows when the values are matching in the list.
2. IN operator can be use as a replacement of OR operator.
Can we display the rows who’s emp name ends with last position ‘E’.
3) DROP: This command is used to rename the table from the database.
Syntax: DROP TABLE <TABLE_NAME>;
Ex:
DROP table student;
DROP table emp;
4) TRUNCATE: This command is used to remove all the rows from the table.
Syntax: TRUNCATE TABLE <TABLE_NAME>;
Ex: TRUNCATE table student;
Select * from TAB; // ALL TABLE NAME’S ARE DISPLAYED
DELETE TRUNCATE
We can Roll Back the data. * We cannot Roll Back the data.
Rows are deleting temporally. * Rows are deleting permanently.
Where clause can be used. * Where clause cannot be used.
Delete is sub language DML. * Delete is sub language DDL.
Page 11 of 108
5) Rename: This command is used to change the table name.
Syntax: RENAME <OLD_TABLE_NAME> TO <NEW_TABLE_NAME>;
Ex: Rename student To student1;
Rename SALGRADE To GRADE;
NOTE: When we use a Truncate command the table gets dropped and re-created. As
the structure is effected is called as a DDL command.
All DDL command are permanent.
All DML command are Temporary.
*To see list of all the tables of a user: Select * from TAB;
*Creating duplicate tables or backup tables: By using the combination of create and
select. We can create copy of a table.
Ex:
Create table emp1 AS select * from emp; //total table copy
Create table emp2 AS select * from emp where deptno = 30; // only deptno = 30
Create table emp3 AS select * from emp where 10; // only deptno =10 is copy
Create table emp4 AS select empno, ename, wages, deptno from emp where
deptno = 20; //empno,ename,wages,deptno is coped by emp4 table
Create table emp5 AS select *from emp where 1=2; //This mean total table copy
***Right click properties options and select quick edit modifier and ok.
**FUNCTIONS: Functions will manuplate the data items and gives the result. They are
two types of functions.
1. Group functions or multiple row functions
2. Scalar functions or single row function
1) Group functions or multiple row functions: This functions act on group of rows.
i. AVG: select AVG(sal) from emp;
ii. SUM: select SUM(sal) from emp;
iii.MAX: select MAX(sal) from emp;
iv.MIN: select MIN(sal) from emp;
v.COUNT(*): select COUNT(*) from emp; //Return total no.of rows in the table
vi.COUNT(EXPR): Return no.of values present in the column.
Ex: Select COUNT(sal) from emp;
Select COUNT(empno) from emp;
Select COUNT(comm) from emp;
Dual table: It is a dummy table which is generally used to perform some calculation is
seeing to the system date and etc. Dual table is collection of one row and one column
with ‘X’ in it.
Ex: Select SYSDATE from dual;
Select 10+20 from dual;
Select 20+40, 50+60 from dual;
2) Scalar functions or single row functions: Scalar function are decided into four
types. They are given that.
i. Character functions
ii. Number functions
iii. Data functions
iv. Conversion functions
i. Character functions:
a. Upper: converts into lower case to upper case.
Ex: Select upper(‘oracle’) from dual; //ORACLE
Page 13 of 108
c. INITCAP: First letter is capital and reaming letters are small letters.
Ex: Select INITCAP(‘oracle training’) from dual; //Oracle
Select INITCAP(‘ORACLE TRAINING’) from dual; //Oracle
h.RTRIM:
Ex: Select RTRIM(‘ZORACLEZZZ’,’Z’) from dual; //ZORACLE
Select RTRIM(‘oracle’) from dual; // oracle
Select RTRIM(‘ORACLE ‘) from dual; // ORACLE
Select LENGTH(RTRIM(‘ORACLE ‘)) from dual; // length is 6
d. POWER(A,B):
Page 15 of 108
Ex: Select POWER(2,5) from dual; // 32
e. CEIL:
Ex: Select CEIL(40.9) from dual; //41
Select CEIL(40.2) from dual; //41
Select CEIL(40.5) from dual; //41
f. FLOOR:
Ex: Select FLOOR(40.9) from dual; //40
Select FLOOR(40.2) from dual; //40
Select FLOOR(40.5) from dual; //40
i. GREATEST:
Ex: Select GREATEST(100,200,300) from dual; // 300
j. LEAST:
Page 16 of 108
Ex: Select LEAST(100,200,300) from dual; // 100
b.Date to_char:
Ex: Select eno,ename,hiredate from emp;
Select eno,ename, TO_CHAR(HIREDATE,’DD-MM-YY’) from emp;
Select eno,ename, TO_CHAR(HIREDATE,’DD-MM-YYYY’) from emp;
Select SYSDATE from dual; // 18-JUN-12
Select TO_CHAR(SYSDATE,’DD-MONTH-YY’) from dual; // 18-JUN-12
Select TO_CHAR(SYSDATE,’DAY’) from dual; // Monday
Select TO_CHAR(SYSDATE,’YYYY’) from dual; // 2012
Select TO_CHAR(SYSDATE,’MM’) from dual; // 06
Select TO_CHAR(SYSDATE,’DDD’) from dual; // 170
Select TO_CHAR(SYSDATE,’DD’) from dual; // 18
Select TO_CHAR(SYSDATE,’MON’) from dual; // MONDAY
Select TO_CHAR(SYSDATE,’DY’) from dual; // mon
Select TO_CHAR(SYSDATE,’DD-MM-YY HH:MI:SS’) from dual; //18-06-12 12:40:44
Select * from emp where TO_CHAR(HIREDATE,’YYYY’) = ‘1981’;
Select * from emp where TO_CHAR(HIREDATE,’YYYY’) = ‘1980’;
Select * from emp where TO_CHAR(HIREDATE,’MON’) = ‘DEC’;
2.TO_NUMBER:
Ex: Select TO_NUMBER(LTRIM(‘$1400’,’$’)) + 10 from dual; // 1410
*Group By clause: Group By clause is used to divided rows into several group. So that
we can apply group function on each group.
Select deptno, sum(sal) from emp where deptno <> 10 Group By deptno;
Select deptno, job, sum(sal) from emp Group By deptno, job;
*Rule of group by clause: All the column in the select of list should use group
functions or should by included in group by clause.
***Interview questions***
1. What is SQL?
SQL transfer Structured Query Language are also called as SEQUEL.
2. List out sub language of SQL?
They are 5 sub languages DDL,DML,DRL/DQL,TCL,DCL .
3. What is different between char and varchar2?
Char is a fixed size and varchar2 is a not a fixed size.
4. What is projection?
Selecting specific columns is projection.
Page 20 of 108
5. How can we filter the rows in the table by use the Where, Group BY, Having,
Order By clause?
Select deptno, sum(sal) from emp where ename <> ‘KING’ Group By deptno
Having sum(sal) > 9000 Order By sum(sal) DESC;
6. What is column Alias?
Providing the duplicate to column Name. This is not a permanent.
7. Can we perform a arithmetic operation by using dual?
Select 10 + 20 Result from dual;
8. What is dual table?
Dual table is dummy table to calculate the some problems. This is one column
and one row. Specified to ‘X’
9. Write a query to display current date along with HH:MI:SS?
Select To_Char(sysdate,’DD-MON-YYYY HH:MI:SS’) from dual?
10.Write a query to see the current date?
Select sysdate from dual;
11.Which operator is used to accept the values from the user?
INSERT, UPDATE,CREATE and etc.
12.How can you see all the table which are in the data base?
Select * from TAB
13.Which command is used to remove the table from the data base?
Drop command is used to the table.
14.What is different between delete and truncate command?
Delete to the table and getting the roll back. Truncate is used not possible the
table roll back.
15.Which operator is used to retrieve the rows based on null values?
IS NULL
16.In how many ways we can rename all the rows from the table?
They are two ways Delete and Truncate
17.How can we create copy of a table?
Create table emp1 AS select * from emp;
Create table emp2 AS select * from emp where deptno = 30;
18.Write a query to display no.of rows in the table?
BY using count(*)
Select count(*) from emp;
19.What is different between count(*) and count(Expr)?
*is total table. Expr is only one column to count the table.
20.What is difference between group functions and scalar function?
Group functions will act on total table and scalar functions will act on one row.
Page 21 of 108
21.What is a use of Group By clause?
Group By clause will decided into several groups.
22.How can we filter the rows of Group By clause?
Having clause is used to filter the data.
23.Which clause is used to arrange the rows in the table?
Order By clause is used to arrange.
24.Which clause should be the last clause of the query?
Is order By caluse.
***Any operation performed on null will result to null values.
25.What is a TOAD?
Tool for Oracle Application Development.
*INTEGRITY CONSTRAINS:
Constrains are rules which are applied on tables.
Constrains helps in improving the accurency and quality of the data base.
They are five types of constrains.
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY or REFERENTIAL INTEGRITY CONSTRAINS
5. CHECK
Constrains can be created at two levels
a. Column level
b. Table level
Page 24 of 108
*Creating composite primary key constraint at table level:
Ex:
Create table student9(Surname varchar2(10),
Firstname varchar2(10),
Marks number(3),
PRIMARY KEY(Surname,Firstname));
Foreign key column name need not match with primary key column name or unique
column name. But the data type should match.
To establish relationship it is mandatory that the parent table should have primary key
constraint or at least unique constraints.
*On delete set null: When delete the row from parent table. The corresponding value
will be changed to null.
Page 27 of 108
Delete from school2 where sno = 102; //valid
One row from parent table is deleted.
Foreign key column value 102 is changed to null.
Note: Every constraint will have a constraint name in the format of SYS_Cn(where N is
number).
Page 29 of 108
Ex: SYS_c004525, SYS_c004526
*ALTER:
*Adding Constraints: Alter command is used to add a constraint to an Existing table.
Ex:
Create table Student10(sno number(3),
Sname varchar2(10),
Marks number(3));
*Dropping a constraint:
Alter command is used to drop a constraint to an existing table.
Ex:
Alter table student10 DROP Primary key;
Page 30 of 108
*Unique Constraint:
Ex:
Create table Student11(sno number(3),
Sname varchar2(10),
Marks number(3));
***JOINS: joins are used to retrieve the data from multiple tables.
Types of Joins:
1. EQUI_JOIN
2. NON EQUI_JOIN
3. SELF JOIN
4. OUTER JOIN
4.1 Right outer join
4.2 Left outer join
4.3 Full outer join
Note:
We need to mention join conditions in the where clause.
In EQUI_JOINS we along use to equal to operator in join condition.
Ex:
Selete empno, ename, sal, job, dname, loc
Page 31 of 108
from emp, dept
where emp.deptno = dept.deptno;
Note: we need to mention table name dot column(emp.deptno) name for the
common column to resolve the any table.
The common column can be retrieved from any of the table.
We can filter the data from the result of join.
Ex:
Select empno, ename, sal, emp.deptno, dname, loc
from emp, dept
where emp.deptno = dept.deptno AND sal > 2000;
To improve the performance of the join we need mention table name dot column
name for all the columns.
Ex:
Select emp.empno, emp.ename, emp.sal,emp.deptno, dept.dname, dept.loc
from emp,dept
where emp.deptno = dept.deptno AND sal > 2000;
*Table alias:
Table alias is an alternate name given to a table.
By using a table alias length of the table reduces and at the same time performance is
maintains.
Table alias are create in same clause can be used in select clause as well as where
clause.
Table alias is temporary once the query is executed the table alias are losed.
Ex:
Select E.Empno, E.Ename, E.sal, E.deptno, D.Dname, D.loc
from emp E, Dept D
where E.deptno = D.deptno;
*Join the multiple tables(3 tables):
Select * from Areas;
Page 32 of 108
City State
Newyork AP
Dallas Mh
Ex: Select E.empno, E.ename, E.sal,D.dname,A.state from emp E, dept D, Areas A
where E.deptno = D.deptno AND D.loc = A.city;
Note: To join ‘n’ tables we need n-1 conditions.
*NON EQUI JOIN: When we do not use NON EQUI JOIN to operator in the join
condition is NON EQUI JOIN.
Ex:
Select * from SALGRADE;
GRADE LOSAL HISAL
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999
*SELF JOIN: When a table is joining to it self it is called self join. In self joins we need to
create two table aliases for the same table.
*CARTESIAN PRODUCT:
When tables are joined without any join condition it is called Cartesian product. In the
result we get all possible combination.
Page 34 of 108
*SUPER KEY: Combination of columns which can be used unique key identify every
row is called as super key.
Table object
Column Attributes
Row Tuple/Record
*OUTER JOINS: It is extension of EQUI JOINS.
In outer joins we get match as well as non matching rows.
(+) This called as outer join operator.
*SET OPERATORS: Set operators are used to retrieve the data from multiple tables.
They are different types.
1. UNION:
Select * form student10;
Sno sname marks
101 Arun 40
102 Arun 50
103 Arun 69
2. UNION ALL:
Union All Syntax: (All rows)
Select sno from student 10
Union All // o/p sno: 101 102 103 103 104
Select sno from student 20;
3. INSERT SECT:
Insert Sect Syntax: (common rows)
Select sno from student 10
Insert Sect // o/p sno: 103
Select sno from student 20;
4. MINUS:
Select sno from student 10
Page 36 of 108
Minus //o/p sno: 101,102
Select sno from student 20;
INTERVIES QUESTIONS
1. What is need for Integrity constraint?
Constrains are rules which are applied on tables.
Page 37 of 108
When primary key is applied on multiple columns it is called composite primary
key. Composite primary key can be applied only at table level.
10.Can we establish a parent & child relationship without having constraint in the
parent table?
On
11.Con you explain change related to foreign key on delete cascade on delete set
null constraint?
Foreign key column in the child table will only accept values which are their the
primary key column or unique column.
We can delete the rows from the parent table and the corresponding child table
rows deleted automatically.
When we delete row from parent table. The corresponding values will be
changed to null.
13.How can you know constraint name and combination type apply for a table?
By using user constraint.
14.Is their any different when a constraint is a created at column level or table
level?
No difference.
Page 38 of 108
17.What is the need for join?
To retrieve the multiple tables
*Commit: This command is used to make changes permanent to the data base.
Syntax: COMMIT;
Ex:
Create table student(sno number(3),
Name varchar2(10),
Marks number(3));
Page 39 of 108
Select * from student300;
Create table student1(sno number(3),
Name varchar2(10),
Marks number(3));
COMMIT;
*ROLLBACK: The rollback will undo the changes which are not permanent.
Syntax:
ROLLBACK;
Ex:
Create table student2(sno number(3),
Name varchar2(10),
Marks number(3));
COMMIT;
Page 40 of 108
*SAVE POINT: Save points are logical marking given for series of transaction.
Instead of complete rollback we can rollback to a save point.
Syntax: SAVEPOINT<SAVEPOINT_NAME>;
Ex:
Create table student3(sno number(3),
Name varchar2(10),
Marks number(3));
SAVEPOINT A;
ROLLBACK;
SAVEPOINT P;
Page 41 of 108
SAVEPOINT Q;
Note: All the save points are lost when the DB is permanent.
*Object Privileges: These Privileges are given by one user to another user.
Page 42 of 108
KIRAN
DBA
AJAY
COMMIT;
Examples of object privileges are select, insert, update, drop and alter etc.
**REVOKE: This command is used to get back the privileges which are granted.
Syntax: REVOKE<privilege_name><privilege_name> ON <table_name> from
<user_name>;
Ex:
KIRAN> REVOKE select, insert ON student from AJAY;
KIRAN> REVOKE ALL ON student from AJAY_ANIL;
Page 43 of 108
KIRAN> REVOKE select ON student from public;
**ROWID:
ROWID is pseudo column which contains hexadecimal values.
ROWID value indicates the address where the row is store in the database.
ROWID values are permanent.
Ex:
Select ROWID, empno, ename, sal, deptno from emp;
Delete from student where Rownum IN(1,2,3); // this is not right query
Select Rowid, sno, sname, marks from student;
Select min(Rowid) from student;
Select min(Rowid) from student group by sno;
*Subqueries:
Subqueries are used to get the result based on unknown values. They are different
type.
1. Single Row subquery
2. Multiple Row subquery
3. Multiple column subquery
4. Co-related subquery
5. Scalar subquery
6. Inline view
*Single Row Subquery:
When subquery returns one row (1 value). It is called Single RowSubquery.
Ex: write a query to display details are having salary > ‘ALLENS’ sal ?
Select * from emp where sal > (select sal from emp where ename = ‘ALLEN’);
o/p: 1600
Note:
Subqueries should always place in the inside.
Subqueries are executed first and then parent query is executed by using the result of
sub query.
Level Two query:
Select * from emp where job = (select job from emp where ename = ‘ALLEN’)
AND job = (select job from emp where ename = ‘BLAKE’);
*ANY: Select * from emp where sal > ANY(select sal from emp
where deptno = 30);
Select * from emp where sal < Any(select sal from emp where deptno = 30);
Ex:
Page 47 of 108
Select * from emp where(job,sal) IN(select job, sal from emp where deptno = 30);
Note: In the o/p we get the rows when both the values are matching.
Delete some valuesu:
Select * from student;
Select min(rowid) from student group by sno;
Select max(rowid) from student group by sno;
*write a query to display the row from emp table who is having the highest salary?
Select * from emp where sal = (select max(sal) from emp);
*write a query to display all the rows who are having salary grater than AVG salary of
emp table?
Select * from emp where sal >(select AVG(sal) from emp);
*Co-RELATED SUBQUERY:
When subquery is executed in relation to parent query, it is called co-related
subquery.
*write a query to display all the rows who are having salary grater than AVG salary his
department?
Select AVG(sal) from emp;
Select * from emp where sal > (select AVG(sal) from emp group by deptno); //invalid
Select * from emp where sal > (select AVG(sal) from emp where deptno = 10);
Page 48 of 108
***Select * from emp e
where sal > (select AVG(sal) from emp where deptno = e.deptno);
*SCALAR subquery: when we use subquery in the select clause. It is called as Scalar
subquery.
*write a query to display following output?
Deptno Dname loc sumsal
10 Accounting New York 8750
20 Research Dallas 10875
30 Sales Chicago 9400
40 Operations Boston ------
Select deptno, dname, loc, (Select sum(sal) from emp where deptno = d.deptno)
Sum_sal from dept d;
*INLINE VIEW:
When a subquery is used in from clause. It is called INLINE view.
*write a query to display details of employees who are having top 5 salaries?
Page 49 of 108
Select * from emp where Rownum <=5 ORDER BY sal desc;
Select * from (select * from emp ORDER BY sal desc) where rownum <=5;
clause subcaluse
select yes scalar
from yes inline
where yes
group by no
having yes
order by no
INTERVIEW QUESTIONS
1. What are pseudo columns?
It is rownum is a pseudo column which starts with one and increment by 1.
*views: view is a logical representation of data from one or more then one table.
They are different types
Simple views
Complex views
Read only views
With check option views
Materialized views
*Single views: when view is created using one base table it is called as Single view.
Sybtax:
Create view<view_name> as <select STMT>;
Ex:
Create view v1 as select empno, ename, sal from emp;
View does not contain any data.
View does not consume memory location.
When we write select statement on view, we get the data from the table.
Page 51 of 108
Empno Ename Sal
7369 Smith 800
7499 Allen 1600
------- ------ ------
------- ------ ------
Tables which are used for creating the view are called as above tables.
Select * from TAB; will gives list of all the tables and view which are the data base
tables.
Ex:
Create view emp_V10 AS select empno, ename, sal, deptno, from emp
where deptno = 10;
Create view emp_V10 AS select empno, ename, sal, deptno, from emp
where deptno = 20;
Create view emp_V10 AS select empno, ename, sal, deptno, from emp
where deptno = 30;
View_name Text
Test_v6 select empno, ename, sal, deptno
from emp where deptno = 30;
In user_view from the database we get list of all the view and corresponding select
statement used for the view.
Select view_name, Text from user_views;
*Complex view:
When a view is created using multiple base tables it is called Complex view.
Ex:
Create view Test_v7
As select e.empno, e.ename, e.sal, e.deptno,
d.dname, d.loc from emp e, dept d where e.deptno = d.deptno;
A view is called as complex view when we use arithmetic operations an functions are
group by clauses.
Create view Test_v10
As select deptno, sum(sal) sum_sal from emp group by deptno;
*materialized view:
Materialized views will help improving the performance of select statement on view.
To create materialized view, the based table should have primary key.
Changes to base table will not reflect on materialized view.
Materialized view or previously called as snap short.
Ex:
Create view Test_V14
As select empno, ename, sal, deptno from emp;
Syntax:
Create MATERIALIZED view <VIEW_NAME> AS <select STMT>;
Ex:
Create materialized view MV1
As select empno, ename, sal, deptno from emp;
Select * from MV1;
DBMS_SNAPSHOT-PACKAGE NAME
REFRESH ---procedures
***INDEX:
Index is an object which is used to improve the performance of select statements.
1.Simple Index:
When index is created on one column it is called as simple index.
Syntax:
CREATE INDEX <INDEX_NAME> ON <TABLE_NAME> (COL_NAME);
Ex:
Create index IDX1 on emp(sal);
Index should be created on columns which we regularly use in the where clause.
When a index is created a separate structure is created with first column is ROWID and
second column as indexed column.
The Rows in the index will be arranged in the ascending order of indexed column.
IDX1
ROWID SAL
800
950
1100
Using algorithm is identifies the back of ROWID’s
1250
Using which rows are displayed.
1600
5000
Page 56 of 108
The above index IDX2 is used only when both the columns are used in the where
clause.
Disadvantages of index:
Index will consume memory.
The performance of DML command will be decreased.
*Unique Index:
If the indexed column contains unique value it is called unique index.
A unique index is automatically created. When we create a table with primary key
constraint or unique constraint.
*Non-unique index:
If an index column contains duplicated values they are called as non-unique index.
Ex:
Create index IDX1 on emp(sal);
*Query to see list of all the indexes along with column name.
Select index_name, table_name, column_name from user_ind_columns;
Desc user_indexes
Desc user_ind_columns
Page 57 of 108
Select * from emp where lower(ename) = ‘king’;
To drop on index:
Ex:
Drop INDEX IDX1;
Page 58 of 108
Syntax: create synonym <Synonym_name> for <Table_name);
Ex:
Create synonym E1 for emp;
Synonym helps in reducing the length of the query.
Synonym is used instead of table names for all the commands.
Ex:
Select * from E1;
To drop a synonym:
SQL> DROP SYNONYM E1;
Object of Oracle:
1. Table
2. View
3. Index
4. Sequences
5. Synonyms
Synonym Objects of PL/SQL:
1. PROCEDURE
2. FUNCTION
3. PACKAGE
4. TRIGGER
Page 59 of 108
*2nd Second Normal form (2NF): A database is in 2NF if it satisfies following rules.
Rule1: Database should be in 1NF.
Rule2: There should be no partial dependency.
Partial dependency
In the above table S Name (non key attribute) is depending on supplier ID (part of
primary key). Hence these exists partial dependency. We can eliminate partial
dependency by dividing the table into two different tables. The following tables are
satisfying 2NF rules.
*3rd Normal form (3NF): A database is in 3NF if it satisfies the following rules.
Rule1: Database should be in 2nd NF.
Rule2: These should be no transitive dependency.
Transitive dependency: When a non key attribute is dependent on another non key
attribute then these Exists transitive dependency the following table is not satisfying
3rd NF rules. PART NO MANFNAME MANFADDRESS
Primary key 1000 TOYOTA PARK AVENUE
1001 MISTUBUSHI LOS ANGELS
1002 TOYOTA PARK AVENUE
Page 60 of 108
In the above table manufacture address (non key) is dependent of manufacture name
(non key). Hence there exists transitive dependency.
We can eliminate transitive dependencies by dividing the table into two different
tables.
Primary key
12.What is sequence?
Sequence is an object is used to generate numbers.
16.What is a synonym?
It is an alternate name given to an object.
Page 62 of 108
Rule 3: Systematic treatment of null values:
The DBMS must allow each field to remain null (or empty) specifically, It must support
a representation of missing information ad inapplicable information.
Page 64 of 108
***PL/SQL***
It is extension of SQL the following or advantages of PL/SQL.
1. We can use programming features like if statement loops etc.
2. PL/SQL helps in reducing network traffic.
3. We can have user defined error massages by using concept of exception
handling.
4. We can perform related actions by using concept of Triggers.
5. We can save the source code permanently for repeated execution.
PL/SQL Block:
A PL/SQL programs called as PL/SQL block.
PL/SQL Block:
DECLARE
-------------------------
------------------------- --DECLARE SECTION --OPTIONAL
-------------------------
BEGIN
-------------------------
------------------------- --EXECUTABLE SECTION --MANDATORY
-------------------------
EXCEPTION
-------------------------
------------------------- --EXCEPTION SECTION --OPTIONAL
-------------------------
END;
/
*Declare: This section is used to declare local variables, cursors, Exceptions and etc.
This section is optional.
*Executable Section: This section contains lines of code which is used to complete
table. It is mandatory.
*Exception Section: This section contains lines of code which will be executed only
when exception is raised. This section is optional.
Page 65 of 108
*Simplest PL/SQL Block:
Begin
--------
--------
--------
END;
/
Begin
DBMS_OUTPUT.PUT_LINE( ‘HELLO WORLD’ );
END;
/
Note: To get the output of the program server output environment variable should be
on.
Command: SET SERVEROUTPUT ON
DBMS_OUTPUT is name of the PACKAGE
.PUT_LINE is name of the PROCEDURE
‘/’ Slash is used to submit the program in DBS.
*Write PL/SQL block which will calculate some of two numbers and display the
output?
DECLARE
A number(2);
B number(2);
C number(3);
BEGIN
A := 10;
B := 20;
C := A + B;
DBMS_OUTPUT.PUT_LINE(C);
Page 66 of 108
DBMS_OUTPUT.PUT_LINE( ‘sum of two numbers’ || C);
END;
/
o/p: 30
o/p: sum of two numbers 30
PL/SQL procedure successfully completed.
*Write a PL/SQL block which accepts two numbers from the user and display the sum?
DECLARE
A number(2);
B number(2);
C number(3);
BEGIN
A := &A; or A := &malli;
B := &B; or B := &iNetSlov
C := A + B;
DBMS_OUTPUT.PUT_LINE( ‘sum of the two numbers’ || C);
END;
/
*Write a PL/SQL block which accepts employee number and increment is salary by
1000?
DECLARE
A number(4);
A := &Empno;
Update emp set sal = sal + 1000 where Empno = A;
END;
/
*Write a PL/SQL block which empno and delete that row from the emp table?
DECLARE
A number(4);
BEGIN
A := &Empno;
Delete from emp where Empno = A;
END;
/
1. Simple:
Declare
A number(2) := 1;
Begin
DBMS_OUTPUT.PUT_LINE( ‘welcome’ );
LOOP
DBMS_OUTPUT.PUT_LINE( ‘HELLO1’ );
DBMS_OUTPUT.PUT_LINE( ‘HELLO2’ );
Exit when A = 4;
A := A + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE( ‘THANK YOU’ );
END;
/
2. While:
Declare
A number(2) :=1;
Begin
DBMS_OUTPUT.PUT_LINE( ‘WELCOME’ );
While A <=4 loop
DBMS_OUTPUT.PUT_LINE( ‘HELLO1’ );
DBMS_OUTPUT.PUT_LINE( ‘HELLO2’ );
A := A + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE( ‘THANK YOU’ );
END;
/
Page 69 of 108
3. FOR LOOP:
Declare
A number;
Begin
DBMS_OUTPUT.PUT_LINE( ‘WELCOME’ );
FOR A IN 1 .. 4 LOOP
DBMS_OUTPUT.PUT_LINE( ‘HELLO1’ );
DBMS_OUTPUT.PUT_LINE( ‘HELLO2’ );
END LOOP;
DBMS_OUTPUT.PUT_LINE( ‘THANK YOU’ );
END;
/
*Write a program which accepts empno to display ename, job and salary?
Declare
L_empno emp.empno % type;
L_ename emp.ename % type;
L_job emp.job % type;
L_salary emp.salary % type;
Begin
L_empno := &empno;
Select ename, job, salary into L_ename, L_job, L_salary from emp where empno =
L_empno;
DBMS_OUTPUT.PUT_LINE( ‘L_ename’ );
DBMS_OUTPUT.PUT_LINE( ‘L_job’ );
DBMS_OUTPUT.PUT_LINE( ‘L_salary’ );
(or)
Note:
When a select statement does not return any row program will terminate abnormally.
When select statement returns more then one row, program will terminate
abnormally.
*EXCEPTIONS:
Runtime Errors are called as Exceptions. They are three types of Exceptions.
1. ORACLE Predefined Exception
2. ORACLE Non Predefined Exception
3. USER Defined Exception
*NO_DATA_FOUND: This Exception is raised when select statement does not return
any Row.
Ex:
Declare
L_sal emp.sal%type;
Begin
DBMS_OUTPUT.PUT_LINE( ‘WELCOME’ );
Select sal INTO L_sal from emp where empno = &empno;
DBMS_OUTPUT.PUT_LINE(L_sal);
Page 72 of 108
DBMS_OUTPUT.PUT_LINE( ‘THANK YOU’ );
EXCEPTION
when NO_DATA_FOUND then
DBMS_OUTPUT.PUT_LINE( ‘INVALID EMPNO’);
END;
/
*TOO_MANY_ROWS:
This Exception is raised when select statement more then one row.
Ex:
Declare
L_sal emp.sal%type;
Begin
DBMS_OUTPUT.PUT_LINE( ‘WELCOME’ );
Select sal INTO L_sal from emp where deptno = 30;
DBMS_OUTPUT.PUT_LINE(L_sal);
DBMS_OUTPUT.PUT_LINE( ‘THANK YOU’ );
EXCEPTION
when TOO_MANY_ROWS then
DBMS_OUTPUT.PUT_LINE( ‘MORE THEN ONE ROW RETURNED’);
END;
/
*ZERO_DIVIDE:
Ex:
Declare
A Number;
Begin
A := 5/0;
Exception
when ZERO_DIVIDE then
DBMS_OUTPUT.PUT_LINE( ‘DO NOT DIVIDE BY 0’ );
END;
/
Note:
This Exception is raised when we try to divided by zero.
Page 73 of 108
*VALUE_ERROR: This Exception is raised when there is miss match with the value and
data type of local variable or size of local variables.
Ex 1:
Declare
L_sal emp.sal%type;
Begin
DBMS_OUTPUT.PUT_LINE( ‘WELCOME’ );
Select ename INTO L_sal from emp where empno = 7521;
DBMS_OUTPUT.PUT_LINE(L_sal);
DBMS_OUTPUT.PUT_LINE( ‘THANK YOU’ );
EXCEPTION
when VALUE_ERROR then
DBMS_OUTPUT.PUT_LINE( ‘please check the local variables’);
END;
/
Ex 2:
Declare
A number(3);
Begin
A := 1234;
Exception
when VALUE_ERROR then
DBMS_OUTPUT.PUT_LINE( ‘PLEASE CHECK THE LOCAL VARIABLES’ );
END;
/
The above program works on an assumption the table student for if having a primary
key SNO column with value 104.
*WHEN OTHERS:
When others are a universal Exception angular this can catch all the Exceptions.
Declare
L_sal number(4);
A number;
Begin
DBMS_OUTPUT.PUT_LINE( ‘Welcome’ );
Select sal INTO L_SAL from emp where deptno = &deptno;
DBMS_OUTPUT.PUT_LINE(‘The sal is ….’||L_sal);
A :=10/0;
DBMS_OUTPUT.PUT_LINE( ‘Thank you’ );
Exception
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( ‘please check the code’ );
END;
/
These error reporting functions are used in when others clause to identified the
exception which is raised.
Page 75 of 108
1. SQLCODE: It returns ERRORCODE
2. SQLERRM: It returns Exception number and Exception message.
Declare
L_sal number(4);
A number;
Begin
DBMS_OUTPUT.PUT_LINE( ‘Welcome’ );
Select sal INTO L_SAL from emp where deptno = &deptno;
DBMS_OUTPUT.PUT_LINE(‘The sal is ….’||L_sal);
A :=15/0;
DBMS_OUTPUT.PUT_LINE( ‘Thank you’ );
Exception
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( ‘please check the code’ );
DBMS_OUTPUT.PUT_LINE(SQLCODE);
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
/
*NESTED BLOCK:
Declare
A number := 10;
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO1’);
Declare
B number := 20;
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO2’);
DBMS_OUTPUT.PUT_LINE(B);
DBMS_OUTPUT.PUT_LINE(A);
END;
DBMS_OUTPUT.PUT_LINE(‘HELLO3’);
DBMS_OUTPUT.PUT_LINE(B); --ERROR
END;
/
Page 76 of 108
Note: outer block variables can be accessed in nested block nested block variables can
not be accessed in outer block.
*EXCEPTION PROPAGATION:
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO1’);
L_SAL EMP.SAL%TYPE;
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO2’);
Select sal INTO L_SAL from emp where empno = 1111;
DBMS_OUTPUT.PUT_LINE(‘HELLO3’);
END;
DBMS_OUTPUT.PUT_LINE(‘HELLO4’);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘HELLO5’);
END;
/
Page 77 of 108
This exception is raised when we delete row from a parent table. If the corresponding
value existing the child table.
Declare
MY_EX1 Exception; --step1
PRAGMA EXCEPTION_INIT(MY_EX1, -2292); --step2
Begin
DBMS_OUTPUT.PUT_LINE(‘Welcome’);
Select from student where eno = 102;
EXCEPTION
WHEN MY_EX1 THEN --step3
DBMS_OUTPUT.PUT_LINE(‘do not delete pargma table’);
END;
/
Declare
MY_EX1 EXCEPTION; --Step1
L_SAL EMP.SAL%TYPE;
Begin
DBMS_OUTPUT.PUT_LINE(‘welcome’);
Select SAL INTO L_SAL from emp where empno = &empno;
IF L_SAL > 2000 THEN
RAISE MY_EX1; --Step2
ENDIF;
DBMS_OUTPUT.PUT_LINE(‘The sal is … ‘||L_sal);
DBMS_OUTPUT.PUT_LINE(‘Thank you’);
EXCEPTION
Page 78 of 108
WHEN MY_EX1 THEN --Step3
DBMS_OUTPUT.PUT_LINE(‘Sal is two high’);
END;
/
Note: When others should be the last handler of the exception section other wise we
get a compiler ERROR.
Declare
L_sal emp.sal%TYPE;
Begin
DBMS_OUTPUT.PUT_LINE(‘Welcome’);
Insert INTO dept values (08,’arun’,70);
Select sal INTO L_sal from emp where empno = 7698;
IF L_sal > 2000 THEN
RAISE_APPLICATION_ERROR(-20150, ‘SAL IS TOO HIGH’);
END IF;
DBMS_OUTPUT.PUT_LINE(‘THE SAL IS…’||L_SAL);
END;
/
*CURSORS: CURSOR is a memory location which is used to run SQL commands. They
are two types of cursors.
1. Implicit cursor
2. Explicit cursor
*Implicit cursor: All the activities related to cursors like opening the cursor, processing
the cursor and closing the cursor are done automatically. Hence these cursor are
called as implicit cursor.
Page 79 of 108
1. SQL%ISOPEN
2. SQL%FOUND
3. SQL%NOTFOUND
4. SQL%ROWCOUNT
*USING SQL%ROWCOUNT:
Begin
Update emp set sal = 2000 where deptno =30;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||’ROWS UPDATED’);
END;
/
*SQL%ISOPEN
Begin
Update emp set sal = 1000 where empno = 7654;
Page 80 of 108
IF SQL%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE(‘CURSOR IS OPEN’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘CURSOR IS CLOSED’);
END IF;
END;
/
Note: By the time we check whether cursor is open or not it is already closed by the
oracle engine. Hence it is always returns false.
*write a PL/SQL block which accepts deptno and display all the employee names of the
department?
Declare
L_ename emp.ename%TYPE;
Begin
Select ename into L_ename from emp where deptno = &deptno;
DBMS_OUTPUT.PUT_LINE(L_ename); --ERROR
END;
/
Act should be done by the developer. Hence this cursor is called explicit cursors.
We should use explicit cursors to run a select statement. Which returns more then one
row?
Steps to use explicit cursors:
Step 1: declare the cursor
Step 2: open the cursor
Step 3: fetch data from cursor to local variables
Step 4: close the cursor
Syntax:
Step 1: declare the cursor
CURSOR <CURSOR_NAME> IS <SELECT STMT>;
Page 81 of 108
Step 2: open the cursor
OPEN <CURSOR_NAME>;
*%ISOPEN: It is a Boolean attribute which returns true when cursor is open. Returns
false when cursor is closed.
*write a program to display all the employee names working in dept number 10?
Declare
Cursor c1
IS select ename from emp where deptno = 10;
L_ename emp.ename%TYPE;
Begin
open c1
loop
FETCH c1 into L_ename;
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(L_ename);
END LOOP;
Page 82 of 108
CLOSE c1;
END;
/
CLIENT DATABASE
ENAME C1
*write a PL/SQL block to display all the department names and locations from the
department table?
Declare
Cursor c1
IS select dname, loc from dept;
L_dname dept.dname%TYPE;
L_loc dapt.loc%TYPE;
Begin
Open c1;
Loop
Fetch c1 into L_dname, L_loc;
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(L_dname||L_loc);
END loop;
Close c1;
END;
/
*write a program to display employee names, job, salary who are working in a
department number 30?
Page 83 of 108
Declare
CURSOR c1
IS select ename,job,salary from emp where deptno = 30;
A c1%ROWTYPE;
Begin
OPEN c1;
LOOP
FETCH c1 INTO A;
EXIT WHEN c1 %NOTFOUND
DBMS_OUTPUT.PUT_LINE(A.ename||’…’||A.job||’…’||A.salary);
END LOOP;
END;
/
Declare
CURSOR c1
IS select ename, job, salary from emp where deptno = 30;
Begin
FOR A IN c1 LOOP
DBMS_OUTPUT.PUT_LINE(A.ename||’…’||A.job||’…’||A.salary);
END LOOP;
END;
/
*Write a program to display the entire employee numbers their names and location?
Declare
CURSOR c1
IS select E.empno, E.ename, D.loc from emp E, Dept D where E.Deptno = D.Deptno;
Begin
Page 84 of 108
FOR A IN c1 LOOP
DBMS_OUTPUT.PUT_LINE(A.empno||’…’||A.ename||’…’||A.loc);
END LOOP;
END;
/
*Write a program it will calculate AVG marks from the entire student table?
Declare
CURSOR c1
IS select * from student;
L_AVG number(5.2);
Begin
FOR A IN c1 LOOP
L_AVG := (A.sub1 + A.sub2 + A.sub3)/3;
DBMS_OUTPUT.PUT_LINE(‘AVERAGE OF’ ||A.sno||’IS’||L_AVG);
END LOOP;
END;
/
*Using%ISOPEN attribute:
Declare
Cursor c1
IS select empno, ename from emp where deptno = 20;
L_empno emp.empno%TYPE;
L_ename emp.ename%TYPE;
Begin
open c1;
IF c1%ISOPEN then
DBMS_OUTPUT.PUT_LINE(‘cursor is open’);
Else
DBMS_OUTPUT.PUT_LINE(‘cursor is closed’);
Page 85 of 108
END IF;
END;
/
*Parameterized cursor: A cursor which accepts a parameter from the user is called as
parameterized cursor. Active dataset changes dynamically basing on the value passed
to the cursor.
Ex:
Declare
Cursor c1(A number)
IS select empno, ename from emp where deptno = A;
L_empno emp.empno%TYPE;
L_ename emp.ename%TYPE;
Begin
open c1(&deptno);
Loop
FETCH c1 INTO L_empno,L_ename;
Exit when c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(L_empno||’…..’||L_ename);
Page 86 of 108
END Loop;
close c1;
END;
/
Ex:
create or replace procedure p1
IS
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO’);
END;
/
1. InParameter:
InParameter’s are used to accept values from the user.
Ex: create a procedure which accepts two numbers and display the num?
*Create or replace procedure ADD_NUM(A IN number, B IN number)
IS
C number;
Page 87 of 108
Begin
C := A + B;
DBMS_OUTPUT.PUT_LINE(‘The sum is…’||C);
END;
/
*create a procedure which accepts employee number and increment salary by 1000?
Create or replace procedure INC_SAL (A IN number)
IS
Begin
Update emp set sal = sal + 1000 where empno = A;
END;
/
*create a procedure which accepts deptno and display the name and location?
Create or replace procedure display_details(L_deptno IN dept.deptno%TYPE)
IS
L_Dname dept.Dname%TYPE;
L_loc dept.loc%TYPE;
Begin
Select Dname, loc INTO L_Dname, L_loc from dept where deptno = L_Deptno;
DBMS_OUTPUT.PUT_LINE(‘L_Dname||’….’||L_loc);
Exception
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘IN value NO’);
END;
/
Page 88 of 108
Query to see all the list of procedures:
Select object_NAME from user_objects where object_TYPE = ‘PROCEDURE’;
Spool command:
This command is used to extract the character which we can see in SQL*PLUSE
environment to a text file.
Ex:
SQL>spool c:\sample\abc.txt
SQL>select * from emp;
SQL>select * from dept;
SQL>spool off
**Out parameters: out parameters are used to return the value to the user.
Ex:
Create a procedure which accepts two numbers and return the sum?
Create or replace procedure ret_sum
(A IN number,B IN number, C OUT number)
IS
Begin
C := A + B;
END;
/
*Functions:
A function is a named PL/SQL block which must and should return a value.
Syntax: create or replace function<FUNCTION_NAME>(VAR1 datatype, var2 datatype,
…….,varn datatype);
Return datatype
IS
Begin
-------
-------
-------
Page 91 of 108
END;
/
Ex: Create a function which accepts two numbers and returns the sum?
Create or replace function ADD_NUM_FUN(A number, B number)
Return number
IS
C number;
Begin
C := A + B;
Return C;
END;
/
*create a function which accepts salary and returns tax value. Tax value is 10% of
salary?
Create or replace function CAL_TAX(L_sal emp.sal%TYPE)
Return number
IS
Page 92 of 108
Begin
L_TAX = L_sal * 10/100;
Return L_TAX;
END;
/
Ex: select empno, ename, sal, cal_tax(sal) from emp;
Differences between procedure and functions:
Procedures Functions
1. Procedures need not return any 1. Must and should return only one
value can return one or more than value.
one value.
*Packages:
A package is collection of logically related sub programs.
Creation of package invokes two steps.
Step 1: creating package specification.
Step 2: creating package body.
Example of PKB:
Create or replace package body test_PKG1
IS
Procedure p1
IS
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO WORLD’);
END;
Procedure display_sal(L_empno IN number)
IS
L_sal emp.sal%TYPE;
Begin
Select sal into L_sal from emp where empno = L_empno;
DBMS_OUTPUT.PUT_LINE(‘The sal is…’||L_sal);
END;
Procedure display_details(L_deptno IN emp.deptno%TYPE)
IS
Cursor c1
IS select ename from emp where deptno = L_deptno;
Begin
For emp_rec IN c1 LOOP
DBMS_OUTPUT.PUT_LINE(emp_rec.ename);
END LOOP;
END;
Function cal_tax(L_sal emp.sal%TYPE)
Return number
IS
Begin
Return(L_sal*10/100);
END;
END test_PKG1;
/
To invoke a sub program which is inside the package, we need to mention package
name subprogram name.
Ex: Exec test_PKG1.p1
Page 94 of 108
Select test_PKG1.cal_tax(2500) from dual;
Note:
Packages can not be parameterized.
Packages can not be nested.
Packages help in modularization.
Packages help in overloading subprograms.
PKB:
Create or replace package body test_pkg2
IS
Procedure p1(A number)
IS
B number;
Begin
B := A * A;
DBMS_OUTPUT.PUT_LINE(‘The square is … ‘||B);
END;
Procedure p1(A number, B number)
IS
C number;
Begin
C := A + B;
DBMS_OUTPUT.PUT_LINE(‘The sum is … ‘||C);
END;
END test_pkg2;
/
***Triggers:
A Trigger is a PL/SQL block which is executed automatically basing on an event.
Triggering events are inserted, update, delete.
Trigger timing can be before, after, instead of
Syntax:
Create or replace trigger <TRIGGER_NAME><TIMMING><EVENT> ON <OBJECT_NAME>
Begin
-----------
-----------
-----------
END;
/
Ex:
create or replace trigger trg1
after insert on dept
begin
DBMS_OUTPUT.PUT_LINE(‘hello’);
END;
/
Trigger created
SQL> insert into dept values(65,’Admin’,’HYD’);
Ex:
Page 96 of 108
Create or replace trigger trg1
After insert or update or delete on dept
Begin
If inserting then
DBMS_OUTPUT.PUT_LINE(‘thank you for inserting’);
ElsIf updating then
DBMS_OUTPUT.PUT_LINE(‘thank you for updating’);
Else
DBMS_OUTPUT.PUT_LINE(‘thank you for deleting’);
End If;
END;
/
Create or replace trigger TRG5 before insert on emp for each row
Begin
If :new.sal>5000 then
Raise_application_error(-20150,’sal cannot be more than 5000’);
END IF;
END;
/
Page 98 of 108
Ex: insert into emp(empno, ename, sal, deptno) values(444,’BBB’,7500,10);
Output: ERROR ORA-20150 :sal cannot be more than 5000
*create a trigger which will accept insert command only for deptno 10?
Create or replace trigger trg3 before insert on emp for each row
Begin
IF :new.deptno<>10 then
Raise_application_error(-20150,’deptno should be only 10’);
END IF;
END;
/
Page 99 of 108
*Instead of triggers:
Instead of triggers are created on complex view.
By using instead of trigger we can execute insert command on a complex view
Ex:
COMPLEX VIEW
Create view vv1
As select e.empno, e.ename, e.sal, e.deptno, d.deptno, d.loc from emp e1 dept d
where e.deptno = d.deptno;
View created
Select * from vv1;
*Abstract datatypes:
Abstract data types are consists of one or more subtypes. Rather than being
constrained to the standard oracle data types of number, date and varchar2 data
types can more accurately describe your data.
Ex:
SQL>create type address_ty5 as object
(street varchar(20),
city varchar2(10),
state char(10),
pin number);
/
Type created
*Nested table:
Nested table is a collection of rows, represented as a column with in the main table.
For each record with in the main table, the nested table may contain multiple rows. In
one sense, it’s a way of storing a one-to-many relationship with in one table.
Table created
Name Type
Ename Varchar2(20);
Details Emp_nt
Desg Varchar2(20)
Dname Varchar2(20)
Doj Date
*VARRAYS: varrays can also be used to create one-to-many relationship with in the
table.
*creating varray:
Ex: create type dependent_brithdate_t5 as varray(10) of date;
Begin
Execute immediate ‘Truncate table emp;
END;
/
*BULK COLLECT:
Bulk collect feature helps in improving the performance of explicit cursor programs.
Fetch statement can fetch all the rows from the cursor to the programs local variable
at once thus helps in improving the performance.
Ex:
Declare
Type string_array is varray(20) of varchar2(20);
L_ename string_array;
Cursor c1
Is select ename from emp;
Begin
Open c1;
Fetch c1 bulk collect into L_ename;
Close c1;
For i in L_ename.first .. L_ename.last loop
DBMS_OUTPUT.PUT_LINE(L_ename(i));
END loop;
END;
/
*REF CURSOR:
A ref cursor is basically a data type.
A variable created based on such a data type is generally called a cursor variable.
SQL * loader:
SQL loader is a tool which is use to load the data from the file to the table.
This tool requires control file(.Ctrl).
Control file contains all the information about source and destination.
It is developer responsibility to create a control file.
Page 104 of 108
Syntax to create control file:
LOAD data
Infile ‘<Data filepath>’
Insert into table <Table_name> fields Terminated by ‘,’
(col1, col2,…., clon)
Ex:
LOAD data
INFILE ‘E:\sunil\student_data.txt’
Insert into table sutdent50 fields terminated by ‘,’
(sno, sname, marks)
*Autonomous transactions:
In general a commit command used in a PL/SQL block will act globally and make all the
changes permanent.
To restrict commit command to a specific program we need to make the PL/SQL block
autonomous.
We can create autonomous PL/SQL block by using ‘PRAGMA AUTONOMOUS_TRAN
SACTION’ in the declare section.
PRAGMA autonomous_transaction is a compiler directive.
Ex:
Create table student20(sno number(3), sname varchar2(10), marks number(3));
Insert into student20 values(101,’Arun’,40)
Insert into student20 values(102,’Arun’,40)
Declare
Pragma autonomus_transactions;
Begin
Insert into student20 values(103,’Arun’,40);
Insert into student20 values(104,’Arun’,40);
commit;
END;
/
*Insert values in lobs: To insert values in the bfile, the function bfilename is used.
It takes the os path of the directory and the name of the file.
Ex:
Insert into airbus_desc5 values(‘ABO1’, bfilename(‘E:\sunil’,’esert.jpg’),
‘the description the plane is as follows’);
*Locks:
As oracle is a multiuser environment there is always a chance that multiple users will
perform DML operators on some table parallel in such case the data becomes
inconsistent.
To maintain the consistency of data base a user can lock the table.
Select for update command is used for locking a table.
Ex:
Ajit> select * from student for update;
Table is locked by Ajit
ASHWIN> update Ajit.student set marks = 95 where sno = 101;
Client will be in waiting state.
Locks are released when a user executes commit command.
*Row level: when where clause in select for update command is evaluating to one
row, row level lock is applied.
Ex: select * from student where sno =101 for update;
*Page level: when where clause in select for update command is evaluating to
multiple rows, page level lock is applied.
Ex: Select * from emp where deptno = 20 for update;
*Table level:
When where clause is not used in select for update, table level lock is applied.
Ex: select * from emp for update;