ORACLE NOTES - For - FULL STACK
ORACLE NOTES - For - FULL STACK
ORACLE NOTES - For - FULL STACK
Oracle Trainer
ORACLE
DATA
Data is defined as a collection of raw facts.
Information
Processed data is known as information.
DATA BASE
⮚ It is the collection of information of all objects in the business, stored at one place.
Conclusion:
⮚ An RDBMS is a software that is useful to automate Business transactions.
⮚ By using this language, we can write English like statements, called QUERIES.
SQL COMMANDS
SQL commands are divided into 5 categories. They are
DDL—Data Definition Language
CREATE ALTER DROP TRUNCATE RENAME
DML—Data Manipulation Language
INSERT UPDATE DELETE
DCL—Data Control Language
GRANT REVOKE
TCL—Transaction Control Language
COMMIT ROLLBACK SAVEPOINT
DRL/DQL—Data Retrieval Language/Data Query Language
SELECT
NOTE
We will write Queries/Programs in any client application like SQL * PLUS, SQL DEVELOPER,
TOAD. . etc.
SQL*PLUS
⮚ SQL * PLUS is the default client application software.
NOTE
Before connecting to database, we should create user account in your database as follows.
● Connect as DBA
DATA MODEL
Data model is a graphical diagram. The data model name is E-R ( Entity-Relationship )
Model. It contains OBJECTS, PROPERTIES and RELATIONS. In E-R model, any object is
represented with RECTANGLE, each property is represented with Ellipse and relation
between objects represented with Rhombus.
(
<colname-1> DATATYPE (size),
<colname-2> DATATYPE (size),
);
Ex:
write a query to create a table emps with columns empid, ename, salary, desg, joindt?
Create table emps
(
Empid number(4),
Ename varchar2(20),
Salary number(5),
Desg varchar2(20),
Joindt date
);
I) Character data
It contains alphabets, digits and symbols.
CHAR (size)
DINESH PV
Oracle Trainer
It is useful to store fixed length character values. By default the size is 1 character, and max
size is 2000 chars or bytes.
Ex: empid char(5)
e0001
e0002
e0003
Ex: gender CHAR
M
F
M
F
VARCHAR2(size)
It is useful to store variable length character values. No default size. we must specify size
and max size is 4000 chars /bytes.
Ex: emp_names varchar2(20)
kiran
ajay
krishna prasad
NCHAR(size)
To store fixed length UNICODE character values. Max. size is 2000 chars/bytes.
NVARCHAR2(size)
To store variable length UNICODE character values. Max size is 4000 bytes or chars.
LONG
It is similar to VARCHAR2() datatype and its maximum size is 2 GB[Giga Bytes].
NOTE:
Only for one column, LONG data type is allowed in a table.
It is used to store INTEGER values. "Precesion" represents max length of the value.
Ex:
empsal number(6)
20
0
-12780
105000
NUMBER(Precesion, [Scale])
It is useful to store integers as well as decimal values. "Scale" represents max length of
decimal part.
Note:
The max value for precision is 38, Max value of scale is 10 power -28
Ex: prod_price number(7,2)
123.1
-99999.99
125
-0.75
0
DATE data types
DATE
It is used to store date values. Oracle has predefined date format as follows.
DD-MON-YY
DD - Digits of date
MON - First 3 chars of month name
YY - Last 2 digits of year
Binary Data types
These data types are useful to store binary data like images, thumb impressions, logos,
video and audio files RAW(), LONG RAW(), BLOB
RAW(size)
Used to store binary data like images, thumb impressions, logos and so on.
DINESH PV
Oracle Trainer
Gender char
);
NULL VALUE:
A missed value is known as null value. Null value is not equal to zero or space or other null
values.
HOW TO DISPLAY TABLE STRUCTURE?
A table structure contains column names, data types and sizes.
EX: describe empinfo;
or
desc emp_info;
HOW TO DISPLAY LIST OF TABLE NAMES?
EX: SELECT * FROM TAB;
Q: What is the meaning of tab?
Tab means table space, which contains list of tables created under current schema.
DATA RETRIEVAL LANGUAGE/ DATA QUERY LANGUAGE
SELECT
It will display a copy of requested data from a table or view.
syntax:
SELECT col1, col2,...., coln or * FROM table_name;
NOTE: In above syntax , * represents all columns from table.
DINESH PV
Oracle Trainer
Assignments:
i) Create a table Item_dtls ( Electronics )
ii) Create a table Sales_dtls
iii) create a table manufacturers
iv) Try to insert at least 10 records in the above tables
v) Try to insert at least 2 records with null values
DISTINCT CLAUSE:
It will display unique values from a column or unique records from a table.
syntax:
select DISTINCT colname1, colname2,...(or) DISTINCT * from <TBL>;
Ex: display list of different designitions?
select distinct(desg) " list of jobs" from emp_info;
output
salesman
developer
clerk
DINESH PV
Oracle Trainer
admin
ORDER BY Clause:
we can display the column data or table data in ascending / descending or sorting [ a to z] /
reverse sorting [z-a] data.
Syntax:
select col1, col2, .... / * FROM TBL order by col1, col2,......[DESC] ;
Note:
By default table data is in random order.
Ex: Display employee names in alphabetical(sorting) order?
select ename from emp ORDER BY ename;
sample output:
ENAME
ADAMS
ALLEN
BLAKE
CLARK
FORD ...
Ex: Display employee names in reverse order?
select ename from emp ORDER BY ename DESC;
sample output:
ENAME
WARD
TURNER
SMITH
SCOTT
MILLER ...
Ex: display ename,sal, desg on the order of salary?
select ename, sal,job from emp order by sal;
OR
DINESH PV
Oracle Trainer
OPERATORS
Arithmetic operators
RELATIONAL OPERATORS
SPECIAL OPERATORS
Relation Negation Operators
Logical Operators
Arithmetic Operators:
+ - * /
These operators are useful to perform arithmetic calculations on user's data and table data.
DUAL table:
DUAL is a system defined table. It has one column and one record. It is useful to calculate
any constant expression.
Ex: select 200+300 from dual;
500
Ex: select (90000*10)/100 "10% of 90000" from dual;
output
9000
Ex: select 2000+(0.10*5000)-300 " After calculation" from dual;
2200
arithmetic Calculations On Table data
Ex: Display emp salaries and 2% of salary as TA?
DINESH PV
Oracle Trainer
RELATIONAL OPERATORS
These Operators are useful to compare values. we can write conditions on the columns. The
result of a condition is a BOOLEAN VALUE, that is either TRUE or FALSE.
< > = <= >=
WHERE clause
In any SQL Query [ SELECT, UPDATE and DELETE ], we will write conditions under this clause.
syntax:
select cl1, cl2,......,cl-n / * from <TBL> where <condition>;
IQ: How to filter table data?
Ans: By using conditions under WHERE clause.
IQ: what is the result of a condition?
Ans: Boolean value , that is TRUE or FALSE.
Ex: display salaries below 12000?
select sal from emp_info where sal < 12000;
Ex: Display employee details who is getting above 12000 salary?
select * from empinfo where sal> 12000;
Ex: display the details of accounting dept?
select * from dept where dname='ACCOUNTING';
Ex: display the details of managers?
select * from emp where job='MANAGER';
SPECIAL OPERATORS
BETWEEN NOT BETWEEN
IN NOT IN
IS NULL IS NOT NULL
DINESH PV
Oracle Trainer
BETWEEN
By using this operator, we will write a condition based on range of values.
Syntax
select cl1, cl2,......,cl-n / * from <TBL>
where <ColumnName> BETWEEN <First_val> AND <Last_val>;
Ex: Get emp details with minimum salary 20000 and maximum salary 35000?
Select * from emps where salary between 20000 and 35000;
IN
By using this operator, we can write a condition based on list of values in a column.
syntax:
select cl1, cl2,......,cl_n / * from <TBL> where <ColumnName> IN(val1, val2, ...);
Ex: Display manager and clerk details?
Select * from emps where job in (‘MANAGER’,’CLERK’);
IS NULL
It used to check the column value is null or not. If column value is null then it returns TRUE,
otherwise FALSE.
syntax
select cl1, cl2,......,cl-n / * from <TBL> where <ColumnName> IS NULL;
Ex: Get employee details if the emp not having salary ?
Select * from emps where salary is null;
LIKE
It is useful to search for pattern in the column values. Pattern is a char or group of chars or
symbols or digits.
LIKE operator is using 2 symbols to represent characters.
_ (underscore) It represent anyone char/digit/symbol.
% It represents zero or any number of chars.
syntax
select cl1, cl2,......,cl-n / * from <TBL>
DINESH PV
Oracle Trainer
Ex: Display employee names begins with "J" and ends with "S"?
select ename from emp where ename like'J%S';
NEGATION OPERATORS
!= (or) <> (NOT EQUAL TO)
NOT BETWEEN
NOT IN
IS NOT NULL
NOT LIKE
Ex: Display all emps details except SALESMAN?
select * from emp where job<>'SALESMAN';
Ex: Display employee details not joined in the last year?
select * from emp where hiredate NOT BETWEEN '01-jan-14' and '31-dec-14';
LOGICAL OPERATORS
These operators are useful to write Multiple conditions under where clause.
AND
It returns true, if all conditions are true in a record.
OR
It returns true if any one condition is true in a record.
syntax
DINESH PV
Oracle Trainer
DELETE
It is used to delete the records from the table. By default, it will delete all records.
Note:
To delete specific records, then we must specify conditions along with delete command.
syntax
DELETE FROM <table_name> where <cond>;
Ex: delete all customer details?
delete from cust_dtls;
DINESH PV
Oracle Trainer
COMMIT
It is used to make transactions as permanent. Once committed, we cannot cancel these
transactions.
ROLLBACK
It is used to cancel user transactions. By default ROLLBACK cancel all transactions
in the current login session.
SAVEPOINT
It is useful as a check point while cancelling transactions with ROLLBACK.
SAVEPOINT <name>;
Example:
create table cust
(
cid char(3),
cname varchar2(20)
);
insert into cust values('c00','Sanju');
insert into cust values('c01','Manoj');
select * from cust;
rollback;
select * from cust;
insert into cust values('c00','Sanju');
insert into cust values('c01','Manoj');
commit;
DINESH PV
Oracle Trainer
DBA
syn:
GRANT <Privillage list> On <DBName.username.objectName> TO <DBName.username>;
REVOKE
By Using this command, DBA can get back or cancel permissions.
DINESH PV
Oracle Trainer
PREVILLAGE LIST
Previllages are known as permissions.
SELECT
INSERT
UPDATE
DELETE
CREATE [TABLE/VIEW/INDEX/SYNONYM]
ALTER [TABLE/VIEW/SEQUENCE]
DROP [TABLE/VIEW/INDEX/SEQUENCE/SYNONYM]
DDL COMMANDS
CREATE ALTER DROP
RENAME TRUNCATE
ALTER
It is used to change the structure of the table by doing the following
DINESH PV
Oracle Trainer
ADDING COLUMNS
Alter Table <table_name> ADD
( <col_1> datatype(size), <col_2> datatype(size), ----- ----- );
Syntax
Alter Table <table_name>
RENAME COLUMN <oldname> TO <newname>;
Ex: alter table emp
rename column ename to empnames;
DINESH PV
Oracle Trainer
DROP
we can delete any data base object by using this command.
syn:
drop <object_type> <object_name>;
we can delete the table as follows:
drop table <tablename>;
Ex: drop table emp;
DINESH PV
Oracle Trainer
Constraints are known as set of rules / business rules which will be defined/changed at DDL
level. Constraints, force the data base to accept only valid values in to the tables.
Constraints ensure the user to fetch valid, complete and accurate data, from database.
For Example
Table creation without constraints:
CREATE TABLE STUD
(
RNO NUMBER(2),
SNAME VARCHAR2(10),
COURSE VARCHAR2(10),
FEE NUMBER(5),
MOBILE NUMBER(10)
);
DINESH PV
Oracle Trainer
Note:
In the above table the marked values are invalid according to business of client.
How to avoid / restrict invalid values into business database?
🡪BY defining constraints on the tables before data to be inserted into the table.
KEY CONSTRAINTS
These constraints will verify individual values.
These are divided into 3 types.
UNIQUE
It doesn't allow duplicates, but allow null values.
Ex: phone numbers, mailid, etc...
email varchar2(30) UNIQUE,
aadhar number(12) UNIQUE,
NOT NULL
It doesn't allow null values, but allow duplicate values.
Ex: empNames, CityNames, .....
sname varchar2(20) NOT NULL,
PRIMARY KEY
It doesn't allow duplicates and doesn't allow null values. Generally Primary key is used to
identify any record Uniquely. Only one primary key constraint is allowed per a table.
Ex:
bank account numbers
empid
regnumbers... etc.
data:-
DOMAIN constraint:
By using Domain constraint, we can define conditions on the columns. Before inserting a
value, the value is verified based on condition. We can write conditions by using any
relational operator.
The name of domain constraint is CHECK.
syntax:
col datatype(size) <key constraint>,
check (col <condition>)
Ex:
rno number(3) primary key,
check (rno between 1 and 999)
Syntax:-1
<col> datatype(size) CONSTRAINT <Friendly name> <Actual_name>
Ex:
rno number(3) constraint pk_rno_student primary key
Ex:
rno number(3),
constraint pk_rno_student primary key(rno)
Note:
The second example is not suitable for NOT NULL constraint.
constraint ck_fee_stud_dtls
check(fee between 12000 and 20000),
constraint ck_moblen_stud_dtls
check(length(mobile)=10),
constraint ck_mob_valid_stud_dtls
check(mobile like'7%' or mobile like'8%' or mobile like'9%' or
mobile like'6%')
);
Ex:
select constraint_name,constraint_type from user_constraints
where table_name='STUD';
Note
By using above tables we are unable fetch the complete data of an object like, department
name of any employee, number of emps in dept and etc.
To answer such kind of requirements we have to maintain the data in 2 methods.
1) Maintaining all the information in one table. [ DENORMALIZATION ]
2) Maintaining data in different tables and implement relationships
between the tables. [ NORMALIZATION]
DENORMALIZATION
Maintaining all necessary information in one big table is known as Denormalized method.
DINESH PV
Oracle Trainer
Advant
age:
Communication gap is eliminated.
DRAWBACKS
🡪 data duplicacy
🡪 Occupy more disk space
🡪 Data retrieval time is very long
Note:
To decrease above drawbacks we can apply normalization process
as follows.
NORMALIZATION
The Process of Dividing big table in to sub tables, until Max. data duplicacy is reduced is
known as normalization process.
DINESH PV
Oracle Trainer
IInd NF
Eleminate duplicate records and defining primary keys in the above tables
DINESH PV
Oracle Trainer
Adv:
🡪No communication gap.
🡪Duplicacy is reduced
🡪Occupy less disk space.
🡪Data search time is reduced
REFERENCES
It is used to define a FK column in the child table, by using parent table PK column.
Defining FK with default name
Syntax:
<col_name> datatype(size) REFERENCES <parent_table>(PK_column)
Note
Generally, PK and FK column names and datatypes are similar.
SYNTAX:
FK with user Defined name:-
constraint <friendly_name> FOREIGN KEY(ChildTablecolumn name)
REFERENCES <Parent_Table>(PK_colname )
Examples:
consider the tables comp_dtls and prod_dtls.
And we are maintaining set of products from each company.
Based on this create the tables and maintain relation between
the tables?
Ex: create comp_dtls as parent table
Ex: create prod_dtls as child table
Managing constraints
ADDING / DELETING / CHANGE CONSTRAINTS on existing table:-
ADD
CONSTRAINT pk_rno_student PRIMARY KEY(rno);
Ex:
check student fee between 1000 and 5000?
ALTER TABLE student
add
constraint ck_fee_student
check(fee between 1000 and 5000);
DEFAULT
We can define a default value into a column. That is if we did not insert any value into
default column, then the default value will be inserted. Default column also accept NULL
values and other values.
🡪To stop other values , define CHECK constraint
🡪To stop NULL values, define NOT NULL constraint
DINESH PV
Oracle Trainer
SYNTAX
col datatype(size) DEFAULT 'value'
Example
Create table customers
(
cid number(2),
cname varchar2(10),
city varchar2(10) DEFAULT ‘DELHI’
);
Insert into customers(cid,cname) values(11,’krish’);
Insert into customers(cid,cname) values(22,’raj’);
Insert into customers(cid,cname) values(33,’john’);
SEQUENCES
Sequence is a database object. It is useful to generate sequential integers.
In real time projects, we can define sequences to generate primary key column values.
syntax:
******
DINESH PV
Oracle Trainer
CURRVAL
It will access current value of sequence.
Ex:
select <seq_name>.currval from dual;
NEXTVAL
It will access next value from sequence.
Ex:
select <seq_name>.nextval from dual;
SEQUENCE USES
i) we can use sequence values while inserting records.
ii) we can use sequence values in updating a column.
Ex:
create sequence custid
start with 11111;
Ex:
select custid.nextval from dual;
11111
Ex:
select custid.nextval from dual;
DINESH PV
Oracle Trainer
11112
Ex:
select custid.currval from dual;
11112
Ex:
create a table custinfo with columns CID,CNAME,CITY.
Insert customer names and cid values genereted by
sequence "custid".City value by default "HYDERABAD".
1)
create sequence custid
start with 11111;
2)
create table custinfo
(
cid number(6) DEFAULT custid.nextval,
cname varchar2(20) constraint nn_cname_custinfo NOT NULL,
city VARCHAR2(10) DEFAULT 'HYDERABAD'
);
SET OPERATORS
We can display combined data from multiple tables.
The operators are
UNION ALL
UNION
INTERSECT
DINESH PV
Oracle Trainer
MINUS
UNION
It will display combined data from multiple tables without duplicates.
SYNTAX
SELECT . . . . . . FROM T1
UNION
SELECT . . . . . FROM T2;
UNION ALL
It will display combined data from multiple tables with duplicates.
SYNTAX
SELECT . . . . . . FROM T1
UNION ALL
SELECT . . . . . FROM T2;
INTERSECT
It will display common data from multiple tables. (From multiple Select stmts)
SYNTAX
SELECT . . . . . . FROM T1
INTERSECT
SELECT . . . . . FROM T2
----- ;
MINUS
It will display values from first selection by eliminating values which are repeating
in second selection.
SYNTAX
DINESH PV
Oracle Trainer
SELECT . . . . . FROM T1
MINUS
SELECT . . . . . FROM T2
MINUS
-----;
Sample Tables:
Examples:
--female customers from br1 and b3
--
select cname,mobile from cust_br1
intersect
DINESH PV
Oracle Trainer
--DISPLAY COMMON CUSTOMER NAMES AND MOBILE NUMBERS FROM ALL BRANCHES
Note:
PSEUDO COLUMNS
These are virtual columns associated with any table.
ROWNUM
ROWID
1) ROWNUM
It maintains serial number for each record in the output.
By using this we can select "n" number of records from the begining
of the table.
DINESH PV
Oracle Trainer
2) ROWID
It maintains physical address of each record.
By using this value, oracle engine identify any record
in the database server.
JOINS
CROSS JOIN
It will display all possible combinations from multiple tables.
Note:
Cross join is also known as Join / Cartesian Product.
Total No. of Combs= No. of recs in TBL1 X No. of recs in TBL2 X . . . .
syntax
select col1, col2,...,coln / *
from table1, table2, ....
where <cond>
Ex:
Get all emp details and dept details?
Select * from emp, dept;
Or
Select e.*, d.* from emp e, dept d;
Note:
In the above example, e and d are known as alias names for the tables emp and dept
respectively.
EQUI JOIN
It will display only matched data from multiple tables based on join condition.
A condition is known as join condition if it is specified between primary key of one table and
foreign key of other table.
syntax
select col1, col2,...,coln / *
from table1, table2, table3, ....
where t1.col=t2.col
and
DINESH PV
Oracle Trainer
t2.col=t3.col .......;
Ex:
Get employee details and corresponding dept details?
Select e.*, d.*
From emp e, dept d where e.deptno=d.deptno;
INNER JOIN
It will display only matched data from multiple tables like Equi join.
In the inner join query, table names are separated with INNER JOIN key word.
And we should write join condition under ON clause.
Syntax
select . . . .
from tb1 INNER JOIN tb2
ON tb1.col=tb2.col;
Ex: Consider the tables PRODUCT and COMPANY with common column cmpid
1) Display all product details along with company name?
Select p.*, c.cmpname from product p inner join company c on p.cmpid=c.cmpid;
SELF JOIN
A table which is joined itself is known as self join. In this join, we will consider 2 alias names
for one physical table. Based alias names , we can write join condition.
We can display output from 2nd alias table only.
synta:
select alias2.*
from TBL alias1, TBL alias2
where
alias-1.col='value'
and
alias1.col=alias2.col;
DINESH PV
Oracle Trainer
employee
ename city
kiran mumbai
hari hyd
madhu hyd
smith delhi
scott mumbai
allen hyd
soumya mumbai
john delhi
Ex:
Get emp details from a city where "ALLEN" is living?
Ex:
display emplyoee details who is living in a city
where "john" is living?
select e2.ename,e2.city
from employee e1 inner join employee e2
on e1.ename='JOHN' and e1.city=e2.city;
OUTER JOINS
Outer joins will display all the data from one table and only matched data from other table.
DINESH PV
Oracle Trainer
In any outer join query, we should write outer join type between table names
and join condition should be specified under ON clause.
syntax
select col1, col2, col..... / *
from TBL_1 [Left Join / Right Join / Full Join] TBL_2
ON tbl1.col=tbl2.col
SUB QUERIES
A query with in the other query is known as Nested query. Sub query is one type of Nested
Query.
"A select query under where clause of other select query is known as Sub Query."
Sub queries are preferable to display output from one table and having an input value from
the other table.
To write a subquery we need at least one common column.
syntax
select ..... from table...
where <cond> ( select ..... from table...where <cond> ( select.......).....);
Hints
i) Based on output table we can write outer query.
ii) Based on input value table we can write sub query.
NOTE: Execution process of a subquery is from innermost query
to the outermost.
outer query<---o/p<--Inner query<---o/p<---Inner query
TYPES OF SUBQUERIES:
1) Single row subquery
DINESH PV
Oracle Trainer
A sub query, which select a value from single record. In this case in between the outer and
inner queries we can use = operator.
syntax
select . . . . from . . . where col =(select . . . . from . . . where. . . );
2) Multi row sub query
A sub query, which select values from multiple records. In this case in between the outer
and inner queries we can use IN operator.
Syntax
select . . . . from . . . where col IN(select . . . . from . . . where. . . );
VIEWS
View is a database object like table. View contains logical copy of table data.
View is created based on table or other view. It can be created based on frequently using
data. It improves the performance at data access level. View maintains data dynamically,
means if table data is changed then the changes reflected into view dynamically.
View Types
1) Simple or Updateable view
DINESH PV
Oracle Trainer
NOTE: By default we don't have permission to create views. That is assigned by DBA.
i) connect as DBA
ii) grant create view to dinesh;
iii)connect as dinesh;
iv) Now try to create a view.
Example:
How to get create view permission?
i)
ex: connect as dba in oracle 11g
sql> conn system/manager
Ex: grant create view to manju;
grant succeeded
1) simple view
This view is created based on single table data. we can execute select, insert, update and
delete commands on this view. That's why simple view is also known as Updateable view.
syntax
create view <view_name>
AS
select ...... from table_name ;
Ex:
write a query to create a view which contains managers information
DINESH PV
Oracle Trainer
2) Composite view:
This view is created based on more than one table data. It doesn't allow insert operation on
it. It is also known as read only view or Join view.
Advantage:
It will reduce no. of times writing join queries again and again.
syntax:
create view <vw_name>
AS
select ........
from table1, table2,...
where <join-cond>;
EX:
Write a query to create a view to maintain product information along with company details?
Create view vw_prod_company
As
Select * from product p, company c
Where p.cmpid=c.cmpid;
INDEXES
DINESH PV
Oracle Trainer
Index is a database object like table. It is useful to search data as much as fast
based on conditions.
Index has 2 parts.
They are
🡪 data part
🡪 address part.
Data part contains ordered values of a column.
Address part contains physical address of each record.
Index occupy physical disk space.
TYPES OF INDEXES
1) simple index:
This index is created on single column of a table.
syntax
create index <idx_name> on table_name(colname);
Ex:
create index , to search data based on salary column?
create index idx_sal on emp(sal);
2) composite index
This index is created on multiple columns of a table.
Syntax
create index <idx_name> on table_name(col1 ,col2,....);
Ex:
create an index on the columns cost,comp_code in the table prod_dtls?
create index idx_prod_search
on prod_dtls(cost,comp_code);
Oracle is providing a set of predefined functions. Each function is useful to perform one task.
These functions are divided into 2 CATEGORES.
1) GROUP / AGGREGATE FUNCTIONS:
It will execute on set of values and display single output value. We can also say, it can
execute on column level / field level.
Note: Group functions cannot applicable on user's data.
Ex: sum(), avg(), min(), max(), count(), count(*)
2) SCALAR / SINGLE ROW FUNCTIONS:
It will execute on set of values and display a set of output values. We can also say, it is be
executed on Record level / row level.
Ex: lower(), length(), trim()
iii) MAX(colname)
It will Display highest value from given column.
Ex: Display highest salary among all salesman?
select max( sal ) from emp where job='SALESMAN';
iv) MIN(colname)
DINESH PV
Oracle Trainer
v) COUNT(colname)
It will Display count of NOT NULL values from given column.
Ex: find how many number of emps getting commission?
select count(empno) from emp where comm is not null;
vi) COUNT(*)
It will Display number of records from given table.
Ex: display number of transactions on current day?
select count(*) from trans_dtls where trans_date=sysdate;
GROUP BY clause:
Internally, it will make logical groups based on each distinct value from given column. On
each logical group, aggregate functions are executed individually.
HINT:
IN any select query, if there exist column names and aggregate functions then we must use
GROUP BY clause.
🡪"The column names from select list, should be present after GROUP BY clause."
Note: Don't use GROUP BY and DISTINCT clauses together in a query.
SYNTAX:
select colname, colname,..., aggregate1, aggregate2,.....
from table WHERE <cond> GROUP BY <col1>,<col2>,...HAVING aggfunc1,..., ORDER
BY col1,col2,.....;
Ex: find out number of emps working under each dept ?
select deptno, count(*) " No. of emps" from emp GROUP BY deptno;
output:
deptno No. of emps
DINESH PV
Oracle Trainer
30 6
20 7
10 5
HAVING clause:
we can specify conditions on aggregate functions. By this, group by output is filtered.
Note: Without group by clause, don't use HAVING clause.
Ex: find out number of emps working under each dept on order of deptno if a dept
contains at least 10 emps?
select deptno, count(*) " No. of emps"
from emp
GROUP BY deptno
HAVING count(*)>=10
order by deptno;
3)POWER(m,n)
It will display "m" to the power of "n"th value.
Ex: select power(5,4) from dual;
625
DINESH PV
Oracle Trainer
Example:
create table stud_marks
(
sid number(3),
telugu number(3),
english number(3),
hindi number(3),
physics number(3),
social number(3),
chemistry number(3)
);
insert into stud_marks values
(111,'98','87','90','95','78','80');
insert into stud_marks values
(222,'80','87','91','96','78','80');
insert into stud_marks values
(333,'60','79','56','78','78','89');
insert into stud_marks values
(444,'61','89','67','71','92','54');
insert into stud_marks values
(555,'51','62','79','79','60','82');
DINESH PV
Oracle Trainer
STRING/CHAR FUNCTIONS
1) ASCII('ch')
[ American Standard code For Information Interchange ]
It will display ascii value of given character.
Ex: select ascii('a') "a",ascii('A') "A" ,ascii('@') "@" from dual;
2) LENGTH('str'/col)
It is used to count number of characters in the given value.
Ex: Get employee names and length of each employee name?
select ename, length(ename) " length" from emp;
Ex: select length('oracle') from dual;
3) LOWER('str'/col)
It will display the given chars or column values in lower case.
Ex: Display employee names in lower case?
select ename,lower(ename) from emp;
Ex: select lower('HAI') from dual;
hai
4) UPPER('str'/col)
It will display given character value or column values in upper case.
Ex: select upper (pname) from products;
5) INITCAP('str'/col) [ Initial Capital ]
It will display the given char value or column values with beginning char as capital.
Ex: select initcap('welcome to oracle') from dual;
Welcome To Oracle
6) SUBSTR('str'/col,m,n) ( substring )
It is used to display a substring from the given string. "m" is indicating from which charater,
"n" is indicting number of characters.
DINESH PV
Oracle Trainer
If "n" is omitted then, it display from "m th" char till the end of string. If "m" value is
negative, then substring is taken from end of string.
ex: select substr('secured',3,4) from dual;
cure
7) INSTR('str'/col,'ch',m,n) [ instring]
It is used to display "n th" occurance of given char ,either from begin or end of given string.
Here "m" value is either +1( default ), or -1
+1 Means search the character from the beginning of string.
-1 Means search the character position from the end of string.
Here "n" is nth occurance of given character.
8) TRANSLATE('str'/col, 'sourcechars','targetchars')
It will display given value by translating source chars with corresponding target chars.
Ex: select translate('welcome','em','xy') from dual;
wxlcoyx
Ex: select translate('welcome','em','x') from dual;
wxlcox
[ char "m" eleminated from output]
10) TRIM('str'/col)
Display given string by deleting spaces before and after the string.
Ex:
select trim(' welcome to ') " trim", initcap('oracle') from dual;
welcome to Oracle
11) LTRIM('str'/col) [ Left Trim ]
Display given string by removing blank spaces from left side of string only.
Ex: select ltrim(' welcome to '), initcap('oracle') from dual;
welcome to Oracle
12) RTRIM('str'/col) [right trim ]
Display given string by removing blank spaces from right side of string only.
Ex: select rtrim(' welcome to '), initcap('oracle') from dual;
output: welcome to Oracle
TRIM KEYWORDS
These keywords are useful to delete given character, either from left side or from right side
or from both sides.
13) LEADING 'ch' FROM 'str'/col
Display given string by removing similar char from left side.
Ex: select trim(leading 'x' from 'xxx2489xxxx') from dual;
2489xxxx
14) TRAILING 'ch' FROM 'str'/col
Display given string by removing similar char from right side.
Ex: select trim(trailing 'x' from 'xxx2489xxxx') from dual;
xxx2489
15) BOTH 'ch' FROM 'str'/col
Display given string by removing similar char from both sides.
Ex: select trim(both 'x' from 'xxx2489xxxx') from dual;
2489
DINESH PV
Oracle Trainer
DATE FUNCTIONS
Date functions are executing on date type data.
1) SYSDATE
It will display system date. We can also add or subtract "n" number of days to the sysdate.
Ex: select sysdate from dual;
DD-MON-YY
26-DEC-21
Ex: find out the date of 10 days back?
select sysdate-10 from dual;
Ex: find out date value after 41 days?
select sysdate+41 from dual;
2) LOCALTIMESTAMP
DINESH PV
Oracle Trainer
It will display current date value along with time component as follows.
DD-MON-YY HH.MM.SS.ns [AM/PM]
Ex: select localtimestamp from dual;
26-DEC-21 12.20.52.694000 PM
4) TO_DATE('Date_Value','Value Format')
It will convert any non-Oracle date value into oracle's date format and display the result. It
accepts any char format of date(dd/mm/yy or dd-mm-yyyy or dd:mon:yyyy or yyyy-mm-dd)
and converts it into oracle's default date format [ DD-MON-YY].
Ex: select to_date('02/12/2019','dd/mm/yyyy') from dual;
Ex: select to_date('2020:01:21','yyyy:mm:dd') from dual;
5) ADD_MONTHS(d,n)
It will display resultant date value after adding/subtracting "n" number of months to the
given date.
"d" for date value.
"n" for number of months.
Ex: get date value after six months from today?
select add_months(sysdate,6) from dual;
Ex: get date value before 10 months from the date "22/may/2014"?
select add_months(to_date('22/may/2014','dd/mon/yyyy'),-10) from dual;
6) MONTHS_BETWEEN(d1,d2)
We can find out number of months between d1 and d2 dates. If first date is lessthan second
date, then result is in negative.
Ex: select months_between(sysdate,'21-may-18') from dual;
DINESH PV
Oracle Trainer
7)LAST_DAY(d)
It will display last date value of month in the given date.
Ex: select last_day(sysdate) from dual;
31-JAN-20
8)NEXT_DAY(date,'dayname')
It will display date value of given day after given date.
Ex: select next_day(sysdate,'saturday') from dual;
Ex: select next_day(sysdate,'monday') from dual;
1) TO_NUMBER(char_value_with_digits)
It will convert the given character values into number type.
Here the character value should contain sequence of digits.
Ex: salary varchar2(10)
---------- ------------
$1200
$11005
$107069.12
create table empinfo
(
eid number(3),
sal varchar2(10)
);
insert into empinfo values(111,'$1200');
insert into empinfo values(222,'$3000');
insert into empinfo values(333,'$900');
insert into empinfo values(444,'$1900');
insert into empinfo values(555,'$3000');
insert into empinfo values(666,'$14000');
Ex: select sum(to_number(substr(sal,2))) totalsal from empsal;
Ex:
select ename,sal,to_char(sal,'00,00,000.00') from emp order by sal;
3) TO_CHAR(date,[char format])
It is useful to convert given data value into character format.
YY Print "
yyyy Print complete year number
YEAR Year number can be spelled.
ANALYTICAL FUNCTIONS
RANK()
It will generate non sequential rank numbers based on result of window clause.
syntax
select rank() over(window clause) from table;
DENSE_RANK()
It will generate sequential rank numbers based on result of window clause.
Syntax
select col1, col2, dense_rank() OVER(window clause) from table;
Ex:
Display ename, salary and rank() and dense ranks() based on highest salary to least salary?
select ename,sal,rank() over(order by sal desc) rank,
dense_rank() over(order by sal desc) drank
from emp;
NVL(colname,value)
It will verify the given column value is null or not. If column value is null, then given value is
substituted. Here column data type and given value data types should be similar.
Ex:
select sal,comm,(sal+nvl(comm,0)) total_sal from emp;
NVL2(col,'val1','val2')
It will verify given column value is null or not. If column value is not null then " value1 " is
substituted. If column value is null then, " value2 " is substituted. In this function, value1 and
value2 should be with same data type.
Ex:
DINESH PV
Oracle Trainer
PL/SQL
PROCEDURAL LANGUAGE / SQL
PL/SQL is a Procedural Language developed by Oracle is an extension of Oracle SQL having
the functionalities of functions, control structures, and triggers.
How to define PLSQL?
PLSQL is a collection of User defined objects like Programs, procedures, Functions, Triggers,
Types, Packages and so on.
PL/SQL objects are divided into 2 categories.
They are
i) Programs / Anonymous Blocks
These objects not saved in the database. These program's logic is included in the User
Interface application development.
ii) Sub Programs
These objects permanently saved in the database server.
EX: Procedures and Functions
ANONYMOUS BLOCK:
STRUCTURE
DECLARE
<declaration stmts >;
BEGIN
<Assignment stmt>;
<Output stmts>;
<Data processing stmts>;
EXCEPTION
DINESH PV
Oracle Trainer
DECLARE block
It contains declaration statements to declare variables. Variable is a name. Variables are
useful to store values temporarily. So these variables get memory space from the database
engine based on their datatype and size.
syntax
varname DATATYPE(size);
Ex: v_eno int;
v_name varchar2(20);
BEGIN block
It is also known as Execution block. It contains 3 types of statements.
🡪Assignment statements
🡪OutPut statements
🡪Data Processing statements
Assignment statements
we can store values into the declared variables by using either assignment operator := or
SELECT query with INTO keyword.
Syntax
BY USING ASSIGNMENT OPERATOR
var := value / expression / Function_calling stmt;
Ex: v_eno := 7654;
Syntax
By Using SELECT Query with INTO keyword
DINESH PV
Oracle Trainer
EXCEPTION Block
It contains error handling statements to handle runtime errors.
END;
It is indicating end of a program.
NOTE: By default, any program or procedure should not display output. To display output,
execute following statement.
SET SERVEROUTPUT ON;
This is valid for current session.
DINESH PV
Oracle Trainer
/
Ex: write a program to display addition , average, max and min of 3000 and 5000?
DECLARE
X INT;
Y INT:=5000;
S INT;
A NUMBER(7,2);
MX INT;
MN INT;
BEGIN
X:=3000;
S:=X+Y;
A:=S/2;
SELECT GREATEST(X,Y) INTO MX FROM DUAL;
SELECT LEAST(X,Y) INTO MN FROM DUAL;
DBMS_OUTPUT.PUT_LINE(' SUM=');
DBMS_OUTPUT.PUT_LINE(S);
DBMS_OUTPUT.PUT_LINE('AVERAGE=');
DBMS_OUTPUT.PUT_LINE(A);
DBMS_OUTPUT.PUT_LINE('HIGHER VALUE=');
DBMS_OUTPUT.PUT_LINE(MX);
DBMS_OUTPUT.PUT_LINE('Least VALUE=');
DBMS_OUTPUT.PUT_LINE(MN);
END;
/
DINESH PV
Oracle Trainer
Types of programs: 2
1) Static program:
It will not accept input values, at run time.
2) Dynamic program:
In this case the program can accept runtime input values. we can make a program as
Dynamic Program by using "&" (Substitution Operator).
Syntax
Varname := '&varname';
Ex: As per above syntax, at runtime it will prompt for variable value as follows.
Enter value for varname: <value>
STATIC PROGRAMS:
declare
veno int:=7654;
vname varchar2(20);
vsal number(5);
vjob varchar2(20);
vhiredate date;
vcomm number(4);
vdeptno number(3);
BEGIN
select ename,sal,job,hiredate,comm,deptno
INTO
vname,vsal,vjob,vhiredate,vcomm,vdeptno
DINESH PV
Oracle Trainer
from emp
where empno=veno;
dbms_output.put_line(' Info of 7654');
dbms_output.put_line('---------------');
dbms_output.put_line(vname);
dbms_output.put_line(vsal);
dbms_output.put_line(vjob);
dbms_output.put_line(vhiredate);
dbms_output.put_line(vcomm);
dbms_output.put_line(vdeptno);
END;
Ex:
Write a program to display employee name, salary, designation, joindate, commission, and
deptno of empid 7654?
declare
veno int:=7654;
vname varchar2(20);
vsal number(5);
vjob varchar2(20);
vhiredate date;
vcomm number(4);
vdeptno number(3);
BEGIN
select ename,sal,job,hiredate,comm,deptno INTO
vname,vsal,vjob,vhiredate,vcomm,vdeptno
from emp
where empno=veno;
dbms_output.put_line
(' Info of Emp id: 7654');
dbms_output.put_line
DINESH PV
Oracle Trainer
('=============================================');
dbms_output.put_line('Name of emp: '||vname);
dbms_output.put_line('Salary of emp: '||vsal);
dbms_output.put_line('Designition of emp: '||vjob);
dbms_output.put_line('Join date of emp: '||vhiredate);
dbms_output.put_line('Commission of emp: '||vcomm);
dbms_output.put_line('Deptno of emp: '||vdeptno);
dbms_output.put_line('=============================================');
END;
/
output:
Info of 7654
=============================================
Name of emp: MARTIN
Salary of emp: 1250
Designition of emp: SALESMAN
Join date of emp: 28-SEP-81
Commission of emp: 1400
Deptno of emp: 30
=============================================
Ex:
Write a program to display number of male customers and number
of female customers?
DINESH PV
Oracle Trainer
declare
male_cnt int;
female_cnt int;
begin
select count(*) into male_cnt from cust_dtls where gender='M';
select count(*) into female_cnt from cust_dtls where gender='F';
dbms_output.put_line(' Number of males= '||male_cnt);
dbms_output.put_line(' Number of Females='||female_cnt);
end;
Assignments:
2) Write a program to display the city and mobile number of customer id " cust-5"?
Dynamic Progarms:
By using & (Substitution operator) operator we will make a program as a dynamic program.
Instead of assigning a constant value in to a variable, While the execution of the program,
the program has to take a value from the end user and that value stored it into a variable.
Varname := '&varname';
Ex:
write a program to display the details of employee for the given empno?
declare
v_eno number(4);
DINESH PV
Oracle Trainer
v_ename varchar2(20);
v_sal number(5);
v_job varchar2(20);
v_jdate date;
v_comm number(5);
V_dno int;
BEGIN
v_eno:='&v_eno';
select ename,sal,job,hiredate,nvl(comm,0),deptno
INTO
v_ename,v_sal,v_job,v_jdate,v_comm,v_dno
from emp where empno=v_eno;
dbms_output.put_line
(chr(10)||' Details of emp id: '||v_eno||chr(10)||
'-----------------------------------------'||chr(10)||
'Name: '||v_ename||chr(10)||
'Working with Salary: '||v_sal||chr(10)||
'Working as : '||v_job||chr(10)||
'Joined on: '||v_jdate||chr(10)||
'Getting Commission: '||v_comm||chr(10)||
'Working under: '||v_dno
);
end;
Ex:
Write a program to display the number of emps in the given deptno?
DINESH PV
Oracle Trainer
declare
vdno number(2);
e_count int;
begin
vdno:='&vdno';
select count(empno) into e_count
from emp
where deptno=vdno;
dbms_output.put_line
(' number of emps in Department : '||vdno||' = '||e_count);
end;
output:
number of emps in 20 = 5
Assignment:
1) write a program to display the total salary i am paying to deptno 30 employees?
2) write a program to display the "number of male customers" from the given city?
3) Write a program to display the number of emps working under given deptno?
4) write a program to find the number of emps working with given designition?
5) Write a program to find and display total salary paying to given dept name?
VARIABLE TYPES
In PLSQL, we have 3 types of variables.
They are
a) Scalar Variable
DINESH PV
Oracle Trainer
b) Composite Variable
c) Collection Type Variable
i) Scalar variable
It is able to store one value at a time. We can declare scalar variables using 2 methods.
a) var datatype(size);
In this method of declaration, sometimes we will get size and datatype incompatibility
issues. These issues are eliminated as follows.
b)
%TYPE
we can declare any scalar variable with column datatype. By this method, we will not get
any data type and size related errors in future.
syntax
var TableName.ColumnName%TYPE;
Ex:
vdno emp.deptno%TYPE;
ii)Composite variable
A variable which is able to store one record at a time. It can decrease number of variable
declarations. It is decreasing length of program and execution time.
Composite variables are 2 types.
a) Store a record from single table. [%ROWTYPE]
b) Store a record from multiple tables. [TYPE]
%ROWTYPE
It is used to declare a variable as a RECORD type variable. It will store one record from one
table.
ADVANTAGE: It is decreasing number of variable declarations.
syntax
varname tblname%ROWTYPE;
Ex:
vemprec emp%rowtype;
DINESH PV
Oracle Trainer
var_name . colname;
Ex:
Write a program to display the information of employee for the given employee id?
declare
--Dynamic declaration of variable
veno emp.empno%type;
--Declaring table based record type variable
e_rec emp%rowtype;
begin
veno:='&veno';
select * into e_rec from emp
where empno=veno;
dbms_output.put_line
(chr(10)||' Emp id: '||veno||chr(10)||
'****************************'||chr(10)||
'Name: '||e_rec.ename||chr(10)||
'Desg: '||e_rec.job||chr(10)||
'Salary: '||e_rec.sal||chr(10)||
'Join Dt: '||e_rec.hiredate||chr(10)||
'Comm: '||e_rec.comm||chr(10)||
'Deptno: '||e_rec.deptno||chr(10)||
'*****************************'
DINESH PV
Oracle Trainer
);
end;
Ex: write a program to display the information of product for the given product id?
declare
vpid prod_dtls.prod_code%type;
p_rec prod_dtls%rowtype;
begin
vpid:='&vpid';
select * into p_rec
from prod_dtls
where prod_code=vpid;
dbms_output.put_line
(chr(10)||' Information of prodid: '||vpid||chr(10)||
p_rec.prod_name||chr(10)||
p_rec.cost||chr(10)||
p_rec.mfg||chr(10)||
p_rec.warrenty||chr(10)||
p_rec.comp_code
);
end;
SUB PROGRAMS
Database programs which are saved under database server permanently.
Sub programs are 2 types.
They are
1) PROCEDURES
2) FUNCTIONS
DINESH PV
Oracle Trainer
/* Procedure body */
<declaration stmts>;
BEGIN
-----
-----
EXCEPTION
--
--
END <proc_name>;
/ ( to compile the procedure in SQL * PLUS)
Procedure created.
HOW TO EXECUTE A PROCEDURE?
DINESH PV
Oracle Trainer
Arguments
It is known as a variable to receive runtime input value or to return output value.
Arguments are 3 types
IN
OUT
IN OUT
By default, arguments are IN type arguments, that is receive input value.
Ex: write a procedure to display customer 1 account details?
CREATE PROCEDURE PROC_CUST_ACT
IS
cust_rec cust_act_dtls%rowtype;
begin
select * into cust_rec from cust_act_dtls where cno='cust-1';
dbms_output.put_line
(chr(10)||
'Actno: '||cust_rec.actno||chr(10)||
DINESH PV
Oracle Trainer
'Act_type: '||cust_rec.act_type||chr(10)||
'Open Dt: '||cust_rec.act_open_date||chr(10)||
'Balance: '||cust_rec.act_bal
);
end proc_cust_act;
/ ( To Compile Procedure )
Ex:
Write a procedure to find number of customers from the city "Delhi"?
create or replace procedure proc_cust_cnt_delhi
is
vcnt int;
begin
select count(*) into vcnt
from cust_dtls where city='Delhi';
dbms_output.put_line
(chr(10)||
'City: Delhi'||chr(10)||
'Customer Count: '||vcnt
);
end;
BEGIN
proc_ecount_30; --Procedure calling stmt
DINESH PV
Oracle Trainer
DYNAMIC PROCEDURES
WRITING THE PROCEDURE TO DISPLAY THE NUMBER OF EMPS IN THE
GIVEN DEPTNO?
SAMPLE EXECUTIONS:
EXEC PROC_2(10);
EXEC PROC_2(20);
EXEC PROC_2(30);
DINESH PV
Oracle Trainer
EXCEPTIONS
Exception is a PLSQL runtime error. It is handled by programmer to display user friendly
error message.
Default oracle error format is
ERROR:
ORA-xxxxxx: <message>
<error code>: <error message >
DINESH PV
Oracle Trainer
SQLCODE SQLERRM
Exceptions are raised under begin block.
Exceptions are handled under Exception Block.
Each exception will be handled with one " when clause ", under exception block.
It will be raised if there exist datatype or size mismatch between variable and value.
vi) CASE_NOT_FOUND
It will be raised if case structure don't has matched case and and don't has ELSE part.
EXAMPLE PROCEDURES
Ex: Write a procedure to display employee name and job for the given salary?
EXEC PROC_NO_EXCEP(5000);
EXEC PROC_NO_EXCEP(800);
EXEC PROC_NO_EXCEP(10000);
VNAME EMP.ENAME%TYPE;
VJOB EMP.JOB%TYPE;
BEGIN
SELECT ename,job INTO vname,vjob
from emp
where sal=vsal;
dbms_output.put_line
(CHR(10)||
'Name of emp: '||vname||CHR(10)||
'Job of emp: '||vjob
);
dbms_output.put_line('<---- End of procedure ----> ');
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE(CHR(10)||' SAL IS DUPLICATED');
DBMS_OUTPUT.PUT_LINE
(CHR(10)||' selecting data from multiple records
is not yet possible without using cursors');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
(CHR(10)||'No emp Getting the salary'||vsal);
end proc_excep;
Ex:
write a procedure to display employee details who is
working with given designition?
sample outputs:
anonymous block completed
MULTIPLE EMPS WORKING LIKE SALESMAN
ex:
when comm_miss then
dbms_output.put_line(' comm value is null');
dbms_output.put_line
(chr(10)||' No employee with given id: '||veno);
when Too_many_rows then
dbms_output.put_line
(chr(10)||' Duplicate empid existed');
when comm_miss then
dbms_output.put_line
(chr(10)||' Employee not getting commission ');
end proc_emp_comm;
sample output:
FUNCTIONS
It is database object Like Procedure. It is also known as a sub program. By default, It should
return a value to the calling object. In pl/sql the functions are known as User Defined
Functions (UDF). Generally, functions are created based on common logic.
PLSQL functions are always executed by calling function.
Syntax:
var:=func_name(arg_val_1, arg_val_2,.....);
Function has 2 parts. That is Specification and Body.
syntax:
/*Spec*/
create or replace function <func_name> ( argvar datatype, argvar datatype...... )
RETURN <value_datatype>
IS
/*body*/
<declaration stmts>;
begin
-----
RETURN(value/var_name);
END <func_name>;
/ [ to compile function in SQL * PLUS ]
Z int;
begin
Z:=x+y;
return(Z);
end f_add;
Note:
A Function can be called through any SELECT or PROGRAM or Procedure
or packages.
Ex: select f_add(100,200) from dual;
300
Ex: write a procedure to display empid, sal, bonus and total salary (sal+ bonus) for the given
employee id?
Ex: Write a procedure to display above details for all employees?
Ex: Write a procedure to display above details for the given job category of emps?
[ Common Functionality is " Finding Bonus Based on salary Range" ]
Bonus is to be calculated as follows
sal<1000 2%
>=1000 & < 2000 5%
>=2000 & < 3000 10%
>=3000 & < 5000 20%
>=5000 25%
Creating a function to calculate the Bonus?
create or replace function func_bonus (s IN emp.sal%type)
return number
is
vbonus number(7,2);
begin
if (s <1000) then
vbonus:=0.02*s;
DINESH PV
Oracle Trainer
dbms_output.put_line
(chr(10)||
' The salary details of: '||veno||chr(10)||
'----------------------------------------------------'||chr(10)||
'EMPID salary bonus Total salary'||chr(10)||
'----------------------------------------------------'||chr(10)||
veno||' '|| vsal||' '||b||' '||tsal
);
end proc_emp_fsal;
/
--Procedure to display empid, salary, bonus and total salary for all emps?
dbms_output.put_line
(veno ||' '||vsal||' '||b||' '||tsal);
END LOOP;
CLOSE c;
end proc_emps_fsal;
/
-->write a procedure to display empid, sal, bonus and total salary for all emps
--> under given job category?
tsal := vsal+b;
exit when (c%notfound);
dbms_output.put_line
(veno ||' '||vsal||' '||b||' '||tsal);
end loop;
close c;
end proc_emps_fsal_job;
/
PACKAGES
Package is a data base object. It is useful to group related objects logically. It will reduce
search time for required procedure or function. Packages also reduce disk I/O Operations ,
by loading all objects into buffer area.
Package has 2 parts.
🡪 Specification
🡪 Body
These parts are created separately.
1) package specification:
It contains procedure and function calling stmts and also variables. The variables declared in
the package are known as Global Variables, Since these variables are accessible to all
procedures and functions within the package.
syn-1: package specification
create or replace package <pkg_name>
AS
<variable declarations>;
DINESH PV
Oracle Trainer
is
--
--
end <proc-2>;
Function <func-1>(.....)
return <datatype>
is
--
--
end <func-1>;
DINESH PV
Oracle Trainer
end <pkg_name>;
/ [ to compile package body ]
Ex:
write a package which contains the procedures and functions to
calculate sal, bonus, final salaries for given empid , for all emps
and for given job category employees?
is
vsal emp.sal%type;
b number(7,2);
fsal number(7,2);
begin
select sal into vsal from emp where empno=veno;
b:=func_bonus(vsal); /* function calling stmt */
fsal:=vsal+b;
dbms_output.put_line(' The salary details of '||veno);
dbms_output.put_line('----------------------------------------------------');
dbms_output.put_line('salary bonus final salary');
dbms_output.put_line( vsal||' '||b||' '||fsal);
end proc_emp_fsal;
bonus:=0.10*s;
end if;
if (s>=3000 and s<5000) then
bonus:=0.20*s;
end if;
if (s>=5000) then
bonus:=0.25*s;
end if;
return(bonus);
end func_bonus;
Procedure proc_emps_fsal
is
cursor c is select empno,sal from emp;
veno emp.empno%type;
vsal emp.sal%type;
b number(7,2);
fsal number(7,2);
begin
open c;
dbms_output.put_line
('----------------------------------------------------');
dbms_output.put_line
('salary bonus final salary');
dbms_output.put_line
('*************************************************');
DINESH PV
Oracle Trainer
loop
fetch c into veno,vsal;
dbms_output.put_line(' The salary details of '||veno);
b:=func_bonus(vsal); /* function calling stmt */
fsal:=vsal+b;
EXIT WHEN (C%NOTFOUND);
dbms_output.put_line(vsal||' '||b||' '||fsal);
END LOOP;
CLOSE C;
end proc_emps_fsal;
/* procedure proc_emps_fsal_job */
procedure proc_emps_fsal_job(vjob emp.job%type)
is
cursor c is select empno,sal from emp where job=vjob;
vsal emp.sal%type;
veno emp.empno%type;
incrval number(7,2);
fsal number(7,2);
begin
open c;
loop
fetch c into veno,vsal;
incrval:=func_bonus(vsal); /* function calling stmt */
fsal:=vsal+incrval;
EXIT WHEN c%NOTFOUND;
dbms_output.put_line(' sal,incrval,final salary of '||veno);
dbms_output.put_line(vsal||' , '||incrval||' , '||fsal);
end loop;
DINESH PV
Oracle Trainer
close c;
end proc_emps_fsal_job;
END emppkg;
IQ:
What is a Local Procedure ?
If you created any procedure inside the package,
then it is known as local procedure.
This procedure not available outside the package.
TRIGGERS
TRIGGER is a data base object like a procedure to perform back ground task.
Triggers are executed automatically without EXEC statement or calling statement.
Triggers are defined at 3 levels.
1) DDL level triggers
DINESH PV
Oracle Trainer
syntax:
create or replace trigger <trig_name>
[before / after]
[ insert / update / delete ]
ON <table name>
[FOR EACH ROW]
declare
------
------
BEGIN
------------
------------
END <trig_name>;
/ [ to compile the trigger in sql * plus ]
trigger created.
ex: table
create table employee
(
ename varchar2(20),
city varchar2(20)
);
ENAME CITY
-------------------- --------------------
Kiran Delhi
madhu Delhi
DINESH HYD
smith texas
Ex:
write a trigger to insert or update the data of employee in
upper case?
/
DINESH PV
Oracle Trainer